27#include <wx/mimetype.h>
29#include <wx/stdpaths.h>
38#include "wx/tokenzr.h"
43#include <wx/wfstream.h>
45#include <wx/zipstrm.h>
46#include <wx/tarstrm.h>
47#include <wx/zstream.h>
52#include <system_error>
53#include <unordered_set>
59 if( !
string.StartsWith( wxT(
"\"" ) ) )
61 string.Prepend ( wxT(
"\"" ) );
62 string.Append ( wxT(
"\"" ) );
76 if( wxFileExists( fullFileName ) )
79 if( wxGetEnv( wxT(
"KICAD_RUN_FROM_BUILD_DIR" ),
nullptr ) )
81 wxFileName buildDir(
Pgm().GetExecutablePath(), shortname );
84 if( !buildDir.GetDirs().IsEmpty()
85 && buildDir.GetDirs().Last().Lower().EndsWith( wxT(
".app" ) ) )
87 buildDir.RemoveLastDir();
90 buildDir.RemoveLastDir();
92 buildDir.AppendDir( shortname );
94 buildDir.AppendDir( shortname.BeforeLast(
'.' ) );
97 if( buildDir.GetDirs().Last() ==
"pl_editor" )
99 buildDir.RemoveLastDir();
100 buildDir.AppendDir(
"pagelayout_editor" );
104 buildDir.AppendDir( shortname + wxT(
".app" ) );
105 buildDir.AppendDir( wxT(
"Contents" ) );
106 buildDir.AppendDir( wxT(
"MacOS" ) );
109 if( wxFileExists( buildDir.GetFullPath() ) )
110 return buildDir.GetFullPath();
115 if(
Pgm().IsKicadEnvVariableDefined() )
119 if( wxFileExists( fullFileName ) )
123#if defined( __WINDOWS__ )
130 const static wxChar* possibilities[] = {
131#if defined( __WXMAC__ )
133 wxT(
"Contents/Applications/pcbnew.app/Contents/MacOS/" ),
134 wxT(
"Contents/Applications/eeschema.app/Contents/MacOS/" ),
135 wxT(
"Contents/Applications/gerbview.app/Contents/MacOS/" ),
136 wxT(
"Contents/Applications/bitmap2component.app/Contents/MacOS/" ),
137 wxT(
"Contents/Applications/pcb_calculator.app/Contents/MacOS/" ),
138 wxT(
"Contents/Applications/pl_editor.app/Contents/MacOS/" ),
141 wxT(
"/usr/local/bin/" ),
142 wxT(
"/usr/local/kicad/bin/" ),
147 for(
unsigned i=0; i<
arrayDim(possibilities); ++i )
150 fullFileName = possibilities[i] + shortname;
156 if( wxFileExists( fullFileName ) )
166int ExecuteFile(
const wxString& aEditorName,
const wxString& aFileName, wxProcess* aCallback,
169 wxString fullEditorName;
170 std::vector<wxString> params;
174 bool inSingleQuotes =
false;
175 bool inDoubleQuotes =
false;
180 if( !param.IsEmpty() )
182 params.push_back( param );
187 for( wxUniChar ch : aEditorName )
194 inSingleQuotes =
false;
202 else if( inDoubleQuotes )
207 inDoubleQuotes =
false;
214 else if( ch ==
'\'' )
217 inSingleQuotes =
true;
222 inDoubleQuotes =
true;
239 fullEditorName = params[0];
241 params.erase( params.begin() );
247 fullEditorName = aEditorName;
250 if( wxFileExists( fullEditorName ) )
252 std::vector<const wchar_t*> args;
254 args.emplace_back( fullEditorName.wc_str() );
256 if( !params.empty() )
258 for(
const wxString& p : params )
259 args.emplace_back( p.wc_str() );
262 if( !aFileName.IsEmpty() )
263 args.emplace_back( aFileName.wc_str() );
265 args.emplace_back(
nullptr );
267 return wxExecute(
const_cast<wchar_t**
>( args.data() ), wxEXEC_ASYNC, aCallback );
271 msg.Printf(
_(
"Command '%s' could not be found." ), fullEditorName );
281 wxGetEnvMap( &env.env );
284 wxString binPath = wxFileName( wxStandardPaths::Get().GetExecutablePath() ).GetPath();
285 env.env[
"PATH"] = binPath + wxS(
';' ) + env.env[
"PATH"];
294 wxString shellCmd = wxS(
"cmd.exe /d /s /c \"" ) + aCommand + wxS(
"\"" );
296 return static_cast<int>( wxExecute( shellCmd, wxEXEC_SYNC, aProcess, &env ) );
301 wxWCharBuffer shell = wxString( wxS(
"/bin/sh" ) ).wc_str();
302 wxWCharBuffer
flag = wxString( wxS(
"-c" ) ).wc_str();
303 wxWCharBuffer command = aCommand.wc_str();
305 const wchar_t* argv[] = { shell.data(),
flag.data(), command.data(),
nullptr };
307 return static_cast<int>( wxExecute( argv, wxEXEC_SYNC, aProcess ) );
315 wxString filename = file;
319 if(
Pgm().UseSystemPdfBrowser() )
323 msg.Printf(
_(
"Unable to find a PDF viewer for '%s'." ), filename );
330 const wchar_t* args[3];
333 args[1] = filename.wc_str();
336 if( wxExecute(
const_cast<wchar_t**
>( args ) ) == -1 )
338 msg.Printf(
_(
"Problem while running the PDF viewer '%s'." ), args[0] );
348void KiCopyFile(
const wxString& aSrcPath,
const wxString& aDestPath, wxString& aErrors )
350 if( !wxCopyFile( aSrcPath, aDestPath ) )
354 if( !aErrors.IsEmpty() )
357 msg.Printf(
_(
"Cannot copy file '%s'." ), aDestPath );
376 std::function<
bool(
const std::string& token, wxString& value )> aCallback,
379 bool success =
false;
389 if( node->IsList() && node->GetNumberOfChildren() > 1 && node->GetChild( 0 )->IsSymbol() )
391 std::string token = node->GetChild( 0 )->GetSymbol();
392 SEXPR::SEXPR_STRING* pathNode = dynamic_cast<SEXPR::SEXPR_STRING*>( node->GetChild( 1 ) );
393 SEXPR::SEXPR_SYMBOL* symNode = dynamic_cast<SEXPR::SEXPR_SYMBOL*>( node->GetChild( 1 ) );
397 path = pathNode->m_value;
399 path = symNode->m_value;
401 if( aCallback( token, path ) )
404 pathNode->m_value = path;
406 symNode->m_value = path;
416 formatter.
Print(
"%s", sexpr->AsString( 0 ).c_str() );
418 success = formatter.
Finish();
429 if( !aErrors.empty() )
430 aErrors += wxS(
"\n" );
432 msg.Printf(
_(
"Cannot copy file '%s'." ), aDestPath );
440 return wxT(
"\"" ) + fn.GetFullPath( format ) + wxT(
"\"" );
446 namespace fs = std::filesystem;
448 std::string rmDir = aFileName.ToStdString();
450 if( rmDir.length() < 3 )
453 *aErrors =
_(
"Invalid directory name, cannot remove root" );
458 if( !fs::exists( rmDir ) )
461 *aErrors = wxString::Format(
_(
"Directory '%s' does not exist" ), aFileName );
466 fs::path
path( rmDir );
468 if( !fs::is_directory(
path ) )
471 *aErrors = wxString::Format(
_(
"'%s' is not a directory" ), aFileName );
478 fs::remove_all(
path );
480 catch(
const fs::filesystem_error& e )
483 *aErrors = wxString::Format(
_(
"Error removing directory '%s': %s" ), aFileName, e.what() );
493 const std::vector<wxString>& aPathsWithOverwriteDisallowed, wxString& aErrors )
495 wxDir dir( aSourceDir );
497 if( !dir.IsOpened() )
499 aErrors += wxString::Format(
_(
"Could not open source directory: %s" ), aSourceDir );
500 aErrors += wxT(
"\n" );
504 if( !wxFileName::Mkdir( aDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
506 aErrors += wxString::Format(
_(
"Could not create destination directory: %s" ), aDestDir );
507 aErrors += wxT(
"\n" );
512 bool cont = dir.GetFirst( &filename );
516 wxString sourcePath = dir.GetNameWithSep() + filename;
517 wxString destPath = aDestDir + wxFileName::GetPathSeparator() + filename;
519 if( wxFileName::DirExists( sourcePath ) )
522 if( !
CopyDirectory( sourcePath, destPath, aPathsWithOverwriteDisallowed, aErrors ) )
528 if(
alg::contains( aPathsWithOverwriteDisallowed, sourcePath ) && wxFileExists( destPath ) )
532 else if( !wxCopyFile( sourcePath, destPath ) )
534 aErrors += wxString::Format(
_(
"Could not copy file: %s to %s" ), sourcePath, destPath );
539 cont = dir.GetNext( &filename );
547 wxString& aErrors, std::vector<wxString>& aPathsWritten )
550 wxFileName sourceFn( aSourcePath );
551 wxString sourcePath = sourceFn.GetFullPath();
552 bool isSourceDirectory = wxFileName::DirExists( sourcePath );
553 wxString baseDestDir = aDestDir;
556 [&](
const wxString& src,
const wxString& dest ) ->
bool
558 if( wxCopyFile( src, dest, aAllowOverwrites ) )
560 aPathsWritten.push_back( dest );
564 aErrors += wxString::Format(
_(
"Could not copy file: %s to %s" ), src, dest );
565 aErrors += wxT(
"\n" );
569 auto processEntries =
570 [&](
const wxString& srcDir,
const wxString& pattern,
const wxString& destDir ) ->
bool
574 if( !dir.IsOpened() )
576 aErrors += wxString::Format(
_(
"Could not open source directory: %s" ), srcDir );
577 aErrors += wxT(
"\n" );
585 bool cont = dir.GetFirst( &filename, pattern, wxDIR_FILES | wxDIR_DIRS | wxDIR_HIDDEN );
589 const wxString entrySrc = srcDir + wxFileName::GetPathSeparator() + filename;
590 const wxString entryDest = destDir + wxFileName::GetPathSeparator() + filename;
592 if( !filename.Matches( wxT(
"~*.lck" ) ) && !filename.Matches( wxT(
"*.lck" ) ) )
594 if( wxFileName::DirExists( entrySrc ) )
599 aErrors += wxString::Format(
_(
"Could not copy directory: %s to %s" ),
600 entrySrc, entryDest );
601 aErrors += wxT(
"\n" );
609 if( !performCopy( entrySrc, entryDest ) )
616 cont = dir.GetNext( &filename );
623 if( isSourceDirectory )
625 wxString sourceDirName = sourceFn.GetFullName();
626 baseDestDir = wxFileName( aDestDir, sourceDirName ).GetFullPath();
630 if( !wxFileName::Mkdir( baseDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
632 aErrors += wxString::Format(
_(
"Could not create destination directory: %s" ), baseDestDir );
633 aErrors += wxT(
"\n" );
639 if( !isSourceDirectory )
641 const wxString fileName = sourceFn.GetFullName();
644 if( fileName.Contains(
'*' ) || fileName.Contains(
'?' ) )
646 const wxString dirPath = sourceFn.GetPath();
648 if( !wxFileName::DirExists( dirPath ) )
650 aErrors += wxString::Format(
_(
"Source directory does not exist: %s" ), dirPath );
651 aErrors += wxT(
"\n" );
657 return processEntries( dirPath, fileName, baseDestDir );
661 return performCopy( sourcePath, wxFileName( baseDestDir, fileName ).GetFullPath() );
665 return processEntries( sourcePath, wxEmptyString, baseDestDir );
670 const wxString& aParentDir )
672 wxDir dir( aSourceDir );
674 if( !dir.IsOpened() )
676 aErrors += wxString::Format(
_(
"Could not open source directory: %s" ), aSourceDir );
682 bool cont = dir.GetFirst( &filename );
686 wxString sourcePath = aSourceDir + wxFileName::GetPathSeparator() + filename;
687 wxString zipPath = aParentDir + filename;
689 if( wxFileName::DirExists( sourcePath ) )
692 aZip.PutNextDirEntry( zipPath +
"/" );
701 aZip.PutNextEntry( zipPath );
702 wxFFileInputStream fileStream( sourcePath );
704 if( !fileStream.IsOk() )
706 aErrors += wxString::Format(
_(
"Could not read file: %s" ), sourcePath );
710 aZip.Write( fileStream );
713 cont = dir.GetNext( &filename );
731bool collectArchiveSources(
const wxString& aSourceDir,
const wxString& aParent,
734 wxDir dir( aSourceDir );
736 if( !dir.IsOpened() )
740 bool cont = dir.GetFirst( &
name, wxEmptyString, wxDIR_DEFAULT );
744 wxString
path = wxFileName( aSourceDir,
name ).GetFullPath();
745 wxString relative = aParent.IsEmpty() ?
name : aParent + wxS(
"/" ) +
name;
746 bool isDirectory = wxDirExists(
path );
747 wxString key = relative + ( isDirectory ? wxS(
"/" ) : wxS(
"" ) );
748 aSources.push_back( {
path, relative, key, isDirectory } );
756 cont = dir.GetNext( &
name );
763bool writeArchiveContents( wxArchiveOutputStream& aArchive,
const std::vector<ARCHIVE_SOURCE>& aSources )
765 for(
const ARCHIVE_SOURCE&
source : aSources )
767 if(
source.m_isDirectory )
769 if( !aArchive.PutNextDirEntry(
source.m_name ) )
775 wxFFileInputStream input(
source.m_path );
776 wxFileOffset expectedLength = input.IsOk() ? input.GetLength() : wxInvalidOffset;
778 if( !input.IsOk() || !aArchive.PutNextEntry(
source.m_name, wxDateTime::Now(), expectedLength ) )
781 input.Read( aArchive );
783 if( input.TellI() != expectedLength || !aArchive.IsOk() || aArchive.GetLastError() != wxSTREAM_NO_ERROR
784 || !aArchive.CloseEntry() )
796 if( !aOut.IsOk() || !wxDirExists( aSourceDir ) )
800 std::vector<ARCHIVE_SOURCE> sources;
802 if( !guard.
IsRooted() || !collectArchiveSources( aSourceDir, aTopDir, guard, sources ) )
805 std::sort( sources.begin(), sources.end(), [](
const ARCHIVE_SOURCE& a,
const ARCHIVE_SOURCE& b )
807 return a.m_key < b.m_key;
812 wxZlibOutputStream gzip( aOut, -1, wxZLIB_GZIP );
813 wxTarOutputStream archive( gzip, wxTAR_PAX, wxConvUTF8 );
814 bool ok = ( aTopDir.IsEmpty() || archive.PutNextDirEntry( aTopDir ) )
815 && writeArchiveContents( archive, sources );
816 bool archiveOk = archive.IsOk() && archive.GetLastError() == wxSTREAM_NO_ERROR;
817 bool archiveClosed = archive.Close();
818 bool gzipClosed = gzip.Close();
819 return ok && archiveOk && archiveClosed && gzipClosed && aOut.IsOk();
822 wxZipOutputStream archive( aOut );
823 bool ok = ( aTopDir.IsEmpty() || archive.PutNextDirEntry( aTopDir ) )
824 && writeArchiveContents( archive, sources );
825 bool archiveOk = archive.IsOk() && archive.GetLastError() == wxSTREAM_NO_ERROR;
826 bool archiveClosed = archive.Close();
827 return ok && archiveOk && archiveClosed && aOut.IsOk();
832 ARCHIVE_FORMAT aFormat,
const wxString& aTopDir, wxString* aError,
842 *aError = error.IsEmpty() ?
_(
"Cannot create temporary archive file" ) : error;
858 std::unique_ptr<wxOutputStream> output = aOpen ? aOpen( file )
859 : std::make_unique<wxFFileOutputStream>( file );
864 catch(
const std::exception& exception )
867 error = wxString::FromUTF8( exception.what() );
871 bool streamError = file.Error();
872 FILE* raw = file.Detach();
874 bool closed = fclose( raw ) == 0;
875 ok = writeOk && !streamError && flushed && closed;
877 if( !writeOk || streamError )
879 if( error.IsEmpty() )
880 error =
_(
"Write error" );
882 else if( !flushed || !closed )
884 error =
_(
"Cannot flush or close temporary file" );
892 if( !ok && error.IsEmpty() )
893 error =
_(
"Cannot replace archive" );
896 if( !ok && wxFileExists( tempPath ) )
898 if( !wxRemoveFile( tempPath ) )
899 error +=
_(
"\nCannot remove temporary archive file" );
909std::filesystem::path
ToFsPath(
const wxString& aPath )
912 return std::filesystem::path( std::wstring( aPath.wc_str() ) );
914 return std::filesystem::path( aPath.utf8_string() );
922 return wxString( aPath.wstring() );
924 std::u8string utf8 = aPath.u8string();
925 return wxString::FromUTF8(
reinterpret_cast<const char*
>( utf8.data() ), utf8.size() );
932 if( wxDirExists(
m_path ) )
933 wxFileName::Rmdir(
m_path, wxPATH_RMDIR_RECURSIVE );
934 else if( wxFileExists(
m_path ) )
941 m_path = wxFileName::CreateTempFileName( aPrefix );
952 if( wxFileName::Mkdir(
m_path, wxS_DIR_DEFAULT, 0 ) )
968std::filesystem::path canonicalPath(
const std::filesystem::path& aPath )
971 std::filesystem::path canon = std::filesystem::weakly_canonical( aPath, ec );
973 return ec ? std::filesystem::path() : canon;
980bool isAncestorOrSame(
const std::filesystem::path& aAncestor,
981 const std::filesystem::path& aDescendant )
983 auto a = aAncestor.begin();
984 auto d = aDescendant.begin();
986 for( ; a != aAncestor.end() && d != aDescendant.end(); ++a, ++d )
992 return a == aAncestor.end();
997class LOOP_SAFE_COLLECTOR :
public wxDirTraverser
1000 LOOP_SAFE_COLLECTOR( wxArrayString& aOutput,
const wxString& aRoot,
bool aCollectFiles,
1001 bool aCollectDirs ) :
1002 m_output( aOutput ),
1004 m_collectFiles( aCollectFiles ),
1005 m_collectDirs( aCollectDirs )
1009 wxDirTraverseResult OnFile(
const wxString& aFilename )
override
1011 if( m_collectFiles )
1012 m_output.Add( aFilename );
1014 return wxDIR_CONTINUE;
1017 wxDirTraverseResult OnDir(
const wxString& aDirname )
override
1019 if( !m_guard.ShouldDescend( aDirname ) )
1020 return wxDIR_IGNORE;
1023 m_output.Add( aDirname );
1025 return wxDIR_CONTINUE;
1029 wxArrayString& m_output;
1030 DIR_LOOP_GUARD m_guard;
1031 bool m_collectFiles;
1036void traverseLoopSafe(
const wxString& aRoot, wxArrayString& aOutput,
bool aCollectFiles,
1037 bool aCollectDirs,
const wxString& aFileSpec,
int aFlags )
1041 if( !dir.IsOpened() )
1044 LOOP_SAFE_COLLECTOR collector( aOutput, aRoot, aCollectFiles, aCollectDirs );
1045 dir.Traverse( collector, aFileSpec, aFlags );
1064 const std::filesystem::path raw =
ToFsPath( aDir );
1065 std::filesystem::path key;
1071 const std::filesystem::path canon = canonicalPath( raw );
1076 if( !
m_root.empty() && !isAncestorOrSame(
m_root, canon ) )
1086 const bool isLink = std::filesystem::is_symlink( raw, ec );
1090 const std::filesystem::path canon = canonicalPath( raw );
1095 if( !
m_root.empty() && isAncestorOrSame( canon,
m_root ) )
1102 key = raw.lexically_normal();
1106 return m_visited.insert( key.generic_string() ).second;
1116 traverseLoopSafe( aRoot, aFiles,
true,
false, aFileSpec, aFlags | wxDIR_FILES | wxDIR_DIRS );
1122 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
bool MakeFile(const wxString &aPrefix)
Create an empty file with a unique name after aPrefix.
bool MakeDirectory(const wxString &aPrefix)
Create an empty directory with a unique name after aPrefix.
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 FromFsPath(const std::filesystem::path &aPath)
bool WriteDirectoryArchive(const wxString &aSourceDir, wxOutputStream &aOut, ARCHIVE_FORMAT aFormat, const wxString &aTopDir)
Write directory entries in sorted archive path order, using the archive root when aTopDir is empty.
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.
std::filesystem::path ToFsPath(const wxString &aPath)
Give aPath to std::filesystem without a detour through the C locale.
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.
std::function< std::unique_ptr< wxOutputStream >(wxFFile &)> ARCHIVE_STREAM_FACTORY
KICOMMON_API std::filesystem::path ToFsPath(const wxString &aPath)
Give aPath to std::filesystem without a detour through the C locale.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
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.