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 <mutex>
#include <wx/process.h>
#include <wx/config.h>
#include <wx/utils.h>
#include <wx/stdpaths.h>
#include <wx/url.h>
#include <pgm_base.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...
 
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...
 
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...
 
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...
 
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

◆ Bracket

enum Bracket
Enumerator
Bracket_None 
Bracket_Normal 
Bracket_Curly 
Bracket_Max 

Definition at line 310 of file common.cpp.

311 {
312  Bracket_None,
313  Bracket_Normal = ')',
314  Bracket_Curly = '}',
315 #ifdef __WINDOWS__
316  Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
317 #endif
319 };

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

484 {
485  wxString msg;
486  wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
487 
488  // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
489  // already an absolute path) absolute:
490  if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
491  {
492  if( aReporter )
493  {
494  msg.Printf( _( "Cannot make path \"%s\" absolute with respect to \"%s\"." ),
495  GetChars( aTargetFullFileName->GetPath() ),
496  GetChars( baseFilePath ) );
497  aReporter->Report( msg, REPORTER::RPT_ERROR );
498  }
499 
500  return false;
501  }
502 
503  // Ensure the path of aTargetFullFileName exists, and create it if needed:
504  wxString outputPath( aTargetFullFileName->GetPath() );
505 
506  if( !wxFileName::DirExists( outputPath ) )
507  {
508  if( wxMkdir( outputPath ) )
509  {
510  if( aReporter )
511  {
512  msg.Printf( _( "Output directory \"%s\" created.\n" ), GetChars( outputPath ) );
513  aReporter->Report( msg, REPORTER::RPT_INFO );
514  return true;
515  }
516  }
517  else
518  {
519  if( aReporter )
520  {
521  msg.Printf( _( "Cannot create output directory \"%s\".\n" ),
522  GetChars( outputPath ) );
523  aReporter->Report( msg, REPORTER::RPT_ERROR );
524  }
525 
526  return false;
527  }
528  }
529 
530  return true;
531 }
#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::CreateAsciiFiles(), DIALOG_GEN_FOOTPRINT_POSITION::CreateGerberFiles(), 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 454 of file common.cpp.

455 {
456  // wxGetenv( wchar_t* ) is not re-entrant on linux.
457  // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
458  static std::mutex getenv_mutex;
459 
460  std::lock_guard<std::mutex> lock( getenv_mutex );
461 
462  // We reserve the right to do this another way, by providing our own member function.
463  return KIwxExpandEnvVars( aString );
464 }
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().

◆ 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(), EDA_BASE_FRAME::LoadSettings(), SYMBOL_PREVIEW_WIDGET::SYMBOL_PREVIEW_WIDGET(), and PANEL_COMMON_SETTINGS::TransferDataToWindow().

◆ 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(), 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(), SCH_EDIT_FRAME::LoadSheetFromFile(), EDA_ITEM::operator=(), SCH_EDITOR_CONTROL::Paste(), SCH_DRAWING_TOOLS::PlaceComponent(), 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(), LIB_TREE_MODEL_ADAPTER::AttachTo(), 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().

◆ KIwxExpandEnvVars()

wxString KIwxExpandEnvVars ( const wxString &  str)

Definition at line 325 of file common.cpp.

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

References _, Bracket_Curly, Bracket_None, Bracket_Normal, and str.

Referenced by ExpandEnvVarSubstitutions().

◆ matchWild()

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

705 {
706  if( !*text )
707  {
708  /* Match if both are empty. */
709  return !*pat;
710  }
711 
712  const char *m = pat,
713  *n = text,
714  *ma = NULL,
715  *na = NULL;
716  int just = 0,
717  acount = 0,
718  count = 0;
719 
720  if( dot_special && (*n == '.') )
721  {
722  /* Never match so that hidden Unix files
723  * are never found. */
724  return false;
725  }
726 
727  for(;;)
728  {
729  if( *m == '*' )
730  {
731  ma = ++m;
732  na = n;
733  just = 1;
734  acount = count;
735  }
736  else if( *m == '?' )
737  {
738  m++;
739 
740  if( !*n++ )
741  return false;
742  }
743  else
744  {
745  if( *m == '\\' )
746  {
747  m++;
748 
749  /* Quoting "nothing" is a bad thing */
750  if( !*m )
751  return false;
752  }
753  if( !*m )
754  {
755  /*
756  * If we are out of both strings or we just
757  * saw a wildcard, then we can say we have a
758  * match
759  */
760  if( !*n )
761  return true;
762 
763  if( just )
764  return true;
765 
766  just = 0;
767  goto not_matched;
768  }
769 
770  /*
771  * We could check for *n == NULL at this point, but
772  * since it's more common to have a character there,
773  * check to see if they match first (m and n) and
774  * then if they don't match, THEN we can check for
775  * the NULL of n
776  */
777  just = 0;
778 
779  if( *m == *n )
780  {
781  m++;
782  count++;
783  n++;
784  }
785  else
786  {
787  not_matched:
788 
789  /*
790  * If there are no more characters in the
791  * string, but we still need to find another
792  * character (*m != NULL), then it will be
793  * impossible to match it
794  */
795  if( !*n )
796  return false;
797 
798  if( ma )
799  {
800  m = ma;
801  n = ++na;
802  count = acount;
803  }
804  else
805  return false;
806  }
807  }
808  }
809 }

Referenced by TimestampDir().

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

612 {
613  out << " width=\"" << size.GetWidth() << "\" height=\"" << size.GetHeight() << "\"";
614  return out;
615 }

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

619 {
620  out << " x=\"" << pt.x << "\" y=\"" << pt.y << "\"";
621  return out;
622 }

◆ 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 doPrintFile(), 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 467 of file common.cpp.

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

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 }
constexpr ret_type KiROUND(fp_type v)
Round a floating point number to an integer using "round halfway cases away from zero".
Definition: common.h:114

References KiROUND().

Referenced by SCH_BASE_FRAME::UpdateStatusBar().

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

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

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

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