27#include <wx/mimetype.h>
29#include <wx/stdpaths.h>
37#include "wx/tokenzr.h"
42#include <wx/wfstream.h>
44#include <wx/zipstrm.h>
48#include <system_error>
49#include <unordered_set>
54 if( !
string.StartsWith( wxT(
"\"" ) ) )
56 string.Prepend ( wxT(
"\"" ) );
57 string.Append ( wxT(
"\"" ) );
71 if( wxFileExists( fullFileName ) )
74 if( wxGetEnv( wxT(
"KICAD_RUN_FROM_BUILD_DIR" ),
nullptr ) )
76 wxFileName buildDir(
Pgm().GetExecutablePath(), shortname );
79 if( !buildDir.GetDirs().IsEmpty()
80 && buildDir.GetDirs().Last().Lower().EndsWith( wxT(
".app" ) ) )
82 buildDir.RemoveLastDir();
85 buildDir.RemoveLastDir();
87 buildDir.AppendDir( shortname );
89 buildDir.AppendDir( shortname.BeforeLast(
'.' ) );
92 if( buildDir.GetDirs().Last() ==
"pl_editor" )
94 buildDir.RemoveLastDir();
95 buildDir.AppendDir(
"pagelayout_editor" );
99 buildDir.AppendDir( shortname + wxT(
".app" ) );
100 buildDir.AppendDir( wxT(
"Contents" ) );
101 buildDir.AppendDir( wxT(
"MacOS" ) );
104 if( wxFileExists( buildDir.GetFullPath() ) )
105 return buildDir.GetFullPath();
110 if(
Pgm().IsKicadEnvVariableDefined() )
114 if( wxFileExists( fullFileName ) )
118#if defined( __WINDOWS__ )
125 const static wxChar* possibilities[] = {
126#if defined( __WXMAC__ )
128 wxT(
"Contents/Applications/pcbnew.app/Contents/MacOS/" ),
129 wxT(
"Contents/Applications/eeschema.app/Contents/MacOS/" ),
130 wxT(
"Contents/Applications/gerbview.app/Contents/MacOS/" ),
131 wxT(
"Contents/Applications/bitmap2component.app/Contents/MacOS/" ),
132 wxT(
"Contents/Applications/pcb_calculator.app/Contents/MacOS/" ),
133 wxT(
"Contents/Applications/pl_editor.app/Contents/MacOS/" ),
136 wxT(
"/usr/local/bin/" ),
137 wxT(
"/usr/local/kicad/bin/" ),
142 for(
unsigned i=0; i<
arrayDim(possibilities); ++i )
145 fullFileName = possibilities[i] + shortname;
151 if( wxFileExists( fullFileName ) )
161int ExecuteFile(
const wxString& aEditorName,
const wxString& aFileName, wxProcess* aCallback,
164 wxString fullEditorName;
165 std::vector<wxString> params;
169 bool inSingleQuotes =
false;
170 bool inDoubleQuotes =
false;
175 if( !param.IsEmpty() )
177 params.push_back( param );
182 for( wxUniChar ch : aEditorName )
189 inSingleQuotes =
false;
197 else if( inDoubleQuotes )
202 inDoubleQuotes =
false;
209 else if( ch ==
'\'' )
212 inSingleQuotes =
true;
217 inDoubleQuotes =
true;
234 fullEditorName = params[0];
236 params.erase( params.begin() );
242 fullEditorName = aEditorName;
245 if( wxFileExists( fullEditorName ) )
247 std::vector<const wchar_t*> args;
249 args.emplace_back( fullEditorName.wc_str() );
251 if( !params.empty() )
253 for(
const wxString& p : params )
254 args.emplace_back( p.wc_str() );
257 if( !aFileName.IsEmpty() )
258 args.emplace_back( aFileName.wc_str() );
260 args.emplace_back(
nullptr );
262 return wxExecute(
const_cast<wchar_t**
>( args.data() ), wxEXEC_ASYNC, aCallback );
266 msg.Printf(
_(
"Command '%s' could not be found." ), fullEditorName );
276 wxGetEnvMap( &env.env );
279 wxString binPath = wxFileName( wxStandardPaths::Get().GetExecutablePath() ).GetPath();
280 env.env[
"PATH"] = binPath + wxS(
';' ) + env.env[
"PATH"];
289 wxString shellCmd = wxS(
"cmd.exe /d /s /c \"" ) + aCommand + wxS(
"\"" );
291 return static_cast<int>( wxExecute( shellCmd, wxEXEC_SYNC, aProcess, &env ) );
296 wxWCharBuffer shell = wxString( wxS(
"/bin/sh" ) ).wc_str();
297 wxWCharBuffer
flag = wxString( wxS(
"-c" ) ).wc_str();
298 wxWCharBuffer command = aCommand.wc_str();
300 const wchar_t* argv[] = { shell.data(),
flag.data(), command.data(),
nullptr };
302 return static_cast<int>( wxExecute( argv, wxEXEC_SYNC, aProcess ) );
310 wxString filename = file;
314 if(
Pgm().UseSystemPdfBrowser() )
318 msg.Printf(
_(
"Unable to find a PDF viewer for '%s'." ), filename );
325 const wchar_t* args[3];
328 args[1] = filename.wc_str();
331 if( wxExecute(
const_cast<wchar_t**
>( args ) ) == -1 )
333 msg.Printf(
_(
"Problem while running the PDF viewer '%s'." ), args[0] );
343void KiCopyFile(
const wxString& aSrcPath,
const wxString& aDestPath, wxString& aErrors )
345 if( !wxCopyFile( aSrcPath, aDestPath ) )
349 if( !aErrors.IsEmpty() )
352 msg.Printf(
_(
"Cannot copy file '%s'." ), aDestPath );
371 std::function<
bool(
const std::string& token, wxString& value )> aCallback,
374 bool success =
false;
384 if( node->IsList() && node->GetNumberOfChildren() > 1 && node->GetChild( 0 )->IsSymbol() )
386 std::string token = node->GetChild( 0 )->GetSymbol();
387 SEXPR::SEXPR_STRING* pathNode = dynamic_cast<SEXPR::SEXPR_STRING*>( node->GetChild( 1 ) );
388 SEXPR::SEXPR_SYMBOL* symNode = dynamic_cast<SEXPR::SEXPR_SYMBOL*>( node->GetChild( 1 ) );
392 path = pathNode->m_value;
394 path = symNode->m_value;
396 if( aCallback( token, path ) )
399 pathNode->m_value = path;
401 symNode->m_value = path;
411 formatter.
Print(
"%s", sexpr->AsString( 0 ).c_str() );
413 success = formatter.
Finish();
424 if( !aErrors.empty() )
425 aErrors += wxS(
"\n" );
427 msg.Printf(
_(
"Cannot copy file '%s'." ), aDestPath );
435 return wxT(
"\"" ) + fn.GetFullPath( format ) + wxT(
"\"" );
441 namespace fs = std::filesystem;
443 std::string rmDir = aFileName.ToStdString();
445 if( rmDir.length() < 3 )
448 *aErrors =
_(
"Invalid directory name, cannot remove root" );
453 if( !fs::exists( rmDir ) )
456 *aErrors = wxString::Format(
_(
"Directory '%s' does not exist" ), aFileName );
461 fs::path
path( rmDir );
463 if( !fs::is_directory(
path ) )
466 *aErrors = wxString::Format(
_(
"'%s' is not a directory" ), aFileName );
473 fs::remove_all(
path );
475 catch(
const fs::filesystem_error& e )
478 *aErrors = wxString::Format(
_(
"Error removing directory '%s': %s" ), aFileName, e.what() );
488 const std::vector<wxString>& aPathsWithOverwriteDisallowed, wxString& aErrors )
490 wxDir dir( aSourceDir );
492 if( !dir.IsOpened() )
494 aErrors += wxString::Format(
_(
"Could not open source directory: %s" ), aSourceDir );
495 aErrors += wxT(
"\n" );
499 if( !wxFileName::Mkdir( aDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
501 aErrors += wxString::Format(
_(
"Could not create destination directory: %s" ), aDestDir );
502 aErrors += wxT(
"\n" );
507 bool cont = dir.GetFirst( &filename );
511 wxString sourcePath = dir.GetNameWithSep() + filename;
512 wxString destPath = aDestDir + wxFileName::GetPathSeparator() + filename;
514 if( wxFileName::DirExists( sourcePath ) )
517 if( !
CopyDirectory( sourcePath, destPath, aPathsWithOverwriteDisallowed, aErrors ) )
523 if(
alg::contains( aPathsWithOverwriteDisallowed, sourcePath ) && wxFileExists( destPath ) )
527 else if( !wxCopyFile( sourcePath, destPath ) )
529 aErrors += wxString::Format(
_(
"Could not copy file: %s to %s" ), sourcePath, destPath );
534 cont = dir.GetNext( &filename );
542 wxString& aErrors, std::vector<wxString>& aPathsWritten )
545 wxFileName sourceFn( aSourcePath );
546 wxString sourcePath = sourceFn.GetFullPath();
547 bool isSourceDirectory = wxFileName::DirExists( sourcePath );
548 wxString baseDestDir = aDestDir;
551 [&](
const wxString& src,
const wxString& dest ) ->
bool
553 if( wxCopyFile( src, dest, aAllowOverwrites ) )
555 aPathsWritten.push_back( dest );
559 aErrors += wxString::Format(
_(
"Could not copy file: %s to %s" ), src, dest );
560 aErrors += wxT(
"\n" );
564 auto processEntries =
565 [&](
const wxString& srcDir,
const wxString& pattern,
const wxString& destDir ) ->
bool
569 if( !dir.IsOpened() )
571 aErrors += wxString::Format(
_(
"Could not open source directory: %s" ), srcDir );
572 aErrors += wxT(
"\n" );
580 bool cont = dir.GetFirst( &filename, pattern, wxDIR_FILES | wxDIR_DIRS | wxDIR_HIDDEN );
584 const wxString entrySrc = srcDir + wxFileName::GetPathSeparator() + filename;
585 const wxString entryDest = destDir + wxFileName::GetPathSeparator() + filename;
587 if( !filename.Matches( wxT(
"~*.lck" ) ) && !filename.Matches( wxT(
"*.lck" ) ) )
589 if( wxFileName::DirExists( entrySrc ) )
594 aErrors += wxString::Format(
_(
"Could not copy directory: %s to %s" ),
595 entrySrc, entryDest );
596 aErrors += wxT(
"\n" );
604 if( !performCopy( entrySrc, entryDest ) )
611 cont = dir.GetNext( &filename );
618 if( isSourceDirectory )
620 wxString sourceDirName = sourceFn.GetFullName();
621 baseDestDir = wxFileName( aDestDir, sourceDirName ).GetFullPath();
625 if( !wxFileName::Mkdir( baseDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
627 aErrors += wxString::Format(
_(
"Could not create destination directory: %s" ), baseDestDir );
628 aErrors += wxT(
"\n" );
634 if( !isSourceDirectory )
636 const wxString fileName = sourceFn.GetFullName();
639 if( fileName.Contains(
'*' ) || fileName.Contains(
'?' ) )
641 const wxString dirPath = sourceFn.GetPath();
643 if( !wxFileName::DirExists( dirPath ) )
645 aErrors += wxString::Format(
_(
"Source directory does not exist: %s" ), dirPath );
646 aErrors += wxT(
"\n" );
652 return processEntries( dirPath, fileName, baseDestDir );
656 return performCopy( sourcePath, wxFileName( baseDestDir, fileName ).GetFullPath() );
660 return processEntries( sourcePath, wxEmptyString, baseDestDir );
665 const wxString& aParentDir )
667 wxDir dir( aSourceDir );
669 if( !dir.IsOpened() )
671 aErrors += wxString::Format(
_(
"Could not open source directory: %s" ), aSourceDir );
677 bool cont = dir.GetFirst( &filename );
681 wxString sourcePath = aSourceDir + wxFileName::GetPathSeparator() + filename;
682 wxString zipPath = aParentDir + filename;
684 if( wxFileName::DirExists( sourcePath ) )
687 aZip.PutNextDirEntry( zipPath +
"/" );
696 aZip.PutNextEntry( zipPath );
697 wxFFileInputStream fileStream( sourcePath );
699 if( !fileStream.IsOk() )
701 aErrors += wxString::Format(
_(
"Could not read file: %s" ), sourcePath );
705 aZip.Write( fileStream );
708 cont = dir.GetNext( &filename );
718std::filesystem::path toFsPath(
const wxString& aPath )
721 return std::filesystem::path( std::wstring( aPath.wc_str() ) );
723 return std::filesystem::path( aPath.utf8_string() );
731std::filesystem::path canonicalPath(
const std::filesystem::path& aPath )
734 std::filesystem::path canon = std::filesystem::weakly_canonical( aPath, ec );
736 return ec ? std::filesystem::path() : canon;
743bool isAncestorOrSame(
const std::filesystem::path& aAncestor,
744 const std::filesystem::path& aDescendant )
746 auto a = aAncestor.begin();
747 auto d = aDescendant.begin();
749 for( ; a != aAncestor.end() && d != aDescendant.end(); ++a, ++d )
755 return a == aAncestor.end();
760class LOOP_SAFE_COLLECTOR :
public wxDirTraverser
763 LOOP_SAFE_COLLECTOR( wxArrayString& aOutput,
const wxString& aRoot,
bool aCollectFiles,
764 bool aCollectDirs ) :
767 m_collectFiles( aCollectFiles ),
768 m_collectDirs( aCollectDirs )
772 wxDirTraverseResult OnFile(
const wxString& aFilename )
override
775 m_output.Add( aFilename );
777 return wxDIR_CONTINUE;
780 wxDirTraverseResult OnDir(
const wxString& aDirname )
override
782 if( !m_guard.ShouldDescend( aDirname ) )
786 m_output.Add( aDirname );
788 return wxDIR_CONTINUE;
792 wxArrayString& m_output;
793 DIR_LOOP_GUARD m_guard;
799void traverseLoopSafe(
const wxString& aRoot, wxArrayString& aOutput,
bool aCollectFiles,
800 bool aCollectDirs,
const wxString& aFileSpec,
int aFlags )
804 if( !dir.IsOpened() )
807 LOOP_SAFE_COLLECTOR collector( aOutput, aRoot, aCollectFiles, aCollectDirs );
808 dir.Traverse( collector, aFileSpec, aFlags );
815 m_root( canonicalPath( toFsPath( aRoot ) ) ),
827 const std::filesystem::path raw = toFsPath( aDir );
828 std::filesystem::path key;
834 const std::filesystem::path canon = canonicalPath( raw );
839 if( !
m_root.empty() && !isAncestorOrSame(
m_root, canon ) )
849 const bool isLink = std::filesystem::is_symlink( raw, ec );
853 const std::filesystem::path canon = canonicalPath( raw );
858 if( !
m_root.empty() && isAncestorOrSame( canon,
m_root ) )
865 key = raw.lexically_normal();
869 return m_visited.insert( key.generic_string() ).second;
879 traverseLoopSafe( aRoot, aFiles,
true,
false, aFileSpec, aFlags | wxDIR_FILES | wxDIR_DIRS );
885 traverseLoopSafe( aRoot, aDirs,
false,
true, wxEmptyString, aFlags | wxDIR_DIRS );
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
bool ShouldDescend(const wxString &aDir)
std::unordered_set< std::string > m_visited
DIR_LOOP_GUARD(const wxString &aRoot, DIR_LOOP_POLICY aPolicy=DIR_LOOP_POLICY::CONFINE_TO_ROOT)
std::filesystem::path m_root
virtual const wxString & GetKicadEnvVariable() const
virtual void ReadPdfBrowserInfos()
Read the PDF browser choice from the common configuration.
virtual const wxString & GetPdfBrowserName() const
virtual const wxString & GetExecutablePath() const
std::unique_ptr< SEXPR > ParseFromFile(const std::string &aFilename)
size_t GetNumberOfChildren() const
SEXPR * GetChild(size_t aIndex) const
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
This file is part of the common library.
wxString FindKicadFile(const wxString &shortname)
Search the executable file shortname in KiCad binary path and return full file name if found or short...
wxString QuoteFullPath(wxFileName &fn, wxPathFormat format)
Quote return value of wxFileName::GetFullPath().
int ExecuteCommandThroughShell(const wxString &aCommand, wxProcess *aProcess)
Run a user-supplied command line through the platform shell so glob expansion, pipes,...
void CopySexprFile(const wxString &aSrcPath, const wxString &aDestPath, std::function< bool(const std::string &token, wxString &value)> aCallback, wxString &aErrors)
bool OpenPDF(const wxString &file)
Run the PDF viewer and display a PDF file.
void KiCopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
int ExecuteFile(const wxString &aEditorName, const wxString &aFileName, wxProcess *aCallback, bool aFileForKicad)
Call the executable file aEditorName with the parameter aFileName.
bool RmDirRecursive(const wxString &aFileName, wxString *aErrors)
Remove the directory aDirName and all its contents including subdirectories and their files.
void QuoteString(wxString &string)
Add un " to the start and the end of string (if not already done).
bool CopyFilesOrDirectory(const wxString &aSourcePath, const wxString &aDestDir, bool aAllowOverwrites, wxString &aErrors, std::vector< wxString > &aPathsWritten)
void CollectSubdirsLoopSafe(const wxString &aRoot, wxArrayString &aDirs, int aFlags)
Recursively collect every subdirectory under aRoot using the same loop detection as CollectFilesLoopS...
void CollectFilesLoopSafe(const wxString &aRoot, wxArrayString &aFiles, const wxString &aFileSpec, int aFlags)
Recursively collect every file under aRoot, deduplicating subdirectories by their resolved path.
static void traverseSEXPR(SEXPR::SEXPR *aNode, const std::function< void(SEXPR::SEXPR *)> &aVisitor)
bool CopyDirectory(const wxString &aSourceDir, const wxString &aDestDir, const std::vector< wxString > &aPathsWithOverwriteDisallowed, wxString &aErrors)
Copy a directory and its contents to another directory.
bool AddDirectoryToZip(wxZipOutputStream &aZip, const wxString &aSourceDir, wxString &aErrors, const wxString &aParentDir)
Add a directory and its contents to a zip file.
bool LaunchExternal(const wxString &aPath)
Launches the given file or folder in the host OS.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
PGM_BASE & Pgm()
The global program "get" accessor.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.