KiCad PCB EDA Suite
common.h File Reference

The common library. More...

#include <vector>
#include <wx/wx.h>
#include <wx/confbase.h>
#include <wx/fileconf.h>
#include <wx/dir.h>
#include <richio.h>
#include <gal/color4d.h>
#include <atomic>
#include <memory>
#include "make_unique.h"

Go to the source code of this file.

Classes

class  LOCALE_IO
 Instantiate the current locale within a scope in which you are expecting exceptions to be thrown. More...
 
struct  std::hash< wxString >
 
struct  std::hash< wxPoint >
 
struct  std::less< wxPoint >
 
class  WX_FILENAME
 A wrapper around a wxFileName which is much more performant with a subset of the API. More...
 

Namespaces

 std
 

Template specialization to enable wxStrings for certain containers (e.g. unordered_map)


 

Macros

#define INCLUDE__COMMON_H_
 
#define EDA_KEY_C   UINT32_C
 
#define GR_KB_RIGHTSHIFT   ( EDA_KEY_C( 0x01000000 ) )
 
#define GR_KB_LEFTSHIFT   ( EDA_KEY_C( 0x02000000 ) )
 
#define GR_KB_CTRL   ( EDA_KEY_C( 0x04000000 ) )
 
#define GR_KB_ALT   ( EDA_KEY_C( 0x08000000 ) )
 
#define GR_KB_SHIFT   ( GR_KB_LEFTSHIFT | GR_KB_RIGHTSHIFT )
 
#define GR_KB_SHIFTCTRL   ( GR_KB_SHIFT | GR_KB_CTRL )
 
#define MOUSE_MIDDLE   ( EDA_KEY_C( 0x10000000 ) )
 
#define GR_KEY_INVALID   ( EDA_KEY_C( 0x80000000 ) )
 
#define GR_KEY_NONE   ( EDA_KEY_C( 0 ) )
 
#define NAMELESS_PROJECT   wxT( "noname" )
 
#define ESC   27
 
#define TEXT_ANGLE_HORIZ   0
 
#define TEXT_ANGLE_VERT   900
 
#define KIROUND(v)   int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 )
 
#define USE_KICAD_WXSTRING_HASH
 
#define USE_KICAD_WXPOINT_LESS_AND_HASH
 
#define EDA_KEY_C   UINT32_C
 
#define GR_KB_RIGHTSHIFT   ( EDA_KEY_C( 0x01000000 ) )
 
#define GR_KB_LEFTSHIFT   ( EDA_KEY_C( 0x02000000 ) )
 
#define GR_KB_CTRL   ( EDA_KEY_C( 0x04000000 ) )
 
#define GR_KB_ALT   ( EDA_KEY_C( 0x08000000 ) )
 
#define GR_KB_SHIFT   ( GR_KB_LEFTSHIFT | GR_KB_RIGHTSHIFT )
 
#define GR_KB_SHIFTCTRL   ( GR_KB_SHIFT | GR_KB_CTRL )
 
#define MOUSE_MIDDLE   ( EDA_KEY_C( 0x10000000 ) )
 
#define GR_KEY_INVALID   ( EDA_KEY_C( 0x80000000 ) )
 
#define GR_KEY_NONE   ( EDA_KEY_C( 0 ) )
 
#define NAMELESS_PROJECT   wxT( "noname" )
 default name for nameless projects More...
 
#define ESC   27
 
#define TEXT_ANGLE_HORIZ   0
 Frequent text rotations, used with {Set,Get}TextAngle(), in 0.1 degrees for now, hoping to migrate to degrees eventually. More...
 
#define TEXT_ANGLE_VERT   900
 
#define KIROUND(v)   int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 )
 KIROUND: a macro so compiler can pre-compute constants. More...
 
#define USE_KICAD_WXSTRING_HASH
 
#define USE_KICAD_WXPOINT_LESS_AND_HASH
 Required to use wxPoint as key type in maps. More...
 

Typedefs

typedef uint32_t timestamp_t
 timestamp_t is our type to represent unique IDs for all kinds of elements; historically simply the timestamp when they were created. More...
 
typedef uint32_t EDA_KEY
 

Enumerations

enum  pseudokeys {
  EDA_PANNING_UP_KEY = 1, EDA_PANNING_DOWN_KEY, EDA_PANNING_LEFT_KEY, EDA_PANNING_RIGHT_KEY,
  EDA_ZOOM_IN_FROM_MOUSE, EDA_ZOOM_OUT_FROM_MOUSE, EDA_ZOOM_CENTER_FROM_MOUSE
}
 Pseudo key codes for command panning. More...
 
enum  EDA_UNITS_T {
  INCHES = 0, MILLIMETRES = 1, UNSCALED_UNITS = 2, DEGREES = 3,
  PERCENT = 4
}
 

Functions

static int KiROUND (double v)
 Round a floating point number to an integer using "round halfway cases away from zero". More...
 
wxSize GetTextSize (const wxString &aSingleLine, wxWindow *aWindow)
 Return the size of aSingleLine of text when it is rendered in aWindow using whatever font is currently set in that window. More...
 
bool EnsureTextCtrlWidth (wxTextCtrl *aCtrl, const wxString *aString=NULL)
 Set the minimum pixel width on a text control in order to make a text string be fully visible within it. More...
 
void SelectReferenceNumber (wxTextEntry *aTextEntry)
 Select the number (or "?") in a reference for ease of editing. More...
 
int ProcessExecute (const wxString &aCommandLine, int aFlags=wxEXEC_ASYNC, wxProcess *callback=NULL)
 Run a command in a child process. More...
 
timestamp_t GetNewTimeStamp ()
 
int GetCommandOptions (const int argc, const char **argv, const char *stringtst, const char **optarg, int *optind)
 
double RoundTo0 (double x, double precision)
 Round to the nearest precision. More...
 
void wxStringSplit (const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
 Split aString to a string list separated at aSplitter. More...
 
wxString SearchHelpFileFullPath (const SEARCH_STACK &aSearchStack, const wxString &aBaseName)
 Return the help file's full path. More...
 
bool EnsureFileDirectoryExists (wxFileName *aTargetFullFileName, const wxString &aBaseFilename, REPORTER *aReporter=NULL)
 Make aTargetFullFileName absolute and create the path of this file if it doesn't yet exist. More...
 
const wxString PrePendPath (const wxString &aEnvVar, const wxString &aPriorityPath)
 Put aPriorityPath in front of all paths in the value of aEnvVar. More...
 
std::unique_ptr< wxConfigBase > GetNewConfig (const wxString &aProgName)
 Create a new wxConfig so we can put configuration files in a more proper place for each platform. More...
 
wxString GetKicadConfigPath ()
 Return the user configuration path used to store KiCad's configuration files. More...
 
const wxString ExpandEnvVarSubstitutions (const wxString &aString)
 Replace any environment variable references with their values. More...
 
const wxString ResolveUriByEnvVars (const wxString &aUri)
 Replace any environment variables in file-path uris (leaving network-path URIs alone). More...
 
std::ostream & operator<< (std::ostream &out, const wxSize &size)
 Helper function to print the given wxSize to a stream. More...
 
std::ostream & operator<< (std::ostream &out, const wxPoint &pt)
 Helper function to print the given wxPoint to a stream. More...
 
long long TimestampDir (const wxString &aDirPath, const wxString &aFilespec)
 A copy of ConvertFileTimeToWx() because wxWidgets left it as a static function private to src/common/filename.cpp. More...
 

Variables

KIGFX::COLOR4D g_GhostColor
 Draw color for moving objects. More...
 

Detailed Description

The common library.

Definition in file common.h.

Macro Definition Documentation

◆ EDA_KEY_C [1/2]

#define EDA_KEY_C   UINT32_C

◆ EDA_KEY_C [2/2]

#define EDA_KEY_C   UINT32_C

Definition at line 72 of file common.h.

◆ ESC [1/2]

#define ESC   27

◆ ESC [2/2]

#define ESC   27

Definition at line 99 of file common.h.

◆ GR_KB_ALT [1/2]

#define GR_KB_ALT   ( EDA_KEY_C( 0x08000000 ) )

Definition at line 77 of file common.h.

◆ GR_KB_ALT [2/2]

#define GR_KB_ALT   ( EDA_KEY_C( 0x08000000 ) )

◆ GR_KB_CTRL [1/2]

#define GR_KB_CTRL   ( EDA_KEY_C( 0x04000000 ) )

◆ GR_KB_CTRL [2/2]

#define GR_KB_CTRL   ( EDA_KEY_C( 0x04000000 ) )

Definition at line 76 of file common.h.

◆ GR_KB_LEFTSHIFT [1/2]

#define GR_KB_LEFTSHIFT   ( EDA_KEY_C( 0x02000000 ) )

Definition at line 75 of file common.h.

◆ GR_KB_LEFTSHIFT [2/2]

#define GR_KB_LEFTSHIFT   ( EDA_KEY_C( 0x02000000 ) )

◆ GR_KB_RIGHTSHIFT [1/2]

#define GR_KB_RIGHTSHIFT   ( EDA_KEY_C( 0x01000000 ) )

Definition at line 74 of file common.h.

◆ GR_KB_RIGHTSHIFT [2/2]

#define GR_KB_RIGHTSHIFT   ( EDA_KEY_C( 0x01000000 ) )

◆ GR_KB_SHIFT [1/2]

#define GR_KB_SHIFT   ( GR_KB_LEFTSHIFT | GR_KB_RIGHTSHIFT )

Definition at line 78 of file common.h.

◆ GR_KB_SHIFT [2/2]

#define GR_KB_SHIFT   ( GR_KB_LEFTSHIFT | GR_KB_RIGHTSHIFT )

◆ GR_KB_SHIFTCTRL [1/2]

#define GR_KB_SHIFTCTRL   ( GR_KB_SHIFT | GR_KB_CTRL )

◆ GR_KB_SHIFTCTRL [2/2]

#define GR_KB_SHIFTCTRL   ( GR_KB_SHIFT | GR_KB_CTRL )

Definition at line 79 of file common.h.

◆ GR_KEY_INVALID [1/2]

#define GR_KEY_INVALID   ( EDA_KEY_C( 0x80000000 ) )

◆ GR_KEY_INVALID [2/2]

#define GR_KEY_INVALID   ( EDA_KEY_C( 0x80000000 ) )

Definition at line 81 of file common.h.

◆ GR_KEY_NONE [1/2]

#define GR_KEY_NONE   ( EDA_KEY_C( 0 ) )

◆ GR_KEY_NONE [2/2]

#define GR_KEY_NONE   ( EDA_KEY_C( 0 ) )

Definition at line 82 of file common.h.

◆ INCLUDE__COMMON_H_

#define INCLUDE__COMMON_H_

Definition at line 34 of file numeric_evaluator.cpp.

◆ KIROUND [1/2]

#define KIROUND (   v)    int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 )

◆ KIROUND [2/2]

#define KIROUND (   v)    int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 )

KIROUND: a macro so compiler can pre-compute constants.

Use this with compile time constants rather than the inline function above.

Definition at line 125 of file common.h.

◆ MOUSE_MIDDLE [1/2]

#define MOUSE_MIDDLE   ( EDA_KEY_C( 0x10000000 ) )

Definition at line 80 of file common.h.

◆ MOUSE_MIDDLE [2/2]

#define MOUSE_MIDDLE   ( EDA_KEY_C( 0x10000000 ) )

◆ NAMELESS_PROJECT [1/2]

#define NAMELESS_PROJECT   wxT( "noname" )

default name for nameless projects

Definition at line 85 of file common.h.

◆ NAMELESS_PROJECT [2/2]

#define NAMELESS_PROJECT   wxT( "noname" )

◆ TEXT_ANGLE_HORIZ [1/2]

#define TEXT_ANGLE_HORIZ   0

◆ TEXT_ANGLE_HORIZ [2/2]

#define TEXT_ANGLE_HORIZ   0

Frequent text rotations, used with {Set,Get}TextAngle(), in 0.1 degrees for now, hoping to migrate to degrees eventually.

Definition at line 103 of file common.h.

◆ TEXT_ANGLE_VERT [1/2]

#define TEXT_ANGLE_VERT   900

Definition at line 104 of file common.h.

◆ TEXT_ANGLE_VERT [2/2]

#define TEXT_ANGLE_VERT   900

◆ USE_KICAD_WXPOINT_LESS_AND_HASH [1/2]

#define USE_KICAD_WXPOINT_LESS_AND_HASH

Required to use wxPoint as key type in maps.

Definition at line 377 of file common.h.

◆ USE_KICAD_WXPOINT_LESS_AND_HASH [2/2]

#define USE_KICAD_WXPOINT_LESS_AND_HASH

◆ USE_KICAD_WXSTRING_HASH [1/2]

#define USE_KICAD_WXSTRING_HASH

◆ USE_KICAD_WXSTRING_HASH [2/2]

#define USE_KICAD_WXSTRING_HASH

Definition at line 365 of file common.h.

Typedef Documentation

◆ EDA_KEY

typedef uint32_t EDA_KEY

Definition at line 71 of file common.h.

◆ timestamp_t

typedef uint32_t timestamp_t

timestamp_t is our type to represent unique IDs for all kinds of elements; historically simply the timestamp when they were created.

Long term, this type might be renamed to something like unique_id_t (and then rename all the methods from {Get,Set}TimeStamp() to {Get,Set}Id()) ?

Definition at line 53 of file common.h.

Enumeration Type Documentation

◆ EDA_UNITS_T

Enumerator
INCHES 
MILLIMETRES 
UNSCALED_UNITS 
DEGREES 
PERCENT 

Definition at line 157 of file common.h.

157  {
158  INCHES = 0,
159  MILLIMETRES = 1,
160  UNSCALED_UNITS = 2,
161  DEGREES = 3,
162  PERCENT = 4,
163 };
Definition: common.h:158

◆ pseudokeys

enum pseudokeys

Pseudo key codes for command panning.

Enumerator
EDA_PANNING_UP_KEY 
EDA_PANNING_DOWN_KEY 
EDA_PANNING_LEFT_KEY 
EDA_PANNING_RIGHT_KEY 
EDA_ZOOM_IN_FROM_MOUSE 
EDA_ZOOM_OUT_FROM_MOUSE 
EDA_ZOOM_CENTER_FROM_MOUSE 

Definition at line 89 of file common.h.

Function Documentation

◆ EnsureFileDirectoryExists()

bool EnsureFileDirectoryExists ( wxFileName *  aTargetFullFileName,
const wxString &  aBaseFilename,
REPORTER aReporter = NULL 
)

Make aTargetFullFileName absolute and create the path of this file if it doesn't yet exist.

Parameters
aTargetFullFileNamethe wxFileName containing the full path and file name to modify. The path may be absolute or relative to aBaseFilename .
aBaseFilenamea full filename. Only its path is used to set the aTargetFullFileName path.
aReportera point to a REPORTER object use to show messages (can be NULL)
Returns
true if aOutputDir already exists or was successfully created.

Definition at line 485 of file common.cpp.

488 {
489  wxString msg;
490  wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
491 
492  // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
493  // already an absolute path) absolute:
494  if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
495  {
496  if( aReporter )
497  {
498  msg.Printf( _( "Cannot make path \"%s\" absolute with respect to \"%s\"." ),
499  GetChars( aTargetFullFileName->GetPath() ),
500  GetChars( baseFilePath ) );
501  aReporter->Report( msg, REPORTER::RPT_ERROR );
502  }
503 
504  return false;
505  }
506 
507  // Ensure the path of aTargetFullFileName exists, and create it if needed:
508  wxString outputPath( aTargetFullFileName->GetPath() );
509 
510  if( !wxFileName::DirExists( outputPath ) )
511  {
512  if( wxMkdir( outputPath ) )
513  {
514  if( aReporter )
515  {
516  msg.Printf( _( "Output directory \"%s\" created.\n" ), GetChars( outputPath ) );
517  aReporter->Report( msg, REPORTER::RPT_INFO );
518  return true;
519  }
520  }
521  else
522  {
523  if( aReporter )
524  {
525  msg.Printf( _( "Cannot create output directory \"%s\".\n" ),
526  GetChars( outputPath ) );
527  aReporter->Report( msg, REPORTER::RPT_ERROR );
528  }
529 
530  return false;
531  }
532  }
533 
534  return true;
535 }
#define _(s)
static const wxChar * GetChars(const wxString &s)
Function GetChars returns a wxChar* to the actual wxChar* data within a wxString, and is helpful for ...
Definition: macros.h:101
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_UNDEFINED)=0
Function Report is a pure virtual function to override in the derived object.

References _, GetChars(), REPORTER::Report(), REPORTER::RPT_ERROR, and REPORTER::RPT_INFO.

Referenced by DIALOG_GEN_FOOTPRINT_POSITION::CreateFiles(), DIALOG_PLOT_SCHEMATIC::createPlotFileName(), DIALOG_EXPORT_SVG::ExportSVGFile(), DIALOG_GENDRILL::GenDrillAndMapFiles(), PLOT_CONTROLLER::OpenPlotfile(), and DIALOG_PLOT::Plot().

◆ EnsureTextCtrlWidth()

bool EnsureTextCtrlWidth ( wxTextCtrl *  aCtrl,
const wxString *  aString = NULL 
)

Set the minimum pixel width on a text control in order to make a text string be fully visible within it.

The current font within the text control is considered. The text can come either from the control or be given as an argument. If the text control is larger than needed, then nothing is done.

Parameters
aCtrlthe text control to potentially make wider.
aStringthe text that is used in sizing the control's pixel width. If NULL, then the text already within the control is used.
Returns
bool - true if the aCtrl had its size changed, else false.

Definition at line 130 of file common.cpp.

131 {
132  wxWindow* window = aCtrl->GetParent();
133 
134  if( !window )
135  window = aCtrl;
136 
137  wxString ctrlText;
138 
139  if( !aString )
140  {
141  ctrlText = aCtrl->GetValue();
142  aString = &ctrlText;
143  }
144 
145  wxSize textz = GetTextSize( *aString, window );
146  wxSize ctrlz = aCtrl->GetSize();
147 
148  if( ctrlz.GetWidth() < textz.GetWidth() + 10 )
149  {
150  ctrlz.SetWidth( textz.GetWidth() + 10 );
151  aCtrl->SetSizeHints( ctrlz );
152  return true;
153  }
154 
155  return false;
156 }
wxSize GetTextSize(const wxString &aSingleLine, wxWindow *aWindow)
Return the size of aSingleLine of text when it is rendered in aWindow using whatever font is currentl...
Definition: common.cpp:115

References GetTextSize().

Referenced by GERBVIEW_FRAME::UpdateTitleAndInfo().

◆ ExpandEnvVarSubstitutions()

const wxString ExpandEnvVarSubstitutions ( const wxString &  aString)

Replace any environment variable references with their values.

Parameters
aString= a string containing (perhaps) references to env var
Returns
a string where env var are replaced by their value

Definition at line 458 of file common.cpp.

459 {
460  // wxGetenv( wchar_t* ) is not re-entrant on linux.
461  // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
462  static std::mutex getenv_mutex;
463 
464  std::lock_guard<std::mutex> lock( getenv_mutex );
465 
466  // We reserve the right to do this another way, by providing our own member function.
467  return KIwxExpandEnvVars( aString );
468 }
wxString KIwxExpandEnvVars(const wxString &str)
Definition: common.cpp:325

References KIwxExpandEnvVars().

Referenced by FILENAME_RESOLVER::addPath(), FILENAME_RESOLVER::checkEnvVarPath(), S3D_PLUGIN_MANAGER::checkPluginName(), S3D_PLUGIN_MANAGER::checkPluginPath(), FILENAME_RESOLVER::createPathList(), LIB_TABLE::ExpandSubstitutions(), S3D_CACHE::Get3DConfigDir(), WS_DATA_MODEL::MakeFullFileName(), TEXT_BUTTON_FILE_BROWSER::OnButtonClick(), FILENAME_RESOLVER::ResolvePath(), ResolveUriByEnvVars(), FILENAME_RESOLVER::Set3DConfigDir(), S3D_CACHE::Set3DConfigDir(), FILENAME_RESOLVER::SetProjectDir(), and FILENAME_RESOLVER::ShortenPath().

◆ GetCommandOptions()

int GetCommandOptions ( const int  argc,
const char **  argv,
const char *  stringtst,
const char **  optarg,
int *  optind 
)

◆ GetKicadConfigPath()

wxString GetKicadConfigPath ( )

Return the user configuration path used to store KiCad's configuration files.

The configuration path order of precedence is determined by the following criteria:

  • The value of the KICAD_CONFIG_HOME environment variable
  • The value of the XDG_CONFIG_HOME environment variable.
  • The result of the call to wxStandardPaths::GetUserConfigDir() with ".config" appended as required on Linux builds.
Returns
A wxString containing the config path for Kicad

Definition at line 267 of file common.cpp.

268 {
269  wxFileName cfgpath;
270 
271  // http://docs.wxwidgets.org/3.0/classwx_standard_paths.html#a7c7cf595d94d29147360d031647476b0
272  cfgpath.AssignDir( wxStandardPaths::Get().GetUserConfigDir() );
273 
274  // GetUserConfigDir() does not default to ~/.config which is the current standard
275  // configuration file location on Linux. This has been fixed in later versions of wxWidgets.
276 #if !defined( __WXMSW__ ) && !defined( __WXMAC__ )
277  wxArrayString dirs = cfgpath.GetDirs();
278 
279  if( dirs.Last() != ".config" )
280  cfgpath.AppendDir( ".config" );
281 #endif
282 
283  wxString envstr;
284 
285  // This shouldn't cause any issues on Windows or MacOS.
286  if( wxGetEnv( wxT( "XDG_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
287  {
288  // Override the assignment above with XDG_CONFIG_HOME
289  cfgpath.AssignDir( envstr );
290  }
291 
292  cfgpath.AppendDir( TO_STR( KICAD_CONFIG_DIR ) );
293 
294  // Use KICAD_CONFIG_HOME to allow the user to force a specific configuration path.
295  if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
296  {
297  // Override the assignment above with KICAD_CONFIG_HOME
298  cfgpath.AssignDir( envstr );
299  }
300 
301  if( !cfgpath.DirExists() )
302  {
303  cfgpath.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
304  }
305 
306  return cfgpath.GetPath();
307 }
#define TO_STR(x)
Definition: macros.h:56

References TO_STR.

Referenced by getAdvancedCfgFilename(), SYMBOL_LIB_TABLE::GetGlobalTableFileName(), FP_LIB_TABLE::GetGlobalTableFileName(), GetNewConfig(), ReadHotKeyConfig(), ReadLegacyHotkeyConfigFile(), and WriteHotKeyConfig().

◆ GetNewConfig()

std::unique_ptr<wxConfigBase> GetNewConfig ( const wxString &  aProgName)

Create a new wxConfig so we can put configuration files in a more proper place for each platform.

This is generally $HOME/.config/kicad/ in Linux according to the FreeDesktop specification at http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html The config object created here should be destroyed by the caller.

Parameters
aProgNameis the name of the program calling this function - can be obtained by calling Pgm().App().GetAppName(). This will be the actual file name of the config file.
Returns
A pointer to a new wxConfigBase derived object is returned. The caller is in charge of deleting it.

Definition at line 256 of file common.cpp.

257 {
258  wxFileName configname;
259  configname.AssignDir( GetKicadConfigPath() );
260  configname.SetFullName( aProgName );
261 
262  // explicitly use wxFileConfig to prevent storing any settings in the system registry on Windows
263  return std::make_unique<wxFileConfig>( wxT( "" ), wxT( "" ), configname.GetFullPath() );
264 }
wxString GetKicadConfigPath()
Return the user configuration path used to store KiCad's configuration files.
Definition: common.cpp:267

References GetKicadConfigPath().

Referenced by BIN_MOD::Init(), PGM_BASE::InitPgm(), PGM_BASE::loadCommonSettings(), and SYMBOL_PREVIEW_WIDGET::SYMBOL_PREVIEW_WIDGET().

◆ GetNewTimeStamp()

timestamp_t GetNewTimeStamp ( )
Returns
an unique time stamp that changes after each call

Definition at line 217 of file common.cpp.

218 {
219  static timestamp_t oldTimeStamp;
220  timestamp_t newTimeStamp;
221 
222  newTimeStamp = time( NULL );
223 
224  if( newTimeStamp <= oldTimeStamp )
225  newTimeStamp = oldTimeStamp + 1;
226 
227  oldTimeStamp = newTimeStamp;
228 
229  return newTimeStamp;
230 }
uint32_t timestamp_t
timestamp_t is our type to represent unique IDs for all kinds of elements; historically simply the ti...
Definition: common.h:53

Referenced by FOOTPRINT_VIEWER_FRAME::AddFootprintToPCB(), PCB_BASE_FRAME::AddModuleToBoard(), BOARD_NETLIST_UPDATER::addNewComponent(), SCH_EDIT_FRAME::AppendSchematic(), Diagnose(), SCH_DRAWING_TOOLS::DrawSheet(), SCH_EDIT_TOOL::Duplicate(), DIALOG_FOOTPRINT_BOARD_EDITOR::EditFootprint(), EDIT_TOOL::EditFpInFpEditor(), CONNECTION_GRAPH::ercCheckBusToBusConflicts(), CONNECTION_GRAPH::ercCheckBusToBusEntryConflicts(), CONNECTION_GRAPH::ercCheckBusToNetConflicts(), CONNECTION_GRAPH::ercCheckLabels(), CONNECTION_GRAPH::ercCheckNoConnects(), BOARD::InsertArea(), COLLECTOR::IsSimilarPointAndTime(), SCH_EAGLE_PLUGIN::loadSchematic(), SCH_LEGACY_PLUGIN::loadSheet(), EDA_ITEM::operator=(), SCH_EDITOR_CONTROL::Paste(), PCB_EDITOR_CONTROL::PlaceModule(), SCH_EDIT_TOOL::RepeatDrawItem(), SCH_SCREENS::ReplaceDuplicateTimeStamps(), CONNECTION_SUBGRAPH::ResolveDrivers(), FOOTPRINT_EDIT_FRAME::SaveFootprintToBoard(), SCH_COMPONENT::SCH_COMPONENT(), SCH_SHEET::SCH_SHEET(), COLLECTOR::SetTimeNow(), SimilarLabelsDiagnose(), TestDuplicateSheetNames(), DIALOG_ERC::TestErc(), and TestMultiunitFootprints().

◆ GetTextSize()

wxSize GetTextSize ( const wxString &  aSingleLine,
wxWindow *  aWindow 
)

Return the size of aSingleLine of text when it is rendered in aWindow using whatever font is currently set in that window.

Definition at line 115 of file common.cpp.

116 {
117  wxCoord width;
118  wxCoord height;
119 
120  {
121  wxClientDC dc( aWindow );
122  dc.SetFont( aWindow->GetFont() );
123  dc.GetTextExtent( aSingleLine, &width, &height );
124  }
125 
126  return wxSize( width, height );
127 }

Referenced by DIALOG_EDIT_COMPONENTS_LIBID::AdjustGridColumns(), DIALOG_FIELDS_EDITOR_GLOBAL::DIALOG_FIELDS_EDITOR_GLOBAL(), EDA_DRAW_FRAME::EDA_DRAW_FRAME(), EnsureTextCtrlWidth(), FIELDS_EDITOR_GRID_DATA_MODEL::GetDataWidth(), PL_EDITOR_FRAME::PL_EDITOR_FRAME(), DIALOG_FP_CONFLICT_ASSIGNMENT_SELECTOR::recalculateColumns(), PL_EDITOR_FRAME::ReCreateHToolbar(), ZONE_SETTINGS::SetupLayersList(), and NET_SELECTOR_COMBOPOPUP::updateSize().

◆ KiROUND()

static int KiROUND ( double  v)
inlinestatic

Round a floating point number to an integer using "round halfway cases away from zero".

In Debug build an assert fires if will not fit into an int.KiROUND: a function so v is not evaluated twice. Unfortunately, compiler is unable to pre-compute constants using this.

Definition at line 118 of file common.h.

119 {
120  return int( v < 0 ? v - 0.5 : v + 0.5 );
121 }

Referenced by ZONE_FILLER::addHatchFillTypeOnZone(), ZONE_FILLER::addKnockout(), PCAD2KICAD::PCB_POLYGON::AddToBoard(), DIMENSION::AdjustDimensionDetails(), GRID_HELPER::Align(), GRID_HELPER::AlignToSegment(), EC_45DEGREE::Apply(), PLOTTER::Arc(), HPGL_PLOTTER::Arc(), PDF_PLOTTER::Arc(), GERBER_PLOTTER::Arc(), PL_EDITOR_FRAME::BestZoom(), LEGACY_PLUGIN::biuParse(), D_PAD::boundingRadius(), build_pad_testpoints(), BuildCornersList_S_Shape(), D_PAD::BuildPadPolygon(), ZONE_FILLER::buildThermalSpokes(), LIB_ARC::CalcEdit(), LIB_ARC::CalcRadiusAngles(), PCAD2KICAD::CalculateTextLengthSize(), KIGFX::WX_VIEW_CONTROLS::CenterOnCursor(), DRC::checkClearancePadToPad(), EE_INSPECTION_TOOL::checkPart(), Clamp_Text_PenSize(), ClipAndDrawPoly(), computeCenter(), ConfigureHPGLPenSizes(), AM_PRIMITIVE::ConvertShapeToPolygon(), PCAD2KICAD::CorrectTextPosition(), PCB_EDIT_FRAME::Create_MuWaveComponent(), PCB_EDIT_FRAME::Create_MuWavePolygonShape(), SCH_GLOBALLABEL::CreateGraphicShape(), MWAVE::CreateMicrowaveInductor(), LIB_EDIT_TOOL::DeleteItemCursor(), PL_EDIT_TOOL::DeleteItemCursor(), SCH_EDIT_TOOL::DeleteItemCursor(), PCBNEW_CONTROL::DeleteItemCursor(), KIGFX::SCH_PAINTER::draw(), AM_PRIMITIVE::DrawBasicShape(), BITMAP_BASE::DrawBitmap(), KIGFX::OPENGL_GAL::DrawGrid(), KIGFX::CAIRO_GAL_BASE::DrawGrid(), GERBER_PLOTTER::emitDcode(), GERBER_FILE_IMAGE::ExecuteRS274XCommand(), HPGL_PLOTTER::FlashPadCircle(), HPGL_PLOTTER::FlashPadOval(), HPGL_PLOTTER::FlashPadRect(), HPGL_PLOTTER::FlashPadRoundRect(), FootprintWriteShape(), DSN::SPECCTRA_DB::FromSESSION(), gen_arc(), GENDRILL_WRITER_BASE::genDrillMapFile(), C3D_RENDER_OGL_LEGACY::generate_new_3DGrid(), geom_transf(), GERBER_DRAW_ITEM::GetABPosition(), GetArcCenter(), LIB_PIN::GetBoundingBox(), SCH_SHEET::GetBoundingBox(), GetClearanceBetweenSegments(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), WS_DATA_ITEM::GetEndPosUi(), SCH_SHEET::GetFileNamePosition(), GRID_HELPER::GetGrid(), KIGFX::GAL::GetGridPoint(), KIGFX::STROKE_FONT::getInterline(), EDA_TEXT::GetInterline(), BASE_SCREEN::getNearestGridPosition(), EE_SELECTION_TOOL::GetNode(), GetPenSizeForBold(), WS_DATA_ITEM::GetPenSizeUi(), WS_DATA_ITEM_POLYGONS::GetPenSizeUi(), WS_DATA_ITEM_TEXT::GetPenSizeUi(), LIB_CIRCLE::GetRadius(), DRAWSEGMENT::GetRadius(), SCH_SHEET::GetSheetNamePosition(), SCH_NO_CONNECT::GetSize(), BITMAP_BASE::GetSize(), D_PAD::GetSolderPasteMargin(), WS_DATA_ITEM::GetStartPosUi(), EDA_TEXT::GetTextBox(), GERBER_DRAW_ITEM::GetXYPosition(), GraphicTextWidth(), GRArc1(), ZONE_CONTAINER::Hatch(), LIB_CIRCLE::HitTest(), LIB_ARC::HitTest(), DRAWSEGMENT::HitTest(), D_PAD::HitTest(), DIALOG_PLOT::init_Dialog(), initializePlotter(), GENERAL_COLLECTOR::Inspect(), TRACK::IsPointOnEnds(), iu_to_d356(), EDA_TEXT::LenSize(), EAGLE_PLUGIN::Load(), EAGLE_PLUGIN::loadPolygon(), EAGLE_PLUGIN::loadSignals(), DSN::SPECCTRA_DB::makeIMAGE(), DSN::SPECCTRA_DB::makePADSTACK(), TRANSFORM::MapAngles(), PLOTTER::markerSquare(), Mils2mm(), GERBVIEW_PRINTOUT::milsToIU(), PCBNEW_PRINTOUT::milsToIU(), Mm2mils(), DIALOG_POSITION_RELATIVE::OnPolarChanged(), DIALOG_MOVE_EXACT::OnPolarChanged(), EAGLE_PLUGIN::packagePad(), EAGLE_PLUGIN::packagePolygon(), PCB_PLOT_PARAMS_PARSER::Parse(), PCAD2KICAD::PCB_ARC::Parse(), PCB_PARSER::parseBoardUnits(), parseInt(), GPCB_FPL_CACHE::parseMODULE(), BRDITEMS_PLOTTER::Plot_1_EdgeModule(), BRDITEMS_PLOTTER::PlotDrawSegment(), PS_PLOTTER::PlotImage(), PDF_PLOTTER::PlotImage(), PSLIKE_PLOTTER::postscriptOverlinePositions(), EDGE_MODULE::Print(), DRAWSEGMENT::Print(), GERBER_DRAW_ITEM::Print(), GERBER_FILE_IMAGE::ReadIJCoord(), PARAM_CFG_INT_WITH_SCALE::ReadParam(), EXCELLON_IMAGE::readToolInformation(), GERBER_FILE_IMAGE::ReadXYCoord(), PSLIKE_PLOTTER::returnPostscriptTextWidth(), RotatePoint(), RoundTo0(), DSN::scale(), scaletoIU(), PLOTTER::segmentAsOval(), SegmentIntersectsSegment(), PL_SELECTION_TOOL::SelectPoint(), EE_SELECTION_TOOL::SelectPoint(), WS_DATA_ITEM_TEXT::SetConstrainedTextSize(), PCAD2KICAD::SetTextSizeFromStrokeFontHeight(), PCAD2KICAD::SetTextSizeFromTrueTypeFontHeight(), snapAngle(), PS_PLOTTER::StartPlot(), PCAD2KICAD::StrToInt1Units(), PCAD2KICAD::StrToIntUnits(), WS_DATA_ITEM_TEXT::SyncDrawItems(), DRC::testDrilledHoles(), TestForIntersectionOfStraightLineSegments(), PS_PLOTTER::Text(), PDF_PLOTTER::Text(), AR_MATRIX::traceArc(), AR_MATRIX::traceCircle(), AR_MATRIX::TraceFilledRectangle(), DIALOG_TEXT_PROPERTIES::TransferDataFromWindow(), DIALOG_EDIT_COMPONENT_IN_LIBRARY::TransferDataFromWindow(), DIALOG_FOOTPRINT_BOARD_EDITOR::TransferDataFromWindow(), DIALOG_PAD_PRIMITIVES_TRANSFORM::Transform(), TransformOvalClearanceToPolygon(), TransformRoundedEndsSegmentToPolygon(), D_PAD::TransformShapeWithClearanceToPolygon(), DIALOG_PAGES_SETTINGS::UpdatePageLayoutExample(), USCALE(), ValueFromString(), and EXCELLON_WRITER::writeCoordinates().

◆ operator<<() [1/2]

std::ostream& operator<< ( std::ostream &  out,
const wxSize &  size 
)

Helper function to print the given wxSize to a stream.

Used for debugging functions like EDA_ITEM::Show and also in unit testing fixtures.

Definition at line 615 of file common.cpp.

616 {
617  out << " width=\"" << size.GetWidth() << "\" height=\"" << size.GetHeight() << "\"";
618  return out;
619 }

◆ operator<<() [2/2]

std::ostream& operator<< ( std::ostream &  out,
const wxPoint &  pt 
)

Helper function to print the given wxPoint to a stream.

Used for debugging functions like EDA_ITEM::Show and also in unit testing fixtures.

Definition at line 622 of file common.cpp.

623 {
624  out << " x=\"" << pt.x << "\" y=\"" << pt.y << "\"";
625  return out;
626 }

◆ PrePendPath()

const wxString PrePendPath ( const wxString &  aEnvVar,
const wxString &  aPriorityPath 
)

Put aPriorityPath in front of all paths in the value of aEnvVar.

Definition at line 32 of file prependpath.cpp.

33 {
34  wxPathList paths;
35 
36  paths.AddEnvList( aEnvVar );
37  paths.Insert( aPriorityPath, 0 );
38 
39  return wxJoin( paths, wxPATH_SEP[0] );
40 }

◆ ProcessExecute()

int ProcessExecute ( const wxString &  aCommandLine,
int  aFlags = wxEXEC_ASYNC,
wxProcess *  callback = NULL 
)

Run a command in a child process.

Parameters
aCommandLineThe process and any arguments to it all in a single string.
aFlagsThe same args as allowed for wxExecute()
callbackwxProcess implementing OnTerminate to be run when the child process finishes
Returns
int - pid of process, 0 in case of error (like return values of wxExecute())

Definition at line 211 of file common.cpp.

212 {
213  return wxExecute( aCommandLine, aFlags, callback );
214 }

Referenced by ExecuteFile(), GetAssociatedDocument(), OpenFile(), OpenPDF(), and SCH_EDIT_FRAME::WriteNetListFile().

◆ ResolveUriByEnvVars()

const wxString ResolveUriByEnvVars ( const wxString &  aUri)

Replace any environment variables in file-path uris (leaving network-path URIs alone).

Definition at line 471 of file common.cpp.

472 {
473  // URL-like URI: return as is.
474  wxURL url( aUri );
475 
476  if( url.GetError() == wxURL_NOERR )
477  return aUri;
478 
479  // Otherwise, the path points to a local file. Resolve environment
480  // variables if any.
481  return ExpandEnvVarSubstitutions( aUri );
482 }
const wxString ExpandEnvVarSubstitutions(const wxString &aString)
Replace any environment variable references with their values.
Definition: common.cpp:458

References ExpandEnvVarSubstitutions().

Referenced by GetAssociatedDocument().

◆ RoundTo0()

double RoundTo0 ( double  x,
double  precision 
)

Round to the nearest precision.

Try to approximate a coordinate using a given precision to prevent rounding errors when converting from inches to mm.

ie round the unit value to 0 if unit is 1 or 2, or 8 or 9

Definition at line 233 of file common.cpp.

234 {
235  assert( precision != 0 );
236 
237  long long ix = KiROUND( x * precision );
238 
239  if ( x < 0.0 )
240  ix = -ix;
241 
242  int remainder = ix % 10; // remainder is in precision mm
243 
244  if( remainder <= 2 )
245  ix -= remainder; // truncate to the near number
246  else if( remainder >= 8 )
247  ix += 10 - remainder; // round to near number
248 
249  if ( x < 0 )
250  ix = -ix;
251 
252  return (double) ix / precision;
253 }
static int KiROUND(double v)
Round a floating point number to an integer using "round halfway cases away from zero".
Definition: common.h:118

References KiROUND().

Referenced by SCH_BASE_FRAME::UpdateStatusBar().

◆ SearchHelpFileFullPath()

wxString SearchHelpFileFullPath ( const SEARCH_STACK aSearchStack,
const wxString &  aBaseName 
)

Return the help file's full path.

Return the KiCad help file with path and extension. Help files can be html (.html ext) or pdf (.pdf ext) files. A <BaseName>.html file is searched and if not found, <BaseName>.pdf file is searched in the same path. If the help file for the current locale is not found, an attempt to find the English version of the help file is made. Help file is searched in directories in this order: help/<canonical name> like help/en_GB help/<short name> like help/en help/en

Parameters
aSearchStackcontains some possible base dirs that may be above the the one actually holding aBaseName. These are starting points for nested searches.
aBaseNameis the name of the help file to search for,

without extension

.

Returns
wxEmptyString is returned if aBaseName is not found, else the full path & filename.

Definition at line 67 of file searchhelpfilefullpath.cpp.

68 {
69  wxArrayString subdirs;
70  wxArrayString altsubdirs;
71  SEARCH_STACK ss = aSStack;
72 
73  // It might already be in aSStack, but why depend on other code
74  // far away when it's so easy to add it again (to our copy) as the first place to look.
75 
76  // This is CMAKE_INSTALL_PREFIX unless DEFAULT_INSTALL_PATH was defined during
77  // build configuration:
78  ss.AddPaths( wxT( DEFAULT_INSTALL_PATH ), 0 );
79 
80 #if defined(__WXMAC__)
81  ss.AddPaths( GetOSXKicadMachineDataDir() );
82  ss.AddPaths( Pgm().GetExecutablePath(), 0 );
83 
84  // OS X packages can have the help files in
85  // /Library/Application\ Support/kicad/help,
86  // and in Contents/SharedSupport/help inside the
87  // bundle.
88  // Below we account for an international subdirectory.
89  subdirs.Add( "help" );
90  altsubdirs.Add( "Contents" );
91  altsubdirs.Add( "SharedSupport" );
92  altsubdirs.Add( "help" );
93 #endif
94 
95 #if ! defined(__WXMAC__) // && defined(__linux__)
96  // This is the executable path minus the trailing bin directory used on Windows and Linux.
97  wxFileName tmp( Pgm().GetExecutablePath(), wxEmptyString );
98  wxArrayString binDirs = tmp.GetDirs();
99 
100  if( !binDirs.IsEmpty() && binDirs[ binDirs.GetCount() - 1 ].CmpNoCase( wxT( "bin" ) ) == 0 )
101  tmp.RemoveLastDir();
102 
103  ss.AddPaths( tmp.GetPath(), 0 );
104 
105  // Based on kicad-doc.bzr/CMakeLists.txt, line 20, the help files are
106  // installed into "<CMAKE_INSTALL_PREFIX>/share/doc/kicad/help" for linux.
107  // This is ${KICAD_HELP} var in that CMakeLists.txt file.
108  // Below we account for an international subdirectory.
109  subdirs.Add( "share" );
110  subdirs.Add( "doc" );
111  subdirs.Add( "kicad" );
112  subdirs.Add( "help" );
113 
114  // Based on kicad-doc.bzr/CMakeLists.txt, line 35, the help files are
115  // installed into "<CMAKE_INSTALL_PREFIX>/doc/help" for Windows.
116  // This is ${KICAD_HELP} var in that CMakeLists.txt file.
117  // Below we account for an international subdirectory.
118  altsubdirs.Add( "doc" );
119  altsubdirs.Add( "help" );
120 #endif
121 
122  // If there's a KICAD environment variable set, always use that guy's path first.
123  if( !Pgm().GetKicadEnvVariable().IsEmpty() )
124  ss.AddPaths( Pgm().GetKicadEnvVariable(), 0 );
125 
126  /* Search for a help file.
127  * we *must* find a help file.
128  * so help is searched in directories in this order:
129  * help/<canonical name> like help/en_GB
130  * help/<short name> like help/en
131  * help/en
132  */
133 
134  wxLocale* i18n = Pgm().GetLocale();
135 
136  // We try to find help file in help/<canonical name>
137  // If fails, try to find help file in help/<short canonical name>
138  // If fails, try to find help file in help/en
139  wxArrayString locale_name_dirs;
140  locale_name_dirs.Add( i18n->GetCanonicalName() ); // canonical name like fr_FR
141 
142  // wxLocale::GetName() does not return always the short name
143  locale_name_dirs.Add( i18n->GetName().BeforeLast( '_' ) ); // short canonical name like fr
144  locale_name_dirs.Add( "en" ); // default (en)
145 
146 #if defined(DEBUG) && 1
147  ss.Show( wxString( __func__ ) );
148  wxLogTrace( tracePathsAndFiles, "%s: m_help_file:'%s'", __func__, aBaseName );
149 #endif
150 
151  wxLogTrace( tracePathsAndFiles, "Checking SEARCH_STACK for file %s", aBaseName );
152 
153  // Help files can be html (.html ext) or pdf (.pdf ext) files.
154  // Therefore, <BaseName>.html file is searched and if not found,
155  // <BaseName>.pdf file is searched in the same paths
156  wxString fn;
157 
158  for( unsigned ii = 0; ii < locale_name_dirs.GetCount(); ii++ )
159  {
160  subdirs.Add( locale_name_dirs[ii] );
161  altsubdirs.Add( locale_name_dirs[ii] );
162 
163  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".html" ), &altsubdirs );
164 
165  if( !fn.IsEmpty() )
166  {
167  // Prepend URI protocol since we will open in a browser
168  fn = wxT( "file://" ) + fn;
169  break;
170  }
171 
172  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".pdf" ), &altsubdirs );
173 
174  if( !fn.IsEmpty() )
175  break;
176 
177  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".html" ), &subdirs );
178 
179  if( !fn.IsEmpty() )
180  {
181  // Prepend URI protocol since we will open in a browser
182  fn = wxT( "file://" ) + fn;
183  break;
184  }
185 
186  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".pdf" ), &subdirs );
187 
188  if( !fn.IsEmpty() )
189  break;
190 
191  subdirs.RemoveAt( subdirs.GetCount() - 1 );
192  altsubdirs.RemoveAt( altsubdirs.GetCount() - 1 );
193  }
194 
195  return fn;
196 }
const wxChar *const tracePathsAndFiles
Flag to enable path and file name debug output.
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:65
Class SEARCH_STACK looks for files in a number of places.
Definition: search_stack.h:41
VTBL_ENTRY wxLocale * GetLocale()
Definition: pgm_base.h:231
wxString FindFileInSearchPaths(const SEARCH_STACK &aStack, const wxString &aFilename, const wxArrayString *aSubdirs)
Function FindFileInSearchPaths looks in "this" for aFilename, but first modifies every search path by...
void AddPaths(const wxString &aPaths, int aIndex=-1)
Function AddPaths insert or append path(s)

References SEARCH_STACK::AddPaths(), FindFileInSearchPaths(), PGM_BASE::GetLocale(), Pgm(), and tracePathsAndFiles.

◆ SelectReferenceNumber()

void SelectReferenceNumber ( wxTextEntry *  aTextEntry)

Select the number (or "?") in a reference for ease of editing.

Definition at line 159 of file common.cpp.

160 {
161  wxString ref = aTextEntry->GetValue();
162 
163  if( ref.find_first_of( '?' ) != ref.npos )
164  {
165  aTextEntry->SetSelection( ref.find_first_of( '?' ), ref.find_last_of( '?' ) + 1 );
166  }
167  else
168  {
169  wxString num = ref;
170 
171  while( !num.IsEmpty() && ( !isdigit( num.Last() ) || !isdigit( num.GetChar( 0 ) ) ) )
172  {
173  if( !isdigit( num.Last() ) )
174  num.RemoveLast();
175 
176  if( !isdigit( num.GetChar ( 0 ) ) )
177  num = num.Right( num.Length() - 1);
178  }
179 
180  aTextEntry->SetSelection( ref.Find( num ), ref.Find( num ) + num.Length() );
181 
182  if( num.IsEmpty() )
183  aTextEntry->SetSelection( -1, -1 );
184  }
185 }

Referenced by DIALOG_EDIT_ONE_FIELD::OnSetFocusText(), DIALOG_FOOTPRINT_BOARD_EDITOR::OnUpdateUI(), and DIALOG_TEXT_PROPERTIES::TransferDataToWindow().

◆ TimestampDir()

long long TimestampDir ( const wxString &  aDirPath,
const wxString &  aFilespec 
)

A copy of ConvertFileTimeToWx() because wxWidgets left it as a static function private to src/common/filename.cpp.

TimestampDir

This routine offers SIGNIFICANT performance benefits over using wxWidgets to gather timestamps from matching files in a directory.

Parameters
aDirPaththe directory to search
aFilespeca (wildcarded) file spec to match against
Returns
a hash of the last-mod-dates of all matching files in the directory

Definition at line 850 of file common.cpp.

851 {
852  long long timestamp = 0;
853 
854 #if defined( __WIN32__ )
855  // Win32 version.
856  // Save time by not searching for each path twice: once in wxDir.GetNext() and once in
857  // wxFileName.GetModificationTime(). Also cuts out wxWidgets' string-matching and case
858  // conversion by staying on the MSW side of things.
859  std::wstring filespec( aDirPath.t_str() );
860  filespec += '\\';
861  filespec += aFilespec.t_str();
862 
863  WIN32_FIND_DATA findData;
864  wxDateTime lastModDate;
865 
866  HANDLE fileHandle = ::FindFirstFile( filespec.data(), &findData );
867 
868  if( fileHandle != INVALID_HANDLE_VALUE )
869  {
870  do
871  {
872  ConvertFileTimeToWx( &lastModDate, findData.ftLastWriteTime );
873  timestamp += lastModDate.GetValue().GetValue();
874  }
875  while ( FindNextFile( fileHandle, &findData ) != 0 );
876  }
877 
878  FindClose( fileHandle );
879 #else
880  // POSIX version.
881  // Save time by not converting between encodings -- do everything on the file-system side.
882  std::string filespec( aFilespec.fn_str() );
883  std::string dir_path( aDirPath.fn_str() );
884 
885  DIR* dir = opendir( dir_path.c_str() );
886 
887  if( dir )
888  {
889  for( dirent* dir_entry = readdir( dir ); dir_entry; dir_entry = readdir( dir ) )
890  {
891  if( !matchWild( filespec.c_str(), dir_entry->d_name, true ) )
892  continue;
893 
894  std::string entry_path = dir_path + '/' + dir_entry->d_name;
895  struct stat entry_stat;
896 
897  wxCRT_Lstat( entry_path.c_str(), &entry_stat );
898 
899  // Timestamp the source file, not the symlink
900  if( S_ISLNK( entry_stat.st_mode ) ) // wxFILE_EXISTS_SYMLINK
901  {
902  char buffer[ PATH_MAX + 1 ];
903  ssize_t pathLen = readlink( entry_path.c_str(), buffer, PATH_MAX );
904 
905  if( pathLen > 0 )
906  {
907  buffer[ pathLen ] = '\0';
908  entry_path = dir_path + buffer;
909 
910  wxCRT_Lstat( entry_path.c_str(), &entry_stat );
911  }
912  }
913 
914  if( S_ISREG( entry_stat.st_mode ) ) // wxFileExists()
915  timestamp += entry_stat.st_mtime * 1000;
916  }
917 
918  closedir( dir );
919  }
920 #endif
921 
922  return timestamp;
923 }
bool matchWild(const char *pat, const char *text, bool dot_special)
A copy of wxMatchWild(), which wxWidgets attributes to Douglas A.
Definition: common.cpp:708

References matchWild().

Referenced by FP_CACHE::GetTimestamp(), and GPCB_FPL_CACHE::GetTimestamp().

◆ wxStringSplit()

void wxStringSplit ( const wxString &  aText,
wxArrayString &  aStrings,
wxChar  aSplitter 
)

Split aString to a string list separated at aSplitter.

Parameters
aTextis the text to split
aStringswill contain the splitted lines
aSplitteris the 'split' character

Definition at line 188 of file common.cpp.

189 {
190  wxString tmp;
191 
192  for( unsigned ii = 0; ii < aText.Length(); ii++ )
193  {
194  if( aText[ii] == aSplitter )
195  {
196  aStrings.Add( tmp );
197  tmp.Clear();
198  }
199 
200  else
201  tmp << aText[ii];
202  }
203 
204  if( !tmp.IsEmpty() )
205  {
206  aStrings.Add( tmp );
207  }
208 }

Referenced by CINFO3D_VISU::AddShapeWithClearanceToContainer(), export_vrml_pcbtext(), EDA_TEXT::GetTextBox(), HTML_MESSAGE_BOX::ListSet(), DIALOG_FOOTPRINT_WIZARD_LIST::onShowTrace(), SCH_TEXT::Plot(), BRDITEMS_PLOTTER::PlotTextePcb(), EDA_TEXT::Print(), TEXTE_PCB::TransformShapeWithClearanceToPolygonSet(), and EDA_TEXT::TransformTextShapeToSegmentList().

Variable Documentation

◆ g_GhostColor

KIGFX::COLOR4D g_GhostColor

Draw color for moving objects.

Draw color for moving objects.

TODO: All of these variables should be moved into the class were they are defined and used. Most of them probably belong in the application class.

Definition at line 58 of file common.cpp.