KiCad PCB EDA Suite
common.h File Reference

The common library. More...

#include <vector>
#include <functional>
#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 <limits>
#include <memory>
#include <type_traits>
#include <typeinfo>
#include <boost/uuid/uuid.hpp>
#include <macros.h>

Go to the source code of this file.

Classes

class  KIID
 
class  KIID_PATH
 
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 NAMELESS_PROJECT   wxT( "noname" )
 default name for nameless projects More...
 
#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 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...
 

Enumerations

enum  EDA_DATA_TYPE { EDA_DATA_TYPE::DISTANCE = 0, EDA_DATA_TYPE::AREA = 1, EDA_DATA_TYPE::VOLUME = 2 }
 The type of unit. More...
 
enum  EDA_UNITS {
  EDA_UNITS::INCHES = 0, EDA_UNITS::MILLIMETRES = 1, EDA_UNITS::UNSCALED = 2, EDA_UNITS::DEGREES = 3,
  EDA_UNITS::PERCENT = 4
}
 

Functions

KIIDNilUuid ()
 
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...
 
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...
 
const wxString ExpandEnvVarSubstitutions (const wxString &aString, PROJECT *aProject)
 Replace any environment variable & text variable references with their values. More...
 
wxString ExpandTextVars (const wxString &aSource, const std::function< bool(wxString *)> *aLocalResolver, const PROJECT *aProject, const std::function< bool(wxString *)> *aFallbackResolver=nullptr)
 Expand '${var-name}' templates in text. More...
 
const wxString ResolveUriByEnvVars (const wxString &aUri, PROJECT *aProject)
 Replace any environment and/or text 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

KIID niluuid
 

Detailed Description

The common library.

Definition in file common.h.

Macro Definition Documentation

◆ NAMELESS_PROJECT

#define NAMELESS_PROJECT   wxT( "noname" )

default name for nameless projects

Definition at line 181 of file common.h.

◆ TEXT_ANGLE_HORIZ

#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 185 of file common.h.

◆ TEXT_ANGLE_VERT

#define TEXT_ANGLE_VERT   900

Definition at line 186 of file common.h.

◆ USE_KICAD_WXPOINT_LESS_AND_HASH

#define USE_KICAD_WXPOINT_LESS_AND_HASH

Required to use wxPoint as key type in maps.

Definition at line 378 of file common.h.

◆ USE_KICAD_WXSTRING_HASH

#define USE_KICAD_WXSTRING_HASH

Definition at line 366 of file common.h.

Typedef Documentation

◆ 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 56 of file common.h.

Enumeration Type Documentation

◆ EDA_DATA_TYPE

enum EDA_DATA_TYPE
strong

The type of unit.

Enumerator
DISTANCE 
AREA 
VOLUME 

Definition at line 191 of file common.h.

◆ EDA_UNITS

enum EDA_UNITS
strong
Enumerator
INCHES 
MILLIMETRES 
UNSCALED 
DEGREES 
PERCENT 

Definition at line 198 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 609 of file common.cpp.

612 {
613  wxString msg;
614  wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
615 
616  // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
617  // already an absolute path) absolute:
618  if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
619  {
620  if( aReporter )
621  {
622  msg.Printf( _( "Cannot make path \"%s\" absolute with respect to \"%s\"." ),
623  aTargetFullFileName->GetPath(),
624  baseFilePath );
625  aReporter->Report( msg, RPT_SEVERITY_ERROR );
626  }
627 
628  return false;
629  }
630 
631  // Ensure the path of aTargetFullFileName exists, and create it if needed:
632  wxString outputPath( aTargetFullFileName->GetPath() );
633 
634  if( !wxFileName::DirExists( outputPath ) )
635  {
636  if( wxMkdir( outputPath ) )
637  {
638  if( aReporter )
639  {
640  msg.Printf( _( "Output directory \"%s\" created.\n" ), outputPath );
641  aReporter->Report( msg, RPT_SEVERITY_INFO );
642  return true;
643  }
644  }
645  else
646  {
647  if( aReporter )
648  {
649  msg.Printf( _( "Cannot create output directory \"%s\".\n" ), outputPath );
650  aReporter->Report( msg, RPT_SEVERITY_ERROR );
651  }
652 
653  return false;
654  }
655  }
656 
657  return true;
658 }
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Function Report is a pure virtual function to override in the derived object.
#define _(s)
Definition: 3d_actions.cpp:33

References _, REPORTER::Report(), RPT_SEVERITY_ERROR, and RPT_SEVERITY_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 283 of file common.cpp.

284 {
285  wxWindow* window = aCtrl->GetParent();
286 
287  if( !window )
288  window = aCtrl;
289 
290  wxString ctrlText;
291 
292  if( !aString )
293  {
294  ctrlText = aCtrl->GetValue();
295  aString = &ctrlText;
296  }
297 
298  wxSize textz = GetTextSize( *aString, window );
299  wxSize ctrlz = aCtrl->GetSize();
300 
301  if( ctrlz.GetWidth() < textz.GetWidth() + 10 )
302  {
303  ctrlz.SetWidth( textz.GetWidth() + 10 );
304  aCtrl->SetSizeHints( ctrlz );
305  return true;
306  }
307 
308  return false;
309 }
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:268

References GetTextSize().

Referenced by GERBVIEW_FRAME::UpdateTitleAndInfo().

◆ ExpandEnvVarSubstitutions()

const wxString ExpandEnvVarSubstitutions ( const wxString &  aString,
PROJECT aProject 
)

Replace any environment variable & text 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 581 of file common.cpp.

582 {
583  // wxGetenv( wchar_t* ) is not re-entrant on linux.
584  // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
585  static std::mutex getenv_mutex;
586 
587  std::lock_guard<std::mutex> lock( getenv_mutex );
588 
589  // We reserve the right to do this another way, by providing our own member function.
590  return KIwxExpandEnvVars( aString, aProject );
591 }
wxString KIwxExpandEnvVars(const wxString &str, const PROJECT *aProject)
Definition: common.cpp:442

References KIwxExpandEnvVars().

Referenced by FILENAME_RESOLVER::addPath(), GITHUB_PLUGIN::cacheLib(), FILENAME_RESOLVER::checkEnvVarPath(), S3D_PLUGIN_MANAGER::checkPluginName(), S3D_PLUGIN_MANAGER::checkPluginPath(), DIALOG_GEN_FOOTPRINT_POSITION::CreateGerberFiles(), FILENAME_RESOLVER::createPathList(), DIALOG_PLOT_SCHEMATIC::createPlotFileName(), DIALOG_EXPORT_SVG::ExportSVGFile(), DIALOG_GENDRILL::GenDrillAndMapFiles(), LIB_TABLE_ROW::GetFullURI(), WS_DATA_MODEL::MakeFullFileName(), TEXT_BUTTON_FILE_BROWSER::OnButtonClick(), DIALOG_GENDRILL::OnGenReportFile(), DIALOG_EXPORT_SVG::OnOutputDirectoryBrowseClicked(), DIALOG_PLOT::OnOutputDirectoryBrowseClicked(), DIALOG_PLOT_SCHEMATIC::OnOutputDirectoryBrowseClicked(), DIALOG_GEN_FOOTPRINT_POSITION::OnOutputDirectoryBrowseClicked(), DIALOG_GENDRILL::OnOutputDirectoryBrowseClicked(), DIALOG_PLOT::Plot(), FILENAME_RESOLVER::ResolvePath(), ResolveUriByEnvVars(), FILENAME_RESOLVER::Set3DConfigDir(), S3D_CACHE::Set3DConfigDir(), FILENAME_RESOLVER::SetProject(), FILENAME_RESOLVER::ShortenPath(), and ERC_TESTER::TestTextVars().

◆ ExpandTextVars()

wxString ExpandTextVars ( const wxString &  aSource,
const std::function< bool(wxString *)> *  aLocalResolver,
const PROJECT aProject,
const std::function< bool(wxString *)> *  aFallbackResolver = nullptr 
)

Expand '${var-name}' templates in text.

The LocalResolver is given first crack at it, after which the PROJECT's resolver is called.

Definition at line 384 of file common.cpp.

388 {
389  wxString newbuf;
390  size_t sourceLen = aSource.length();
391 
392  newbuf.Alloc( sourceLen ); // best guess (improves performance)
393 
394  for( size_t i = 0; i < sourceLen; ++i )
395  {
396  if( aSource[i] == '$' && i + 1 < sourceLen && aSource[i+1] == '{' )
397  {
398  wxString token;
399 
400  for( i = i + 2; i < sourceLen; ++i )
401  {
402  if( aSource[i] == '}' )
403  break;
404  else
405  token.append( aSource[i] );
406  }
407 
408  if( token.IsEmpty() )
409  continue;
410 
411  if( aLocalResolver && (*aLocalResolver)( &token ) )
412  {
413  newbuf.append( token );
414  }
415  else if( aProject && aProject->TextVarResolver( &token ) )
416  {
417  newbuf.append( token );
418  }
419  else if( aFallbackResolver && (*aFallbackResolver)( &token ) )
420  {
421  newbuf.append( token );
422  }
423  else
424  {
425  // Token not resolved: leave the reference unchanged
426  newbuf.append( "${" + token + "}" );
427  }
428  }
429  else
430  {
431  newbuf.append( aSource[i] );
432  }
433  }
434 
435  return newbuf;
436 }
VTBL_ENTRY bool TextVarResolver(wxString *aToken) const
Definition: project.cpp:68

References PROJECT::TextVarResolver().

Referenced by WS_DRAW_ITEM_LIST::BuildFullText(), TEXTE_PCB::GetShownText(), SCH_FIELD::GetShownText(), SCH_TEXT::GetShownText(), TEXTE_MODULE::GetShownText(), and ResolveUriByEnvVars().

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

269 {
270  wxCoord width;
271  wxCoord height;
272 
273  {
274  wxClientDC dc( aWindow );
275  dc.SetFont( aWindow->GetFont() );
276  dc.GetTextExtent( aSingleLine, &width, &height );
277  }
278 
279  return wxSize( width, height );
280 }

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

◆ NilUuid()

KIID& NilUuid ( )

Definition at line 57 of file common.cpp.

58 {
59  static KIID nil( 0 );
60  return nil;
61 }
Definition: common.h:68

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

739 {
740  out << " width=\"" << size.GetWidth() << "\" height=\"" << size.GetHeight() << "\"";
741  return out;
742 }

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

746 {
747  out << " x=\"" << pt.x << "\" y=\"" << pt.y << "\"";
748  return out;
749 }

References wxPoint::x, and wxPoint::y.

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

367 {
368  return (int) wxExecute( aCommandLine, aFlags, callback );
369 }

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

◆ ResolveUriByEnvVars()

const wxString ResolveUriByEnvVars ( const wxString &  aUri,
PROJECT aProject 
)

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

Definition at line 594 of file common.cpp.

595 {
596  wxString uri = ExpandTextVars( aUri, nullptr, aProject );
597 
598  // URL-like URI: return as is.
599  wxURL url( uri );
600 
601  if( url.GetError() == wxURL_NOERR )
602  return uri;
603 
604  // Otherwise, the path points to a local file. Resolve environment variables if any.
605  return ExpandEnvVarSubstitutions( aUri, aProject );
606 }
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:581
wxString ExpandTextVars(const wxString &aSource, const std::function< bool(wxString *)> *aLocalResolver, const PROJECT *aProject, const std::function< bool(wxString *)> *aFallbackResolver)
Expand '${var-name}' templates in text.
Definition: common.cpp:384

References ExpandEnvVarSubstitutions(), and ExpandTextVars().

Referenced by GetAssociatedDocument().

◆ 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 }
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:104
const wxChar *const tracePathsAndFiles
Flag to enable path and file name debug output.
SEARCH_STACK looks for files in a number of places.
Definition: search_stack.h:41
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(), and tracePathsAndFiles.

Referenced by COMMON_CONTROL::ShowHelp().

◆ SelectReferenceNumber()

void SelectReferenceNumber ( wxTextEntry *  aTextEntry)

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

Definition at line 312 of file common.cpp.

313 {
314  wxString ref = aTextEntry->GetValue();
315 
316  if( ref.find_first_of( '?' ) != ref.npos )
317  {
318  aTextEntry->SetSelection( ref.find_first_of( '?' ), ref.find_last_of( '?' ) + 1 );
319  }
320  else
321  {
322  wxString num = ref;
323 
324  while( !num.IsEmpty() && ( !isdigit( num.Last() ) || !isdigit( num.GetChar( 0 ) ) ) )
325  {
326  // Trim non-digit from end
327  if( !isdigit( num.Last() ) )
328  num.RemoveLast();
329 
330  // Trim non-digit from the start
331  if( !num.IsEmpty() && !isdigit( num.GetChar( 0 ) ) )
332  num = num.Right( num.Length() - 1 );
333  }
334 
335  aTextEntry->SetSelection( ref.Find( num ), ref.Find( num ) + num.Length() );
336 
337  if( num.IsEmpty() )
338  aTextEntry->SetSelection( -1, -1 );
339  }
340 }

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

974 {
975  long long timestamp = 0;
976 
977 #if defined( __WIN32__ )
978  // Win32 version.
979  // Save time by not searching for each path twice: once in wxDir.GetNext() and once in
980  // wxFileName.GetModificationTime(). Also cuts out wxWidgets' string-matching and case
981  // conversion by staying on the MSW side of things.
982  std::wstring filespec( aDirPath.t_str() );
983  filespec += '\\';
984  filespec += aFilespec.t_str();
985 
986  WIN32_FIND_DATA findData;
987  wxDateTime lastModDate;
988 
989  HANDLE fileHandle = ::FindFirstFile( filespec.data(), &findData );
990 
991  if( fileHandle != INVALID_HANDLE_VALUE )
992  {
993  do
994  {
995  ConvertFileTimeToWx( &lastModDate, findData.ftLastWriteTime );
996  timestamp += lastModDate.GetValue().GetValue();
997  }
998  while ( FindNextFile( fileHandle, &findData ) != 0 );
999  }
1000 
1001  FindClose( fileHandle );
1002 #else
1003  // POSIX version.
1004  // Save time by not converting between encodings -- do everything on the file-system side.
1005  std::string filespec( aFilespec.fn_str() );
1006  std::string dir_path( aDirPath.fn_str() );
1007 
1008  DIR* dir = opendir( dir_path.c_str() );
1009 
1010  if( dir )
1011  {
1012  for( dirent* dir_entry = readdir( dir ); dir_entry; dir_entry = readdir( dir ) )
1013  {
1014  if( !matchWild( filespec.c_str(), dir_entry->d_name, true ) )
1015  continue;
1016 
1017  std::string entry_path = dir_path + '/' + dir_entry->d_name;
1018  struct stat entry_stat;
1019 
1020  if( wxCRT_Lstat( entry_path.c_str(), &entry_stat ) == 0 )
1021  {
1022  // Timestamp the source file, not the symlink
1023  if( S_ISLNK( entry_stat.st_mode ) ) // wxFILE_EXISTS_SYMLINK
1024  {
1025  char buffer[ PATH_MAX + 1 ];
1026  ssize_t pathLen = readlink( entry_path.c_str(), buffer, PATH_MAX );
1027 
1028  if( pathLen > 0 )
1029  {
1030  struct stat linked_stat;
1031  buffer[ pathLen ] = '\0';
1032  entry_path = dir_path + buffer;
1033 
1034  if( wxCRT_Lstat( entry_path.c_str(), &linked_stat ) == 0 )
1035  {
1036  entry_stat = linked_stat;
1037  }
1038  else
1039  {
1040  // if we couldn't lstat the linked file we'll have to just use
1041  // the symbolic link info
1042  }
1043  }
1044  }
1045 
1046  if( S_ISREG( entry_stat.st_mode ) ) // wxFileExists()
1047  timestamp += entry_stat.st_mtime * 1000;
1048  }
1049  else
1050  {
1051  // if we couldn't lstat the file itself all we can do is use the name
1052  timestamp += (signed) std::hash<std::string>{}( std::string( dir_entry->d_name ) );
1053  }
1054  }
1055 
1056  closedir( dir );
1057  }
1058 #endif
1059 
1060  return timestamp;
1061 }
bool matchWild(const char *pat, const char *text, bool dot_special)
A copy of wxMatchWild(), which wxWidgets attributes to Douglas A.
Definition: common.cpp:831

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

344 {
345  wxString tmp;
346 
347  for( unsigned ii = 0; ii < aText.Length(); ii++ )
348  {
349  if( aText[ii] == aSplitter )
350  {
351  aStrings.Add( tmp );
352  tmp.Clear();
353  }
354 
355  else
356  tmp << aText[ii];
357  }
358 
359  if( !tmp.IsEmpty() )
360  {
361  aStrings.Add( tmp );
362  }
363 }

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

Variable Documentation

◆ niluuid