KiCad PCB EDA Suite
gestfich.cpp File Reference

Functions for file management. More...

#include <fctsys.h>
#include <wx/mimetype.h>
#include <wx/filename.h>
#include <wx/dir.h>
#include <pgm_base.h>
#include <confirm.h>
#include <common.h>
#include <macros.h>
#include <gestfich.h>

Go to the source code of this file.

Functions

void AddDelimiterString (wxString &string)
 Function AddDelimiterString Add un " to the start and the end of string (if not already done). More...
 
wxString EDA_FILE_SELECTOR (const wxString &aTitle, const wxString &aPath, const wxString &aFileName, const wxString &aExtension, const wxString &aWildcard, wxWindow *aParent, int aStyle, const bool aKeepWorkingDirectory, const wxPoint &aPosition, wxString *aMruPath)
 Function EDA_FILE_SELECTOR. More...
 
wxString FindKicadFile (const wxString &shortname)
 Function FindKicadFile searches the executable file shortname in KiCad binary path and return full file name if found or shortname if the kicad binary path is kicad/bin. More...
 
int ExecuteFile (wxWindow *frame, const wxString &ExecFile, const wxString &param, wxProcess *callback)
 Function ExecuteFile calls the executable file ExecFile with the command line parameters param. More...
 
bool OpenPDF (const wxString &file)
 Function OpenPDF run the PDF viewer and display a PDF file. More...
 
void OpenFile (const wxString &file)
 
bool doPrintFile (const wxString &file, bool aDryRun)
 
void PrintFile (const wxString &file)
 
bool CanPrintFile (const wxString &file)
 
void CopyFile (const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
 Function CopyFile. More...
 
wxString QuoteFullPath (wxFileName &fn, wxPathFormat format)
 Quote return value of wxFileName::GetFullPath(). More...
 
bool DeleteDirectory (const wxString &aDirName, bool aRecurse, bool aIncludeHidden)
 Delete a directory and all of its contents recursively. More...
 

Detailed Description

Functions for file management.

Definition in file gestfich.cpp.

Function Documentation

◆ AddDelimiterString()

void AddDelimiterString ( wxString &  string)

Function AddDelimiterString Add un " to the start and the end of string (if not already done).

Parameters
string= string to modify

Definition at line 42 of file gestfich.cpp.

43 {
44  if( !string.StartsWith( wxT( "\"" ) ) )
45  {
46  string.Prepend ( wxT( "\"" ) );
47  string.Append ( wxT( "\"" ) );
48  }
49 }

Referenced by KICAD_MANAGER_CONTROL::Execute(), ExecuteFile(), KICAD_MANAGER_FRAME::OnBrowseInFileExplorer(), DIALOG_BOM::OnEditGenerator(), TREE_PROJECT_FRAME::OnOpenDirectory(), and TREE_PROJECT_FRAME::OnOpenSelectedFileWithTextEditor().

◆ CanPrintFile()

bool CanPrintFile ( const wxString &  file)

Definition at line 352 of file gestfich.cpp.

353 {
354  return doPrintFile( file, true );
355 }
bool doPrintFile(const wxString &file, bool aDryRun)
Definition: gestfich.cpp:271

References doPrintFile().

Referenced by TREE_PROJECT_FRAME::OnRight().

◆ CopyFile()

void CopyFile ( const wxString &  aSrcPath,
const wxString &  aDestPath,
wxString &  aErrors 
)

Function CopyFile.

Parameters
aSrcPath
aDestPath
aErrorsa wxString to append any errors to

Definition at line 358 of file gestfich.cpp.

359 {
360  if( !wxCopyFile( aSrcPath, aDestPath ) )
361  {
362  wxString msg;
363 
364  if( !aErrors.IsEmpty() )
365  aErrors += "\n";
366 
367  msg.Printf( _( "Cannot copy file \"%s\"." ), aDestPath );
368  aErrors += msg;
369  }
370 }
#define _(s)

References _.

Referenced by IfaceOrAddress(), and SAVE_AS_TRAVERSER::OnFile().

◆ DeleteDirectory()

bool DeleteDirectory ( const wxString &  aDirName,
bool  aRecurse = true,
bool  aIncludeHidden = true 
)

Delete a directory and all of its contents recursively.

This function ensures that all contents of subdirectories are deleted before deleting the directory. If recursion is disabled, then the existence of subdirectories will cause the deletion to fail and the function to return false.

Note that if hidden files/folders exist in the directory, and aIncludeHidden is false, then the directory may not be deleted.

Parameters
aRecursespecifies if subdirectories should also be deleted
aIncludeHiddenspecifies if hidden files/directories should be deleted as well
Returns
true if the directory could be deleted

Definition at line 379 of file gestfich.cpp.

380 {
381  int hiddenFlag = ( aIncludeHidden ? wxDIR_HIDDEN : 0 );
382  wxDir mainDir( aDirName );
383 
384  if( !mainDir.IsOpened() )
385  return false;
386 
387  if( mainDir.HasSubDirs() && !aRecurse )
388  {
389  mainDir.Close();
390  return false;
391  }
392 
393  // Get the name from wxWidgets so that we are sure all the separators are correct
394  wxString fullDirName = mainDir.GetNameWithSep();
395 
396  wxString dir;
397  bool valid = mainDir.GetFirst( &dir, wxEmptyString, wxDIR_DIRS | hiddenFlag );
398 
399  // Iterate over the subdirectories to recursively delete them and their contents
400  while( valid )
401  {
402  dir.Prepend( fullDirName );
403 
404  // This call will also delete the actual directory, so we don't have to
405  if( !DeleteDirectory( dir, true, aIncludeHidden ) )
406  {
407  mainDir.Close();
408  return false;
409  }
410  valid = mainDir.GetNext( &dir );
411  }
412 
413 
414  wxString file;
415  valid = mainDir.GetFirst( &file, wxEmptyString, wxDIR_FILES | hiddenFlag );
416 
417  // Iterate over the files to remove all of them from the directory
418  while( valid )
419  {
420  file.Prepend( fullDirName );
421 
422  if( !wxRemoveFile( file ) )
423  {
424  mainDir.Close();
425  return false;
426  }
427  valid = mainDir.GetNext( &file );
428  }
429 
430  mainDir.Close();
431 
432  // Now delete the actual directory
433  if( !wxRmdir( aDirName ) )
434  {
435  mainDir.Close();
436  return false;
437  }
438 
439  return true;
440 }
bool DeleteDirectory(const wxString &aDirName, bool aRecurse, bool aIncludeHidden)
Delete a directory and all of its contents recursively.
Definition: gestfich.cpp:379

References DeleteDirectory().

Referenced by TREEPROJECT_ITEM::Delete(), and DeleteDirectory().

◆ doPrintFile()

bool doPrintFile ( const wxString &  file,
bool  aDryRun 
)

Definition at line 271 of file gestfich.cpp.

272 {
273  wxFileName fileName( file );
274  wxString ext = fileName.GetExt();
275  wxFileType* filetype = wxTheMimeTypesManager->GetFileTypeFromExtension( ext );
276 
277  if( !filetype )
278  return false;
279 
280  wxString printCommand;
281  wxString openCommand;
282  wxString application;
283 
284  wxFileType::MessageParameters params( file );
285  filetype->GetPrintCommand( &printCommand, params );
286  filetype->GetOpenCommand( &openCommand, params );
287  delete filetype;
288 
289  if( !printCommand.IsEmpty() )
290  {
291  if( !aDryRun )
292  ProcessExecute( printCommand );
293 
294  return true;
295  }
296 
297 #ifdef __WXMAC__
298  if( ext == "ps" || ext == "pdf" )
299  application = "Preview";
300  else if( ext == "csv" )
301  application = "Numbers";
302  else if( ext == "txt" || ext == "rpt" || ext == "pos" || ext == "cmp" || ext == "net" )
303  application = "TextEdit";
304 
305  if( !application.IsEmpty() )
306  {
307  printCommand.Printf( "osascript -e 'tell application \"%s\"' "
308  "-e ' set srcFileRef to (open POSIX file \"%s\")' "
309  "-e ' activate' "
310  "-e ' print srcFileRef print dialog true' "
311  "-e 'end tell' ",
312  application,
313  file );
314 
315  if( !aDryRun )
316  system( printCommand.c_str() );
317 
318  return true;
319  }
320 #endif
321 
322 #ifdef __WXGTK__
323  if( ext == "ps" || ext == "pdf"
324  || ext == "csv"
325  || ext == "txt" || ext == "rpt" || ext == "pos" || ext == "cmp" || ext == "net" )
326  {
327  printCommand.Printf( "lp \"%s\"", file );
328 
329  if( !aDryRun )
330  ProcessExecute( printCommand );
331 
332  return true;
333  }
334 #endif
335 
336  if( !aDryRun )
337  {
338  DisplayError( nullptr, wxString::Format( _( "Cannot print '%s'.\n\nUnknown filetype." ),
339  file ) );
340  }
341 
342  return false;
343 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:236
int ProcessExecute(const wxString &aCommandLine, int aFlags, wxProcess *callback)
Run a command in a child process.
Definition: common.cpp:211
#define _(s)
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, CPTREE &aTree)
Function Format outputs a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:205

References _, DisplayError(), Format(), and ProcessExecute().

Referenced by CanPrintFile(), and PrintFile().

◆ EDA_FILE_SELECTOR()

wxString EDA_FILE_SELECTOR ( const wxString &  aTitle,
const wxString &  aPath,
const wxString &  aFileName,
const wxString &  aExtension,
const wxString &  aWildcard,
wxWindow *  aParent,
int  aStyle,
const bool  aKeepWorkingDirectory,
const wxPoint &  aPosition = wxDefaultPosition,
wxString *  aMruPath = NULL 
)

Function EDA_FILE_SELECTOR.

is a helper function that wraps a call to wxFileSelector.

Parameters
aTitleis a string to display in the dialog title bar.
aPathis a string contain the default path for the path dialog.
aFileNameis a string containing the default file name.
aExtensionis a string containing the default file extension.
aWildcardis a string containing the default wildcard.
aParentis the parent window of the dialog.
aStyleis the style of the path dialog, wxFD_???.
aKeepWorkingDirectorydetermines if current working directory should be set to the user selected path.
aPositionis the position of the dialog.
aMruPathis a pointer to a string to copy the path selected by the user when the OK button is pressed to dismiss the dialog. This can be NULL.
Returns
the full path and file name of the selected file or wxEmptyString if the user pressed the cancel button to dismiss the dialog.

Definition at line 52 of file gestfich.cpp.

62 {
63  wxString fullfilename;
64  wxString curr_cwd = wxGetCwd();
65  wxString defaultname = aFileName;
66  wxString defaultpath = aPath;
67  wxString dotted_Ext = wxT(".") + aExtension;
68 
69 #ifdef __WINDOWS__
70  defaultname.Replace( wxT( "/" ), wxT( "\\" ) );
71  defaultpath.Replace( wxT( "/" ), wxT( "\\" ) );
72 #endif
73 
74  if( defaultpath.IsEmpty() )
75  {
76  if( aMruPath == NULL )
77  defaultpath = wxGetCwd();
78  else
79  defaultpath = *aMruPath;
80  }
81 
82  wxSetWorkingDirectory( defaultpath );
83 
84 #if 0 && defined (DEBUG)
85  printf( "defaultpath=\"%s\" defaultname=\"%s\" Ext=\"%s\" Mask=\"%s\" flag=%d keep_working_directory=%d\n",
86  TO_UTF8( defaultpath ),
87  TO_UTF8( defaultname ),
88  TO_UTF8( aExtension ),
89  TO_UTF8( aWildcard ),
90  aStyle,
91  aKeepWorkingDirectory );
92 #endif
93 
94  fullfilename = wxFileSelector( aTitle, defaultpath, defaultname,
95  dotted_Ext, aWildcard,
96  aStyle, // open mode wxFD_OPEN, wxFD_SAVE ..
97  aParent, aPosition.x, aPosition.y );
98 
99  if( aKeepWorkingDirectory )
100  wxSetWorkingDirectory( curr_cwd );
101 
102  if( !fullfilename.IsEmpty() && aMruPath )
103  {
104  wxFileName fn = fullfilename;
105  *aMruPath = fn.GetPath();
106  }
107 
108  return fullfilename;
109 }
#define TO_UTF8(wxstring)
Macro TO_UTF8 converts a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:48

References TO_UTF8.

Referenced by PGM_BASE::AskUserForPreferredEditor(), DIALOG_BOM::chooseGenerator(), PCB_EDITOR_CONTROL::ExportSpecctraDSN(), LIB_CONTROL::ExportSymbolAsSVG(), GetAssociatedDocument(), PANEL_HOTKEYS_EDITOR::ImportHotKeys(), PCB_EDITOR_CONTROL::ImportSpecctraSession(), NETLIST_DIALOG_ADD_GENERATOR::OnBrowseGenerators(), and MWAVE_POLYGONAL_SHAPE_DLG::ReadDataShapeDescr().

◆ ExecuteFile()

int ExecuteFile ( wxWindow *  frame,
const wxString &  ExecFile,
const wxString &  param,
wxProcess *  callback 
)

Function ExecuteFile calls the executable file ExecFile with the command line parameters param.

Definition at line 174 of file gestfich.cpp.

176 {
177  wxString fullFileName = FindKicadFile( ExecFile );
178 
179  if( wxFileExists( fullFileName ) )
180  {
181  if( !param.IsEmpty() )
182  fullFileName += wxT( " " ) + param;
183 
184  return ProcessExecute( fullFileName, wxEXEC_ASYNC, callback );
185  }
186 #ifdef __WXMAC__
187  else
188  {
189  AddDelimiterString( fullFileName );
190 
191  if( !param.IsEmpty() )
192  fullFileName += wxT( " " ) + param;
193 
194  return ProcessExecute( wxT( "/usr/bin/open -a " ) + fullFileName, wxEXEC_ASYNC, callback );
195  }
196 #endif
197 
198  wxString msg;
199  msg.Printf( _( "Command \"%s\" could not found" ), GetChars( fullFileName ) );
200  DisplayError( frame, msg, 20 );
201  return -1;
202 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:236
int ProcessExecute(const wxString &aCommandLine, int aFlags, wxProcess *callback)
Run a command in a child process.
Definition: common.cpp:211
void AddDelimiterString(wxString &string)
Function AddDelimiterString Add un " to the start and the end of string (if not already done).
Definition: gestfich.cpp:42
wxString FindKicadFile(const wxString &shortname)
Function FindKicadFile searches the executable file shortname in KiCad binary path and return full fi...
Definition: gestfich.cpp:112
#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

References _, AddDelimiterString(), DisplayError(), FindKicadFile(), GetChars(), and ProcessExecute().

Referenced by KICAD_MANAGER_CONTROL::Execute(), DIALOG_CONFIG_EQUFILES::OnEditEquFile(), DIALOG_BOM::OnEditGenerator(), SCH_EDIT_FRAME::OnOpenPcbnew(), TREE_PROJECT_FRAME::OnOpenSelectedFileWithTextEditor(), GERBVIEW_FRAME::OnShowGerberSourceFile(), PCB_EDIT_FRAME::RunEeschema(), and DIALOG_ERC::TestErc().

◆ FindKicadFile()

wxString FindKicadFile ( const wxString &  shortname)

Function FindKicadFile searches the executable file shortname in KiCad binary path and return full file name if found or shortname if the kicad binary path is kicad/bin.

kicad binary path is found from: BinDir or environment variable KICAD or (default) c:\kicad or /usr/local/kicad or default binary path

Definition at line 112 of file gestfich.cpp.

113 {
114  // Test the presence of the file in the directory shortname of
115  // the KiCad binary path.
116 #ifndef __WXMAC__
117  wxString fullFileName = Pgm().GetExecutablePath() + shortname;
118 #else
119  wxString fullFileName = Pgm().GetExecutablePath() + wxT( "Contents/MacOS/" ) + shortname;
120 #endif
121  if( wxFileExists( fullFileName ) )
122  return fullFileName;
123 
124  // Test the presence of the file in the directory shortname
125  // defined by the environment variable KiCad.
126  if( Pgm().IsKicadEnvVariableDefined() )
127  {
128  fullFileName = Pgm().GetKicadEnvVariable() + shortname;
129 
130  if( wxFileExists( fullFileName ) )
131  return fullFileName;
132  }
133 
134  // Path list for KiCad binary files
135  const static wxChar* possibilities[] = {
136 #if defined( __WINDOWS__ )
137  wxT( "c:/kicad/bin/" ),
138  wxT( "d:/kicad/bin/" ),
139  wxT( "c:/Program Files/kicad/bin/" ),
140  wxT( "d:/Program Files/kicad/bin/" ),
141 #elif defined( __WXMAC__ )
142  // all internal paths are relative to main bundle kicad.app
143  wxT( "Contents/Applications/pcbnew.app/Contents/MacOS/" ),
144  wxT( "Contents/Applications/eeschema.app/Contents/MacOS/" ),
145  wxT( "Contents/Applications/gerbview.app/Contents/MacOS/" ),
146  wxT( "Contents/Applications/bitmap2component.app/Contents/MacOS/" ),
147  wxT( "Contents/Applications/pcb_calculator.app/Contents/MacOS/" ),
148  wxT( "Contents/Applications/pl_editor.app/Contents/MacOS/" ),
149 #else
150  wxT( "/usr/bin/" ),
151  wxT( "/usr/local/bin/" ),
152  wxT( "/usr/local/kicad/bin/" ),
153 #endif
154  };
155 
156  // find binary file from possibilities list:
157  for( unsigned i=0; i<arrayDim(possibilities); ++i )
158  {
159 #ifndef __WXMAC__
160  fullFileName = possibilities[i] + shortname;
161 #else
162  // make relative paths absolute
163  fullFileName = Pgm().GetExecutablePath() + possibilities[i] + shortname;
164 #endif
165 
166  if( wxFileExists( fullFileName ) )
167  return fullFileName;
168  }
169 
170  return shortname;
171 }
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:66
VTBL_ENTRY const wxString & GetKicadEnvVariable() const
Definition: pgm_base.h:220
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Definition: macros.h:108
VTBL_ENTRY const wxString & GetExecutablePath() const
Definition: pgm_base.h:222
size_t i
Definition: json11.cpp:649

References arrayDim(), PGM_BASE::GetExecutablePath(), PGM_BASE::GetKicadEnvVariable(), i, and Pgm().

Referenced by ExecuteFile().

◆ OpenFile()

void OpenFile ( const wxString &  file)

Definition at line 252 of file gestfich.cpp.

253 {
254  wxFileName fileName( file );
255  wxFileType* filetype = wxTheMimeTypesManager->GetFileTypeFromExtension( fileName.GetExt() );
256 
257  if( !filetype )
258  return;
259 
260  wxString command;
261  wxFileType::MessageParameters params( file );
262 
263  filetype->GetOpenCommand( &command, params );
264  delete filetype;
265 
266  if( !command.IsEmpty() )
267  ProcessExecute( command );
268 }
int ProcessExecute(const wxString &aCommandLine, int aFlags, wxProcess *callback)
Run a command in a child process.
Definition: common.cpp:211

References ProcessExecute().

Referenced by TREEPROJECT_ITEM::Activate().

◆ OpenPDF()

bool OpenPDF ( const wxString &  file)

Function OpenPDF run the PDF viewer and display a PDF file.

Parameters
file= PDF file to open
Returns
true is success, false if no PDF viewer found

Definition at line 205 of file gestfich.cpp.

206 {
207  wxString command;
208  const wxString& filename = file;
209 
211 
212  if( !Pgm().UseSystemPdfBrowser() ) // Run the preferred PDF Browser
213  {
214  command = Pgm().GetPdfBrowserName() + wxT( " '" ) + filename + wxT( "'" );
215  }
216  else
217  {
218  if( wxLaunchDefaultApplication( filename ) )
219  return true;
220 
221 #ifdef __WXMAC__
222  command = wxT( "/usr/bin/open -a '" ) + filename + wxT( "'" );
223 #endif
224  // If launching the system default PDF viewer fails, fall through with empty command
225  // string so the error message is displayed.
226  }
227 
228  if( !command.IsEmpty() )
229  {
230  if( ProcessExecute( command ) != -1 )
231  {
232  return true;
233  }
234  else
235  {
236  wxString msg;
237  msg.Printf( _( "Problem while running the PDF viewer\nCommand is \"%s\"" ), command );
238  DisplayError( NULL, msg );
239  }
240  }
241  else
242  {
243  wxString msg;
244  msg.Printf( _( "Unable to find a PDF viewer for \"%s\"" ), file );
245  DisplayError( NULL, msg );
246  }
247 
248  return false;
249 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:236
int ProcessExecute(const wxString &aCommandLine, int aFlags, wxProcess *callback)
Run a command in a child process.
Definition: common.cpp:211
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:66
VTBL_ENTRY const wxString & GetPdfBrowserName() const
Definition: pgm_base.h:226
#define _(s)
VTBL_ENTRY void ReadPdfBrowserInfos()
Function ReadPdfBrowserInfos reads the PDF browser choice from the common configuration.
Definition: eda_doc.cpp:42

References _, DisplayError(), PGM_BASE::GetPdfBrowserName(), Pgm(), ProcessExecute(), and PGM_BASE::ReadPdfBrowserInfos().

Referenced by TREEPROJECT_ITEM::Activate(), and GetAssociatedDocument().

◆ PrintFile()

void PrintFile ( const wxString &  file)

Definition at line 346 of file gestfich.cpp.

347 {
348  doPrintFile( file, false );
349 }
bool doPrintFile(const wxString &file, bool aDryRun)
Definition: gestfich.cpp:271

References doPrintFile().

Referenced by TREEPROJECT_ITEM::Print().

◆ QuoteFullPath()

wxString QuoteFullPath ( wxFileName &  fn,
wxPathFormat  format = wxPATH_NATIVE 
)

Quote return value of wxFileName::GetFullPath().

This allows file name paths with spaces to be used as parameters to ProcessExecute function calls.

Parameters
fnis the filename to wrap
formatif provided, can be used to transform the nature of the wrapped filename to another platform.

Definition at line 373 of file gestfich.cpp.

374 {
375  return wxT( "\"" ) + fn.GetFullPath( format ) + wxT( "\"" );
376 }

Referenced by SCH_EDIT_FRAME::OnOpenPcbnew(), GERBVIEW_FRAME::OnShowGerberSourceFile(), and DIALOG_ERC::TestErc().