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

282 {
283  Bracket_None,
284  Bracket_Normal = ')',
285  Bracket_Curly = '}',
286 #ifdef __WINDOWS__
287  Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
288 #endif
290 };

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

447 {
448  wxString msg;
449  wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
450 
451  // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
452  // already an absolute path) absolute:
453  if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
454  {
455  if( aReporter )
456  {
457  msg.Printf( _( "Cannot make path \"%s\" absolute with respect to \"%s\"." ),
458  GetChars( aTargetFullFileName->GetPath() ),
459  GetChars( baseFilePath ) );
460  aReporter->Report( msg, REPORTER::RPT_ERROR );
461  }
462 
463  return false;
464  }
465 
466  // Ensure the path of aTargetFullFileName exists, and create it if needed:
467  wxString outputPath( aTargetFullFileName->GetPath() );
468 
469  if( !wxFileName::DirExists( outputPath ) )
470  {
471  if( wxMkdir( outputPath ) )
472  {
473  if( aReporter )
474  {
475  msg.Printf( _( "Output directory \"%s\" created.\n" ), GetChars( outputPath ) );
476  aReporter->Report( msg, REPORTER::RPT_INFO );
477  return true;
478  }
479  }
480  else
481  {
482  if( aReporter )
483  {
484  msg.Printf( _( "Cannot create output directory \"%s\".\n" ),
485  GetChars( outputPath ) );
486  aReporter->Report( msg, REPORTER::RPT_ERROR );
487  }
488 
489  return false;
490  }
491  }
492 
493  return true;
494 }
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 101 of file common.cpp.

References GetTextSize().

Referenced by GERBVIEW_FRAME::UpdateTitleAndInfo().

102 {
103  wxWindow* window = aCtrl->GetParent();
104 
105  if( !window )
106  window = aCtrl;
107 
108  wxString ctrlText;
109 
110  if( !aString )
111  {
112  ctrlText = aCtrl->GetValue();
113  aString = &ctrlText;
114  }
115 
116  wxSize textz = GetTextSize( *aString, window );
117  wxSize ctrlz = aCtrl->GetSize();
118 
119  if( ctrlz.GetWidth() < textz.GetWidth() + 10 )
120  {
121  ctrlz.SetWidth( textz.GetWidth() + 10 );
122  aCtrl->SetSizeHints( ctrlz );
123  return true;
124  }
125 
126  return false;
127 }
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:86
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 417 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().

418 {
419  // wxGetenv( wchar_t* ) is not re-entrant on linux.
420  // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
421  static MUTEX getenv_mutex;
422 
423  MUTLOCK lock( getenv_mutex );
424 
425  // We reserve the right to do this another way, by providing our own member
426  // function.
427  return KIwxExpandEnvVars( aString );
428 }
wxString KIwxExpandEnvVars(const wxString &str)
Definition: common.cpp:296
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 238 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().

239 {
240  wxFileName cfgpath;
241 
242  // http://docs.wxwidgets.org/3.0/classwx_standard_paths.html#a7c7cf595d94d29147360d031647476b0
243  cfgpath.AssignDir( wxStandardPaths::Get().GetUserConfigDir() );
244 
245  // GetUserConfigDir() does not default to ~/.config which is the current standard
246  // configuration file location on Linux. This has been fixed in later versions of wxWidgets.
247 #if !defined( __WXMSW__ ) && !defined( __WXMAC__ )
248  wxArrayString dirs = cfgpath.GetDirs();
249 
250  if( dirs.Last() != ".config" )
251  cfgpath.AppendDir( ".config" );
252 #endif
253 
254  wxString envstr;
255 
256  // This shouldn't cause any issues on Windows or MacOS.
257  if( wxGetEnv( wxT( "XDG_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
258  {
259  // Override the assignment above with XDG_CONFIG_HOME
260  cfgpath.AssignDir( envstr );
261  }
262 
263  cfgpath.AppendDir( wxT( "kicad" ) );
264 
265  // Use KICAD_CONFIG_HOME to allow the user to force a specific configuration path.
266  if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
267  {
268  // Override the assignment above with KICAD_CONFIG_HOME
269  cfgpath.AssignDir( envstr );
270  }
271 
272  if( !cfgpath.DirExists() )
273  {
274  cfgpath.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
275  }
276 
277  return cfgpath.GetPath();
278 }
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 226 of file common.cpp.

References GetKicadConfigPath().

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

227 {
228  wxConfigBase* cfg = 0;
229  wxFileName configname;
230  configname.AssignDir( GetKicadConfigPath() );
231  configname.SetFullName( aProgName );
232 
233  cfg = new wxFileConfig( wxT( "" ), wxT( "" ), configname.GetFullPath() );
234  return cfg;
235 }
wxString GetKicadConfigPath()
Return the user configuration path used to store KiCad&#39;s configuration files.
Definition: common.cpp:238
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 86 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().

87 {
88  wxCoord width;
89  wxCoord height;
90 
91  {
92  wxClientDC dc( aWindow );
93  dc.SetFont( aWindow->GetFont() );
94  dc.GetTextExtent( aSingleLine, &width, &height );
95  }
96 
97  return wxSize( width, height );
98 }
wxString KIwxExpandEnvVars ( const wxString &  str)

Definition at line 296 of file common.cpp.

References Bracket_Curly, Bracket_None, and Bracket_Normal.

Referenced by ExpandEnvVarSubstitutions().

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

Referenced by TimestampDir().

644 {
645  if ( !*text )
646  {
647  /* Match if both are empty. */
648  return !*pat;
649  }
650 
651  const char *m = pat,
652  *n = text,
653  *ma = NULL,
654  *na = NULL;
655  int just = 0,
656  acount = 0,
657  count = 0;
658 
659  if (dot_special && (*n == '.'))
660  {
661  /* Never match so that hidden Unix files
662  * are never found. */
663  return false;
664  }
665 
666  for (;;)
667  {
668  if (*m == '*')
669  {
670  ma = ++m;
671  na = n;
672  just = 1;
673  acount = count;
674  }
675  else if (*m == '?')
676  {
677  m++;
678  if (!*n++)
679  return false;
680  }
681  else
682  {
683  if (*m == '\\')
684  {
685  m++;
686  /* Quoting "nothing" is a bad thing */
687  if (!*m)
688  return false;
689  }
690  if (!*m)
691  {
692  /*
693  * If we are out of both strings or we just
694  * saw a wildcard, then we can say we have a
695  * match
696  */
697  if (!*n)
698  return true;
699  if (just)
700  return true;
701  just = 0;
702  goto not_matched;
703  }
704  /*
705  * We could check for *n == NULL at this point, but
706  * since it's more common to have a character there,
707  * check to see if they match first (m and n) and
708  * then if they don't match, THEN we can check for
709  * the NULL of n
710  */
711  just = 0;
712  if (*m == *n)
713  {
714  m++;
715  count++;
716  n++;
717  }
718  else
719  {
720 
721  not_matched:
722 
723  /*
724  * If there are no more characters in the
725  * string, but we still need to find another
726  * character (*m != NULL), then it will be
727  * impossible to match it
728  */
729  if (!*n)
730  return false;
731 
732  if (ma)
733  {
734  m = ma;
735  n = ++na;
736  count = acount;
737  }
738  else
739  return false;
740  }
741  }
742  }
743 }
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 181 of file common.cpp.

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

182 {
183  return wxExecute( aCommandLine, aFlags, callback );
184 }
const wxString ResolveUriByEnvVars ( const wxString &  aUri)

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

Definition at line 431 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().

432 {
433  // URL-like URI: return as is.
434  wxURL url( aUri );
435  if( url.GetError() == wxURL_NOERR )
436  return aUri;
437 
438  // Otherwise, the path points to a local file. Resolve environment
439  // variables if any.
440  return ExpandEnvVarSubstitutions( aUri );
441 }
const wxString ExpandEnvVarSubstitutions(const wxString &aString)
Replace any environment variable references with their values.
Definition: common.cpp:417
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 203 of file common.cpp.

References KiROUND().

Referenced by SCH_BASE_FRAME::UpdateStatusBar().

204 {
205  assert( precision != 0 );
206 
207  long long ix = KiROUND( x * precision );
208 
209  if ( x < 0.0 )
210  ix = -ix;
211 
212  int remainder = ix % 10; // remainder is in precision mm
213 
214  if( remainder <= 2 )
215  ix -= remainder; // truncate to the near number
216  else if( remainder >= 8 )
217  ix += 10 - remainder; // round to near number
218 
219  if ( x < 0 )
220  ix = -ix;
221 
222  return (double) ix / precision;
223 }
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 130 of file common.cpp.

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

131 {
132  wxString ref = aTextEntry->GetValue();
133 
134  if( ref.find_first_of( '?' ) != ref.npos )
135  {
136  aTextEntry->SetSelection( ref.find_first_of( '?' ), ref.find_last_of( '?' ) + 1 );
137  }
138  else
139  {
140  wxString num = ref;
141 
142  while( !num.IsEmpty() && ( !isdigit( num.Last() ) || !isdigit( num.GetChar( 0 ) ) ) )
143  {
144  if( !isdigit( num.Last() ) )
145  num.RemoveLast();
146  if( !isdigit( num.GetChar ( 0 ) ) )
147  num = num.Right( num.Length() - 1);
148  }
149 
150  aTextEntry->SetSelection( ref.Find( num ), ref.Find( num ) + num.Length() );
151 
152  if( num.IsEmpty() )
153  aTextEntry->SetSelection( -1, -1 );
154  }
155 }
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 779 of file common.cpp.

References matchWild().

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

780 {
781  long long timestamp = 0;
782 
783 #if defined(__WIN32__)
784  // Win32 version.
785  // Save time by not searching for each path twice: once in wxDir.GetNext() and once in
786  // wxFileName.GetModificationTime(). Also cuts out wxWidgets' string-matching and case
787  // conversion by staying on the MSW side of things.
788  std::wstring filespec( aDirPath.t_str() );
789  filespec += '\\';
790  filespec += aFilespec.t_str();
791 
792  WIN32_FIND_DATA findData;
793  wxDateTime lastModDate;
794 
795  HANDLE fileHandle = ::FindFirstFile( filespec.data(), &findData );
796 
797  if( fileHandle != INVALID_HANDLE_VALUE )
798  {
799  do
800  {
801  ConvertFileTimeToWx( &lastModDate, findData.ftLastWriteTime );
802  timestamp += lastModDate.GetValue().GetValue();
803  }
804  while ( FindNextFile( fileHandle, &findData ) != 0);
805  }
806 
807  FindClose( fileHandle );
808 #else
809  // POSIX version.
810  // Save time by not converting between encodings -- do everything on the file-system side.
811  std::string filespec( aFilespec.fn_str() );
812  std::string dir_path( aDirPath.fn_str() );
813 
814  DIR* dir = opendir( dir_path.c_str() );
815 
816  if( dir )
817  {
818  for( dirent* dir_entry = readdir( dir ); dir_entry; dir_entry = readdir( dir ) )
819  {
820  if( !matchWild( filespec.c_str(), dir_entry->d_name, true ) )
821  continue;
822 
823  std::string entry_path = dir_path + '/' + dir_entry->d_name;
824  struct stat entry_stat;
825 
826  wxCRT_Lstat( entry_path.c_str(), &entry_stat );
827 
828  // Timestamp the source file, not the symlink
829  if( S_ISLNK( entry_stat.st_mode ) ) // wxFILE_EXISTS_SYMLINK
830  {
831  char buffer[ PATH_MAX + 1 ];
832  ssize_t pathLen = readlink( entry_path.c_str(), buffer, PATH_MAX );
833 
834  if( pathLen > 0 )
835  {
836  buffer[ pathLen ] = '\0';
837  entry_path = dir_path + buffer;
838 
839  wxCRT_Lstat( entry_path.c_str(), &entry_stat );
840  }
841  }
842 
843  if( S_ISREG( entry_stat.st_mode ) ) // wxFileExists()
844  timestamp += entry_stat.st_mtime * 1000;
845  }
846 
847  closedir( dir );
848  }
849 #endif
850 
851  return timestamp;
852 }
bool matchWild(const char *pat, const char *text, bool dot_special)
A copy of wxMatchWild(), which wxWidgets attributes to Douglas A.
Definition: common.cpp:643
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 158 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().

159 {
160  wxString tmp;
161 
162  for( unsigned ii = 0; ii < aText.Length(); ii++ )
163  {
164  if( aText[ii] == aSplitter )
165  {
166  aStrings.Add( tmp );
167  tmp.Clear();
168  }
169 
170  else
171  tmp << aText[ii];
172  }
173 
174  if( !tmp.IsEmpty() )
175  {
176  aStrings.Add( tmp );
177  }
178 }

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