KiCad PCB EDA Suite
common.cpp File Reference
#include <fctsys.h>
#include <eda_base_frame.h>
#include <base_struct.h>
#include <common.h>
#include <macros.h>
#include <base_units.h>
#include <reporter.h>
#include <wx/process.h>
#include <wx/config.h>
#include <wx/utils.h>
#include <wx/stdpaths.h>
#include <wx/url.h>
#include <pgm_base.h>
#include <ki_mutex.h>

Go to the source code of this file.

Enumerations

enum  Bracket { Bracket_None, Bracket_Normal = ')', Bracket_Curly = '}', Bracket_Max }
 

Functions

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)
 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...
 
void wxStringSplit (const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
 Split aString to a string list separated at aSplitter. More...
 
int ProcessExecute (const wxString &aCommandLine, int aFlags, wxProcess *callback)
 Run a command in a child process. More...
 
timestamp_t GetNewTimeStamp ()
 
double RoundTo0 (double x, double precision)
 Round to the nearest precision. More...
 
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...
 
wxString KIwxExpandEnvVars (const wxString &str)
 
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...
 
bool EnsureFileDirectoryExists (wxFileName *aTargetFullFileName, const wxString &aBaseFilename, REPORTER *aReporter)
 Make aTargetFullFileName absolute and create the path of this file if it doesn't yet exist. More...
 
bool matchWild (const char *pat, const char *text, bool dot_special)
 A copy of wxMatchWild(), which wxWidgets attributes to Douglas A. 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

COLOR4D g_GhostColor
 Global variables definitions. More...
 

Enumeration Type Documentation

enum Bracket
Enumerator
Bracket_None 
Bracket_Normal 
Bracket_Curly 
Bracket_Max 

Definition at line 306 of file common.cpp.

307 {
308  Bracket_None,
309  Bracket_Normal = ')',
310  Bracket_Curly = '}',
311 #ifdef __WINDOWS__
312  Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
313 #endif
315 };

Function Documentation

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 469 of file common.cpp.

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().

472 {
473  wxString msg;
474  wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
475 
476  // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
477  // already an absolute path) absolute:
478  if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
479  {
480  if( aReporter )
481  {
482  msg.Printf( _( "Cannot make path \"%s\" absolute with respect to \"%s\"." ),
483  GetChars( aTargetFullFileName->GetPath() ),
484  GetChars( baseFilePath ) );
485  aReporter->Report( msg, REPORTER::RPT_ERROR );
486  }
487 
488  return false;
489  }
490 
491  // Ensure the path of aTargetFullFileName exists, and create it if needed:
492  wxString outputPath( aTargetFullFileName->GetPath() );
493 
494  if( !wxFileName::DirExists( outputPath ) )
495  {
496  if( wxMkdir( outputPath ) )
497  {
498  if( aReporter )
499  {
500  msg.Printf( _( "Output directory \"%s\" created.\n" ), GetChars( outputPath ) );
501  aReporter->Report( msg, REPORTER::RPT_INFO );
502  return true;
503  }
504  }
505  else
506  {
507  if( aReporter )
508  {
509  msg.Printf( _( "Cannot create output directory \"%s\".\n" ),
510  GetChars( outputPath ) );
511  aReporter->Report( msg, REPORTER::RPT_ERROR );
512  }
513 
514  return false;
515  }
516  }
517 
518  return true;
519 }
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:92
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_UNDEFINED)=0
Function Report is a pure virtual function to override in the derived object.
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 126 of file common.cpp.

References GetTextSize().

Referenced by GERBVIEW_FRAME::UpdateTitleAndInfo().

127 {
128  wxWindow* window = aCtrl->GetParent();
129 
130  if( !window )
131  window = aCtrl;
132 
133  wxString ctrlText;
134 
135  if( !aString )
136  {
137  ctrlText = aCtrl->GetValue();
138  aString = &ctrlText;
139  }
140 
141  wxSize textz = GetTextSize( *aString, window );
142  wxSize ctrlz = aCtrl->GetSize();
143 
144  if( ctrlz.GetWidth() < textz.GetWidth() + 10 )
145  {
146  ctrlz.SetWidth( textz.GetWidth() + 10 );
147  aCtrl->SetSizeHints( ctrlz );
148  return true;
149  }
150 
151  return false;
152 }
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:111
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 442 of file common.cpp.

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(), WORKSHEET_LAYOUT::MakeFullFileName(), TEXT_BUTTON_FILE_BROWSER::OnButtonClick(), FILENAME_RESOLVER::ResolvePath(), ResolveUriByEnvVars(), FILENAME_RESOLVER::Set3DConfigDir(), S3D_CACHE::Set3DConfigDir(), FILENAME_RESOLVER::SetProjectDir(), and FILENAME_RESOLVER::ShortenPath().

443 {
444  // wxGetenv( wchar_t* ) is not re-entrant on linux.
445  // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
446  static MUTEX getenv_mutex;
447 
448  MUTLOCK lock( getenv_mutex );
449 
450  // We reserve the right to do this another way, by providing our own member
451  // function.
452  return KIwxExpandEnvVars( aString );
453 }
wxString KIwxExpandEnvVars(const wxString &str)
Definition: common.cpp:321
boost::interprocess::interprocess_mutex MUTEX
Establish KiCad MUTEX choices here in this file: typedef MUTEX and typedef MUTLOCK.
Definition: ki_mutex.h:42
boost::interprocess::scoped_lock< MUTEX > MUTLOCK
Definition: ki_mutex.h:43
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 263 of file common.cpp.

Referenced by SYMBOL_LIB_TABLE::GetGlobalTableFileName(), FP_LIB_TABLE::GetGlobalTableFileName(), GetNewConfig(), ReadHotkeyConfigFile(), EDA_BASE_FRAME::WriteHotkeyConfig(), and CACHE_WRAPPER::~CACHE_WRAPPER().

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

References GetKicadConfigPath().

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

252 {
253  wxConfigBase* cfg = 0;
254  wxFileName configname;
255  configname.AssignDir( GetKicadConfigPath() );
256  configname.SetFullName( aProgName );
257 
258  cfg = new wxFileConfig( wxT( "" ), wxT( "" ), configname.GetFullPath() );
259  return cfg;
260 }
wxString GetKicadConfigPath()
Return the user configuration path used to store KiCad&#39;s configuration files.
Definition: common.cpp:263
timestamp_t GetNewTimeStamp ( )
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 111 of file common.cpp.

Referenced by DIALOG_EDIT_COMPONENTS_LIBID::AdjustGridColumns(), PCB_EDIT_FRAME::CreateTextePcb(), 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(), BOARD_DESIGN_SETTINGS::SetBoardThickness(), ZONE_SETTINGS::SetupLayersList(), TEXTE_PCB::TransformShapeWithClearanceToPolygonSet(), and NET_SELECTOR_COMBOPOPUP::updateSize().

112 {
113  wxCoord width;
114  wxCoord height;
115 
116  {
117  wxClientDC dc( aWindow );
118  dc.SetFont( aWindow->GetFont() );
119  dc.GetTextExtent( aSingleLine, &width, &height );
120  }
121 
122  return wxSize( width, height );
123 }
wxString KIwxExpandEnvVars ( const wxString &  str)

Definition at line 321 of file common.cpp.

References Bracket_Curly, Bracket_None, and Bracket_Normal.

Referenced by ExpandEnvVarSubstitutions().

322 {
323  size_t strlen = str.length();
324 
325  wxString strResult;
326  strResult.Alloc(strlen);
327 
328  for ( size_t n = 0; n < strlen; n++ ) {
329  wxUniChar str_n = str[n];
330 
331  switch ( str_n.GetValue() ) {
332 #ifdef __WINDOWS__
333  case wxT('%'):
334 #endif // __WINDOWS__
335  case wxT('$'):
336  {
337  Bracket bracket;
338 #ifdef __WINDOWS__
339  if ( str_n == wxT('%') )
340  bracket = Bracket_Windows;
341  else
342 #endif // __WINDOWS__
343  if ( n == strlen - 1 ) {
344  bracket = Bracket_None;
345  }
346  else {
347  switch ( str[n + 1].GetValue() ) {
348  case wxT('('):
349  bracket = Bracket_Normal;
350  str_n = str[++n]; // skip the bracket
351  break;
352 
353  case wxT('{'):
354  bracket = Bracket_Curly;
355  str_n = str[++n]; // skip the bracket
356  break;
357 
358  default:
359  bracket = Bracket_None;
360  }
361  }
362 
363  size_t m = n + 1;
364  wxUniChar str_m = str[m];
365 
366  while ( m < strlen && (wxIsalnum(str_m) || str_m == wxT('_')) )
367  str_m = str[++m];
368 
369  wxString strVarName(str.c_str() + n + 1, m - n - 1);
370 
371 #ifdef __WXWINCE__
372  const bool expanded = false;
373 #else
374  // NB: use wxGetEnv instead of wxGetenv as otherwise variables
375  // set through wxSetEnv may not be read correctly!
376  bool expanded = false;
377  wxString tmp;
378  if (wxGetEnv(strVarName, &tmp))
379  {
380  strResult += tmp;
381  expanded = true;
382  }
383  else
384 #endif
385  {
386  // variable doesn't exist => don't change anything
387 #ifdef __WINDOWS__
388  if ( bracket != Bracket_Windows )
389 #endif
390  if ( bracket != Bracket_None )
391  strResult << str[n - 1];
392  strResult << str_n << strVarName;
393  }
394 
395  // check the closing bracket
396  if ( bracket != Bracket_None ) {
397  if ( m == strlen || str_m != (wxChar)bracket ) {
398  // under MSW it's common to have '%' characters in the registry
399  // and it's annoying to have warnings about them each time, so
400  // ignroe them silently if they are not used for env vars
401  //
402  // under Unix, OTOH, this warning could be useful for the user to
403  // understand why isn't the variable expanded as intended
404 #ifndef __WINDOWS__
405  wxLogWarning(_("Environment variables expansion failed: missing '%c' at position %u in '%s'."),
406  (char)bracket, (unsigned int) (m + 1), str.c_str());
407 #endif // __WINDOWS__
408  }
409  else {
410  // skip closing bracket unless the variables wasn't expanded
411  if ( !expanded )
412  strResult << (wxChar)bracket;
413  str_m = str[++m];
414  }
415  }
416 
417  n = m - 1; // skip variable name
418  str_n = str[n];
419  }
420  break;
421 
422  case wxT('\\'):
423  // backslash can be used to suppress special meaning of % and $
424  if ( n != strlen - 1 && (str[n + 1] == wxT('%') || str[n + 1] == wxT('$')) ) {
425  str_n = str[++n];
426  strResult += str_n;
427 
428  break;
429  }
430  //else: fall through
431 
432  default:
433  strResult += str_n;
434  }
435  }
436 
437  return strResult;
438 }
if(dlg.ShowModal()==wxID_OK)
Definition: selcolor.cpp:76
const string & str
Definition: json11.cpp:596
Bracket
Definition: common.cpp:306
bool matchWild ( const char *  pat,
const char *  text,
bool  dot_special 
)

A copy of wxMatchWild(), which wxWidgets attributes to Douglas A.

Lewis dalew.nosp@m.is@c.nosp@m.s.Buf.nosp@m.falo.nosp@m..EDU and ircII's reg.c.

This version is modified to skip any encoding conversions (for performance).

Definition at line 668 of file common.cpp.

Referenced by TimestampDir().

669 {
670  if ( !*text )
671  {
672  /* Match if both are empty. */
673  return !*pat;
674  }
675 
676  const char *m = pat,
677  *n = text,
678  *ma = NULL,
679  *na = NULL;
680  int just = 0,
681  acount = 0,
682  count = 0;
683 
684  if (dot_special && (*n == '.'))
685  {
686  /* Never match so that hidden Unix files
687  * are never found. */
688  return false;
689  }
690 
691  for (;;)
692  {
693  if (*m == '*')
694  {
695  ma = ++m;
696  na = n;
697  just = 1;
698  acount = count;
699  }
700  else if (*m == '?')
701  {
702  m++;
703  if (!*n++)
704  return false;
705  }
706  else
707  {
708  if (*m == '\\')
709  {
710  m++;
711  /* Quoting "nothing" is a bad thing */
712  if (!*m)
713  return false;
714  }
715  if (!*m)
716  {
717  /*
718  * If we are out of both strings or we just
719  * saw a wildcard, then we can say we have a
720  * match
721  */
722  if (!*n)
723  return true;
724  if (just)
725  return true;
726  just = 0;
727  goto not_matched;
728  }
729  /*
730  * We could check for *n == NULL at this point, but
731  * since it's more common to have a character there,
732  * check to see if they match first (m and n) and
733  * then if they don't match, THEN we can check for
734  * the NULL of n
735  */
736  just = 0;
737  if (*m == *n)
738  {
739  m++;
740  count++;
741  n++;
742  }
743  else
744  {
745 
746  not_matched:
747 
748  /*
749  * If there are no more characters in the
750  * string, but we still need to find another
751  * character (*m != NULL), then it will be
752  * impossible to match it
753  */
754  if (!*n)
755  return false;
756 
757  if (ma)
758  {
759  m = ma;
760  n = ++na;
761  count = acount;
762  }
763  else
764  return false;
765  }
766  }
767  }
768 }
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 206 of file common.cpp.

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

207 {
208  return wxExecute( aCommandLine, aFlags, callback );
209 }
const wxString ResolveUriByEnvVars ( const wxString &  aUri)

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

Definition at line 456 of file common.cpp.

References ExpandEnvVarSubstitutions().

Referenced by FIELDS_GRID_TRICKS::doPopupSelection(), FIELDS_EDITOR_GRID_TRICKS::doPopupSelection(), TEXT_BUTTON_URL::OnButtonClick(), and SCH_EDIT_FRAME::OnEditItem().

457 {
458  // URL-like URI: return as is.
459  wxURL url( aUri );
460  if( url.GetError() == wxURL_NOERR )
461  return aUri;
462 
463  // Otherwise, the path points to a local file. Resolve environment
464  // variables if any.
465  return ExpandEnvVarSubstitutions( aUri );
466 }
const wxString ExpandEnvVarSubstitutions(const wxString &aString)
Replace any environment variable references with their values.
Definition: common.cpp:442
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 228 of file common.cpp.

References KiROUND().

Referenced by SCH_BASE_FRAME::UpdateStatusBar().

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

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

Definition at line 155 of file common.cpp.

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

156 {
157  wxString ref = aTextEntry->GetValue();
158 
159  if( ref.find_first_of( '?' ) != ref.npos )
160  {
161  aTextEntry->SetSelection( ref.find_first_of( '?' ), ref.find_last_of( '?' ) + 1 );
162  }
163  else
164  {
165  wxString num = ref;
166 
167  while( !num.IsEmpty() && ( !isdigit( num.Last() ) || !isdigit( num.GetChar( 0 ) ) ) )
168  {
169  if( !isdigit( num.Last() ) )
170  num.RemoveLast();
171  if( !isdigit( num.GetChar ( 0 ) ) )
172  num = num.Right( num.Length() - 1);
173  }
174 
175  aTextEntry->SetSelection( ref.Find( num ), ref.Find( num ) + num.Length() );
176 
177  if( num.IsEmpty() )
178  aTextEntry->SetSelection( -1, -1 );
179  }
180 }
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 804 of file common.cpp.

References matchWild().

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

805 {
806  long long timestamp = 0;
807 
808 #if defined(__WIN32__)
809  // Win32 version.
810  // Save time by not searching for each path twice: once in wxDir.GetNext() and once in
811  // wxFileName.GetModificationTime(). Also cuts out wxWidgets' string-matching and case
812  // conversion by staying on the MSW side of things.
813  std::wstring filespec( aDirPath.t_str() );
814  filespec += '\\';
815  filespec += aFilespec.t_str();
816 
817  WIN32_FIND_DATA findData;
818  wxDateTime lastModDate;
819 
820  HANDLE fileHandle = ::FindFirstFile( filespec.data(), &findData );
821 
822  if( fileHandle != INVALID_HANDLE_VALUE )
823  {
824  do
825  {
826  ConvertFileTimeToWx( &lastModDate, findData.ftLastWriteTime );
827  timestamp += lastModDate.GetValue().GetValue();
828  }
829  while ( FindNextFile( fileHandle, &findData ) != 0);
830  }
831 
832  FindClose( fileHandle );
833 #else
834  // POSIX version.
835  // Save time by not converting between encodings -- do everything on the file-system side.
836  std::string filespec( aFilespec.fn_str() );
837  std::string dir_path( aDirPath.fn_str() );
838 
839  DIR* dir = opendir( dir_path.c_str() );
840 
841  if( dir )
842  {
843  for( dirent* dir_entry = readdir( dir ); dir_entry; dir_entry = readdir( dir ) )
844  {
845  if( !matchWild( filespec.c_str(), dir_entry->d_name, true ) )
846  continue;
847 
848  std::string entry_path = dir_path + '/' + dir_entry->d_name;
849  struct stat entry_stat;
850 
851  wxCRT_Lstat( entry_path.c_str(), &entry_stat );
852 
853  // Timestamp the source file, not the symlink
854  if( S_ISLNK( entry_stat.st_mode ) ) // wxFILE_EXISTS_SYMLINK
855  {
856  char buffer[ PATH_MAX + 1 ];
857  ssize_t pathLen = readlink( entry_path.c_str(), buffer, PATH_MAX );
858 
859  if( pathLen > 0 )
860  {
861  buffer[ pathLen ] = '\0';
862  entry_path = dir_path + buffer;
863 
864  wxCRT_Lstat( entry_path.c_str(), &entry_stat );
865  }
866  }
867 
868  if( S_ISREG( entry_stat.st_mode ) ) // wxFileExists()
869  timestamp += entry_stat.st_mtime * 1000;
870  }
871 
872  closedir( dir );
873  }
874 #endif
875 
876  return timestamp;
877 }
bool matchWild(const char *pat, const char *text, bool dot_special)
A copy of wxMatchWild(), which wxWidgets attributes to Douglas A.
Definition: common.cpp:668
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 183 of file common.cpp.

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

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

Variable Documentation

COLOR4D g_GhostColor

Global variables definitions.

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 57 of file common.cpp.

Referenced by DrawMovingItems(), and EDA_DRAW_PANEL::OnPaint().