KiCad PCB EDA Suite
Loading...
Searching...
No Matches
gestfich.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2004 Jean-Pierre Charras, [email protected]
5 * Copyright (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
26
27#include <wx/mimetype.h>
28#include <wx/dir.h>
29#include <wx/stdpaths.h>
30#include <wx/utils.h>
31
32#include <filesystem>
33
34#include <pgm_base.h>
35#include <kiplatform/io.h>
36#include <confirm.h>
37#include <core/arraydim.h>
38#include <gestfich.h>
39#include <string_utils.h>
40#include <launch_ext.h>
41#include <paths.h>
42#include "wx/tokenzr.h"
43#include <richio.h>
44#include <sexpr/sexpr.h>
45#include <sexpr/sexpr_parser.h>
46
47#include <wx/wfstream.h>
48#include <wx/fs_zip.h>
49#include <wx/zipstrm.h>
50#include <wx/tarstrm.h>
51#include <wx/zstream.h>
52
53#include <algorithm>
54#include <filesystem>
55#include <string>
56#include <system_error>
57#include <unordered_set>
58#include <vector>
59#include <core/kicad_algo.h>
60#include <paths.h>
61
62void QuoteString( wxString& string )
63{
64 if( !string.StartsWith( wxT( "\"" ) ) )
65 {
66 string.Prepend ( wxT( "\"" ) );
67 string.Append ( wxT( "\"" ) );
68 }
69}
70
71
72wxString FindKicadFile( const wxString& shortname )
73{
74 // Test the presence of the file in the directory shortname of
75 // the KiCad binary path.
76#ifndef __WXMAC__
77 wxString fullFileName = Pgm().GetExecutablePath() + shortname;
78#else
79 wxString fullFileName = Pgm().GetExecutablePath() + wxT( "Contents/MacOS/" ) + shortname;
80#endif
81 if( wxFileExists( fullFileName ) )
82 return fullFileName;
83
85 {
86 wxFileName buildDir( Pgm().GetExecutablePath(), shortname );
87
88#ifdef __WXMAC__
89 if( !buildDir.GetDirs().IsEmpty()
90 && buildDir.GetDirs().Last().Lower().EndsWith( wxT( ".app" ) ) )
91 {
92 buildDir.RemoveLastDir();
93 }
94#endif
95 buildDir.RemoveLastDir();
96#ifndef __WXMSW__
97 buildDir.AppendDir( shortname );
98#else
99 buildDir.AppendDir( shortname.BeforeLast( '.' ) );
100#endif
101
102 if( buildDir.GetDirs().Last() == "pl_editor" )
103 {
104 buildDir.RemoveLastDir();
105 buildDir.AppendDir( "pagelayout_editor" );
106 }
107
108#ifdef __WXMAC__
109 buildDir.AppendDir( shortname + wxT( ".app" ) );
110 buildDir.AppendDir( wxT( "Contents" ) );
111 buildDir.AppendDir( wxT( "MacOS" ) );
112#endif
113
114 if( wxFileExists( buildDir.GetFullPath() ) )
115 return buildDir.GetFullPath();
116 }
117
118 // Test the presence of the file in the directory shortname
119 // defined by the environment variable KiCad.
120 if( Pgm().IsKicadEnvVariableDefined() )
121 {
122 fullFileName = Pgm().GetKicadEnvVariable() + shortname;
123
124 if( wxFileExists( fullFileName ) )
125 return fullFileName;
126 }
127
128#if defined( __WINDOWS__ )
129 // KiCad can be installed highly portably on Windows, anywhere and concurrently
130 // either the "kicad file" is immediately adjacent to the exe or it's not a valid install
131 return shortname;
132#else
133
134 // Path list for KiCad binary files
135 const static wxChar* possibilities[] = {
136#if defined( __WXMAC__ )
137 // all internal paths are relative to main bundle kicad.app
138 wxT( "Contents/Applications/pcbnew.app/Contents/MacOS/" ),
139 wxT( "Contents/Applications/eeschema.app/Contents/MacOS/" ),
140 wxT( "Contents/Applications/gerbview.app/Contents/MacOS/" ),
141 wxT( "Contents/Applications/pcb_calculator.app/Contents/MacOS/" ),
142 wxT( "Contents/Applications/pl_editor.app/Contents/MacOS/" ),
143#else
144 wxT( "/usr/bin/" ),
145 wxT( "/usr/local/bin/" ),
146 wxT( "/usr/local/kicad/bin/" ),
147#endif
148 };
149
150 // find binary file from possibilities list:
151 for( unsigned i=0; i<arrayDim(possibilities); ++i )
152 {
153#ifndef __WXMAC__
154 fullFileName = possibilities[i] + shortname;
155#else
156 // make relative paths absolute
157 fullFileName = Pgm().GetExecutablePath() + possibilities[i] + shortname;
158#endif
159
160 if( wxFileExists( fullFileName ) )
161 return fullFileName;
162 }
163
164 return shortname;
165
166#endif
167}
168
169
170int ExecuteFile( const wxString& aEditorName, const wxString& aFileName, wxProcess* aCallback,
171 bool aFileForKicad )
172{
173 wxString fullEditorName;
174 std::vector<wxString> params;
175
176#ifdef __UNIX__
177 wxString param;
178 bool inSingleQuotes = false;
179 bool inDoubleQuotes = false;
180
181 auto pushParam =
182 [&]()
183 {
184 if( !param.IsEmpty() )
185 {
186 params.push_back( param );
187 param.clear();
188 }
189 };
190
191 for( wxUniChar ch : aEditorName )
192 {
193 if( inSingleQuotes )
194 {
195 if( ch == '\'' )
196 {
197 pushParam();
198 inSingleQuotes = false;
199 continue;
200 }
201 else
202 {
203 param += ch;
204 }
205 }
206 else if( inDoubleQuotes )
207 {
208 if( ch == '"' )
209 {
210 pushParam();
211 inDoubleQuotes = false;
212 }
213 else
214 {
215 param += ch;
216 }
217 }
218 else if( ch == '\'' )
219 {
220 pushParam();
221 inSingleQuotes = true;
222 }
223 else if( ch == '"' )
224 {
225 pushParam();
226 inDoubleQuotes = true;
227 }
228 else if( ch == ' ' )
229 {
230 pushParam();
231 }
232 else
233 {
234 param += ch;
235 }
236 }
237
238 pushParam();
239
240 if( aFileForKicad )
241 fullEditorName = FindKicadFile( params[0] );
242 else
243 fullEditorName = params[0];
244
245 params.erase( params.begin() );
246#else
247
248 if( aFileForKicad )
249 fullEditorName = FindKicadFile( aEditorName );
250 else
251 fullEditorName = aEditorName;
252#endif
253
254 if( wxFileExists( fullEditorName ) )
255 {
256 std::vector<const wchar_t*> args;
257
258 args.emplace_back( fullEditorName.wc_str() );
259
260 if( !params.empty() )
261 {
262 for( const wxString& p : params )
263 args.emplace_back( p.wc_str() );
264 }
265
266 if( !aFileName.IsEmpty() )
267 args.emplace_back( aFileName.wc_str() );
268
269 args.emplace_back( nullptr );
270
271 return wxExecute( const_cast<wchar_t**>( args.data() ), wxEXEC_ASYNC, aCallback );
272 }
273
274 wxString msg;
275 msg.Printf( _( "Command '%s' could not be found." ), fullEditorName );
276 DisplayErrorMessage( nullptr, msg );
277 return -1;
278}
279
280
281#ifdef __WXMSW__
282static const wxChar PATH_LIST_SEPARATOR = wxT( ';' );
283#else
284static const wxChar PATH_LIST_SEPARATOR = wxT( ':' );
285#endif
286
287
288// Windows spells it "Path", so reuse that spelling rather than hand the child two keys
289static wxString& envPathEntry( wxEnvVariableHashMap& aEnv )
290{
291#ifdef __WXMSW__
292 for( auto& [name, value] : aEnv )
293 {
294 if( name.CmpNoCase( wxS( "PATH" ) ) == 0 )
295 return value;
296 }
297#endif
298
299 return aEnv[wxS( "PATH" )];
300}
301
302
303#if !defined( __WXMSW__ ) && !defined( __WXMAC__ )
304// Symlinks are resolved so /bin and /usr/bin match on merged-usr systems
305static wxString normalizedDir( const wxString& aPath )
306{
307 std::error_code ec;
308 std::filesystem::path resolved =
309 std::filesystem::weakly_canonical( std::filesystem::path( aPath.utf8_str().data() ), ec );
310
311 if( ec )
312 return aPath;
313
314 return wxString::FromUTF8( resolved.string().c_str() );
315}
316
317
318static bool pathListContains( const wxString& aPathList, const wxString& aDir )
319{
320 wxString dir = normalizedDir( aDir );
321 wxStringTokenizer tokenizer( aPathList, PATH_LIST_SEPARATOR, wxTOKEN_STRTOK );
322
323 while( tokenizer.HasMoreTokens() )
324 {
325 if( normalizedDir( tokenizer.GetNextToken() ) == dir )
326 return true;
327 }
328
329 return false;
330}
331#endif
332
333
334int ExecuteCommandThroughShell( const wxString& aCommand, wxProcess* aProcess )
335{
336 wxExecuteEnv env;
337 wxGetEnvMap( &env.env );
338
339 // On Unix only add directories missing from PATH so a KiCad in /usr/bin cannot reorder the user's PATH
340 wxString& pathList = envPathEntry( env.env );
341 std::vector<wxString> dirs = PATHS::GetToolDirectories( PATHS::GetExecutableDir() );
342
343 for( auto it = dirs.rbegin(); it != dirs.rend(); ++it )
344 {
345#if defined( __WXMSW__ ) || defined( __WXMAC__ )
346 // Bundled tools must win over anything earlier on PATH
347 pathList = pathList.IsEmpty() ? *it : *it + PATH_LIST_SEPARATOR + pathList;
348#else
349 if( !pathListContains( pathList, *it ) )
350 pathList = pathList.IsEmpty() ? *it : *it + PATH_LIST_SEPARATOR + pathList;
351#endif
352 }
353
354#ifdef __WXMSW__
355 // The array form of wxExecute is unusable with cmd.exe. wx joins the argv elements back into a
356 // single command line, wrapping any element containing spaces in double quotes and escaping
357 // embedded quotes with backslashes. cmd.exe does not understand backslash-escaped quotes and
358 // applies its own quote-stripping rules to the /c argument, which mangles absolute paths that
359 // contain spaces or quotes. Build the command line ourselves and let cmd.exe's /s rule strip
360 // exactly the outer quote pair, passing everything between through verbatim. /d disables any
361 // AutoRun registry commands so job execution is not machine-dependent.
362 wxString shellCmd = wxS( "cmd.exe /d /s /c \"" ) + aCommand + wxS( "\"" );
363
364 return static_cast<int>( wxExecute( shellCmd, wxEXEC_SYNC, aProcess, &env ) );
365#else
366 // Invoke /bin/sh -c so glob expansion, pipes, and other shell features work. The string form of
367 // wxExecute would call execvp() directly, bypassing the shell. Hold the wchar buffers in named
368 // locals so the argv pointers stay valid on wxUSE_UNICODE_UTF8 builds where wc_str() is a temp.
369 wxWCharBuffer shell = wxString( wxS( "/bin/sh" ) ).wc_str();
370 wxWCharBuffer flag = wxString( wxS( "-c" ) ).wc_str();
371 wxWCharBuffer command = aCommand.wc_str();
372
373 const wchar_t* argv[] = { shell.data(), flag.data(), command.data(), nullptr };
374
375 return static_cast<int>( wxExecute( argv, wxEXEC_SYNC, aProcess, &env ) );
376#endif
377}
378
379
380bool OpenPDF( const wxString& file )
381{
382 wxString msg;
383 wxString filename = file;
384
386
387 if( Pgm().UseSystemPdfBrowser() )
388 {
389 if( !LaunchExternal( filename ) )
390 {
391 msg.Printf( _( "Unable to find a PDF viewer for '%s'." ), filename );
392 DisplayErrorMessage( nullptr, msg );
393 return false;
394 }
395 }
396 else
397 {
398 const wchar_t* args[3];
399
400 args[0] = Pgm().GetPdfBrowserName().wc_str();
401 args[1] = filename.wc_str();
402 args[2] = nullptr;
403
404 if( wxExecute( const_cast<wchar_t**>( args ) ) == -1 )
405 {
406 msg.Printf( _( "Problem while running the PDF viewer '%s'." ), args[0] );
407 DisplayErrorMessage( nullptr, msg );
408 return false;
409 }
410 }
411
412 return true;
413}
414
415
416void KiCopyFile( const wxString& aSrcPath, const wxString& aDestPath, wxString& aErrors )
417{
418 if( !wxCopyFile( aSrcPath, aDestPath ) )
419 {
420 wxString msg;
421
422 if( !aErrors.IsEmpty() )
423 aErrors += "\n";
424
425 msg.Printf( _( "Cannot copy file '%s'." ), aDestPath );
426 aErrors += msg;
427 }
428}
429
430
431static void traverseSEXPR( SEXPR::SEXPR* aNode, const std::function<void( SEXPR::SEXPR* )>& aVisitor )
432{
433 aVisitor( aNode );
434
435 if( aNode->IsList() )
436 {
437 for( unsigned i = 0; i < aNode->GetNumberOfChildren(); i++ )
438 traverseSEXPR( aNode->GetChild( i ), aVisitor );
439 }
440}
441
442
443void CopySexprFile( const wxString& aSrcPath, const wxString& aDestPath,
444 std::function<bool( const std::string& token, wxString& value )> aCallback,
445 wxString& aErrors )
446{
447 bool success = false;
448
449 try
450 {
451 SEXPR::PARSER parser;
452 std::unique_ptr<SEXPR::SEXPR> sexpr( parser.ParseFromFile( TO_UTF8( aSrcPath ) ) );
453
454 traverseSEXPR( sexpr.get(),
455 [&]( SEXPR::SEXPR* node )
456 {
457 if( node->IsList() && node->GetNumberOfChildren() > 1 && node->GetChild( 0 )->IsSymbol() )
458 {
459 std::string token = node->GetChild( 0 )->GetSymbol();
460 SEXPR::SEXPR_STRING* pathNode = dynamic_cast<SEXPR::SEXPR_STRING*>( node->GetChild( 1 ) );
461 SEXPR::SEXPR_SYMBOL* symNode = dynamic_cast<SEXPR::SEXPR_SYMBOL*>( node->GetChild( 1 ) );
462 wxString path;
463
464 if( pathNode )
465 path = pathNode->m_value;
466 else if( symNode )
467 path = symNode->m_value;
468
469 if( aCallback( token, path ) )
470 {
471 if( pathNode )
472 pathNode->m_value = path;
473 else if( symNode )
474 symNode->m_value = path;
475 }
476 }
477 } );
478
479
480 // Pass through the pretifier to ensure format is the same as when a file is saved by a frame
481 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( aDestPath );
482
483 // Format as a string to prevent format string attacks
484 formatter.Print( "%s", sexpr->AsString( 0 ).c_str() );
485
486 success = formatter.Finish();
487 }
488 catch( ... )
489 {
490 success = false;
491 }
492
493 if( !success )
494 {
495 wxString msg;
496
497 if( !aErrors.empty() )
498 aErrors += wxS( "\n" );
499
500 msg.Printf( _( "Cannot copy file '%s'." ), aDestPath );
501 aErrors += msg;
502 }
503}
504
505
506wxString QuoteFullPath( wxFileName& fn, wxPathFormat format )
507{
508 return wxT( "\"" ) + fn.GetFullPath( format ) + wxT( "\"" );
509}
510
511
512bool RmDirRecursive( const wxString& aFileName, wxString* aErrors )
513{
514 namespace fs = std::filesystem;
515
516 std::string rmDir = aFileName.ToStdString();
517
518 if( rmDir.length() < 3 )
519 {
520 if( aErrors )
521 *aErrors = _( "Invalid directory name, cannot remove root" );
522
523 return false;
524 }
525
526 if( !fs::exists( rmDir ) )
527 {
528 if( aErrors )
529 *aErrors = wxString::Format( _( "Directory '%s' does not exist" ), aFileName );
530
531 return false;
532 }
533
534 fs::path path( rmDir );
535
536 if( !fs::is_directory( path ) )
537 {
538 if( aErrors )
539 *aErrors = wxString::Format( _( "'%s' is not a directory" ), aFileName );
540
541 return false;
542 }
543
544 try
545 {
546 fs::remove_all( path );
547 }
548 catch( const fs::filesystem_error& e )
549 {
550 if( aErrors )
551 *aErrors = wxString::Format( _( "Error removing directory '%s': %s" ), aFileName, e.what() );
552
553 return false;
554 }
555
556 return true;
557}
558
559
560bool CopyDirectory( const wxString& aSourceDir, const wxString& aDestDir,
561 const std::vector<wxString>& aPathsWithOverwriteDisallowed, wxString& aErrors )
562{
563 wxDir dir( aSourceDir );
564
565 if( !dir.IsOpened() )
566 {
567 aErrors += wxString::Format( _( "Could not open source directory: %s" ), aSourceDir );
568 aErrors += wxT( "\n" );
569 return false;
570 }
571
572 if( !wxFileName::Mkdir( aDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
573 {
574 aErrors += wxString::Format( _( "Could not create destination directory: %s" ), aDestDir );
575 aErrors += wxT( "\n" );
576 return false;
577 }
578
579 wxString filename;
580 bool cont = dir.GetFirst( &filename );
581
582 while( cont )
583 {
584 wxString sourcePath = dir.GetNameWithSep() + filename;
585 wxString destPath = aDestDir + wxFileName::GetPathSeparator() + filename;
586
587 if( wxFileName::DirExists( sourcePath ) )
588 {
589 // Recursively copy subdirectories
590 if( !CopyDirectory( sourcePath, destPath, aPathsWithOverwriteDisallowed, aErrors ) )
591 return false;
592 }
593 else
594 {
595 // Copy files
596 if( alg::contains( aPathsWithOverwriteDisallowed, sourcePath ) && wxFileExists( destPath ) )
597 {
598 // Presumably user does not want an error on a no-overwrite condition....
599 }
600 else if( !wxCopyFile( sourcePath, destPath ) )
601 {
602 aErrors += wxString::Format( _( "Could not copy file: %s to %s" ), sourcePath, destPath );
603 return false;
604 }
605 }
606
607 cont = dir.GetNext( &filename );
608 }
609
610 return true;
611}
612
613
614bool CopyFilesOrDirectory( const wxString& aSourcePath, const wxString& aDestDir, bool aAllowOverwrites,
615 wxString& aErrors, std::vector<wxString>& aPathsWritten )
616{
617 // Parse source path and determine if it's a directory
618 wxFileName sourceFn( aSourcePath );
619 wxString sourcePath = sourceFn.GetFullPath();
620 bool isSourceDirectory = wxFileName::DirExists( sourcePath );
621 wxString baseDestDir = aDestDir;
622
623 auto performCopy =
624 [&]( const wxString& src, const wxString& dest ) -> bool
625 {
626 if( wxCopyFile( src, dest, aAllowOverwrites ) )
627 {
628 aPathsWritten.push_back( dest );
629 return true;
630 }
631
632 aErrors += wxString::Format( _( "Could not copy file: %s to %s" ), src, dest );
633 aErrors += wxT( "\n" );
634 return false;
635 };
636
637 auto processEntries =
638 [&]( const wxString& srcDir, const wxString& pattern, const wxString& destDir ) -> bool
639 {
640 wxDir dir( srcDir );
641
642 if( !dir.IsOpened() )
643 {
644 aErrors += wxString::Format( _( "Could not open source directory: %s" ), srcDir );
645 aErrors += wxT( "\n" );
646 return false;
647 }
648
649 wxString filename;
650 bool success = true;
651
652 // Find all entries matching pattern (files + directories + hidden items)
653 bool cont = dir.GetFirst( &filename, pattern, wxDIR_FILES | wxDIR_DIRS | wxDIR_HIDDEN );
654
655 while( cont )
656 {
657 const wxString entrySrc = srcDir + wxFileName::GetPathSeparator() + filename;
658 const wxString entryDest = destDir + wxFileName::GetPathSeparator() + filename;
659
660 if( !filename.Matches( wxT( "~*.lck" ) ) && !filename.Matches( wxT( "*.lck" ) ) )
661 {
662 if( wxFileName::DirExists( entrySrc ) )
663 {
664 // Recursively process subdirectories
665 if( !CopyFilesOrDirectory( entrySrc, destDir, aAllowOverwrites, aErrors, aPathsWritten ) )
666 {
667 aErrors += wxString::Format( _( "Could not copy directory: %s to %s" ),
668 entrySrc, entryDest );
669 aErrors += wxT( "\n" );
670
671 success = false;
672 }
673 }
674 else
675 {
676 // Copy individual files
677 if( !performCopy( entrySrc, entryDest ) )
678 {
679 success = false;
680 }
681 }
682 }
683
684 cont = dir.GetNext( &filename );
685 }
686
687 return success;
688 };
689
690 // If copying a directory, append its name to destination path
691 if( isSourceDirectory )
692 {
693 wxString sourceDirName = sourceFn.GetFullName();
694 baseDestDir = wxFileName( aDestDir, sourceDirName ).GetFullPath();
695 }
696
697 // Create destination directory hierarchy
698 if( !wxFileName::Mkdir( baseDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
699 {
700 aErrors += wxString::Format( _( "Could not create destination directory: %s" ), baseDestDir );
701 aErrors += wxT( "\n" );
702
703 return false;
704 }
705
706 // Execute appropriate copy operation based on source type
707 if( !isSourceDirectory )
708 {
709 const wxString fileName = sourceFn.GetFullName();
710
711 // Handle wildcard patterns in filenames
712 if( fileName.Contains( '*' ) || fileName.Contains( '?' ) )
713 {
714 const wxString dirPath = sourceFn.GetPath();
715
716 if( !wxFileName::DirExists( dirPath ) )
717 {
718 aErrors += wxString::Format( _( "Source directory does not exist: %s" ), dirPath );
719 aErrors += wxT( "\n" );
720
721 return false;
722 }
723
724 // Process all matching files in source directory
725 return processEntries( dirPath, fileName, baseDestDir );
726 }
727
728 // Single file copy operation
729 return performCopy( sourcePath, wxFileName( baseDestDir, fileName ).GetFullPath() );
730 }
731
732 // Full directory copy operation
733 return processEntries( sourcePath, wxEmptyString, baseDestDir );
734}
735
736
737bool AddDirectoryToZip( wxZipOutputStream& aZip, const wxString& aSourceDir, wxString& aErrors,
738 const wxString& aParentDir )
739{
740 wxDir dir( aSourceDir );
741
742 if( !dir.IsOpened() )
743 {
744 aErrors += wxString::Format( _( "Could not open source directory: %s" ), aSourceDir );
745 aErrors += "\n";
746 return false;
747 }
748
749 wxString filename;
750 bool cont = dir.GetFirst( &filename );
751
752 while( cont )
753 {
754 wxString sourcePath = aSourceDir + wxFileName::GetPathSeparator() + filename;
755 wxString zipPath = aParentDir + filename;
756
757 if( wxFileName::DirExists( sourcePath ) )
758 {
759 // Add directory entry to the ZIP file
760 aZip.PutNextDirEntry( zipPath + "/" );
761
762 // Recursively add subdirectories
763 if( !AddDirectoryToZip( aZip, sourcePath, aErrors, zipPath + "/" ) )
764 return false;
765 }
766 else
767 {
768 // Add file entry to the ZIP file
769 aZip.PutNextEntry( zipPath );
770 wxFFileInputStream fileStream( sourcePath );
771
772 if( !fileStream.IsOk() )
773 {
774 aErrors += wxString::Format( _( "Could not read file: %s" ), sourcePath );
775 return false;
776 }
777
778 aZip.Write( fileStream );
779 }
780
781 cont = dir.GetNext( &filename );
782 }
783
784 return true;
785}
786
787
788namespace
789{
790struct ARCHIVE_SOURCE
791{
792 wxString m_path;
793 wxString m_name;
794 wxString m_key;
795 bool m_isDirectory;
796};
797
798
799bool collectArchiveSources( const wxString& aSourceDir, const wxString& aParent,
800 DIR_LOOP_GUARD& aGuard, std::vector<ARCHIVE_SOURCE>& aSources )
801{
802 wxDir dir( aSourceDir );
803
804 if( !dir.IsOpened() )
805 return false;
806
807 wxString name;
808 bool cont = dir.GetFirst( &name, wxEmptyString, wxDIR_DEFAULT );
809
810 while( cont )
811 {
812 wxString path = wxFileName( aSourceDir, name ).GetFullPath();
813 wxString relative = aParent.IsEmpty() ? name : aParent + wxS( "/" ) + name;
814 bool isDirectory = wxDirExists( path );
815 wxString key = relative + ( isDirectory ? wxS( "/" ) : wxS( "" ) );
816 aSources.push_back( { path, relative, key, isDirectory } );
817
818 if( isDirectory )
819 {
820 if( !aGuard.ShouldDescend( path ) || !collectArchiveSources( path, relative, aGuard, aSources ) )
821 return false;
822 }
823
824 cont = dir.GetNext( &name );
825 }
826
827 return true;
828}
829
830
831bool writeArchiveContents( wxArchiveOutputStream& aArchive, const std::vector<ARCHIVE_SOURCE>& aSources )
832{
833 for( const ARCHIVE_SOURCE& source : aSources )
834 {
835 if( source.m_isDirectory )
836 {
837 if( !aArchive.PutNextDirEntry( source.m_name ) )
838 return false;
839
840 continue;
841 }
842
843 wxFFileInputStream input( source.m_path );
844 wxFileOffset expectedLength = input.IsOk() ? input.GetLength() : wxInvalidOffset;
845
846 if( !input.IsOk() || !aArchive.PutNextEntry( source.m_name, wxDateTime::Now(), expectedLength ) )
847 return false;
848
849 input.Read( aArchive );
850
851 if( input.TellI() != expectedLength || !aArchive.IsOk() || aArchive.GetLastError() != wxSTREAM_NO_ERROR
852 || !aArchive.CloseEntry() )
853 return false;
854 }
855
856 return true;
857}
858} // namespace
859
860
861bool WriteDirectoryArchive( const wxString& aSourceDir, wxOutputStream& aOut,
862 ARCHIVE_FORMAT aFormat, const wxString& aTopDir )
863{
864 if( !aOut.IsOk() || !wxDirExists( aSourceDir ) )
865 return false;
866
867 DIR_LOOP_GUARD guard( aSourceDir );
868 std::vector<ARCHIVE_SOURCE> sources;
869
870 if( !guard.IsRooted() || !collectArchiveSources( aSourceDir, aTopDir, guard, sources ) )
871 return false;
872
873 std::sort( sources.begin(), sources.end(), []( const ARCHIVE_SOURCE& a, const ARCHIVE_SOURCE& b )
874 {
875 return a.m_key < b.m_key;
876 } );
877
878 if( aFormat == ARCHIVE_FORMAT::TGZ )
879 {
880 wxZlibOutputStream gzip( aOut, -1, wxZLIB_GZIP );
881 wxTarOutputStream archive( gzip, wxTAR_PAX, wxConvUTF8 );
882 bool ok = ( aTopDir.IsEmpty() || archive.PutNextDirEntry( aTopDir ) )
883 && writeArchiveContents( archive, sources );
884 bool archiveOk = archive.IsOk() && archive.GetLastError() == wxSTREAM_NO_ERROR;
885 bool archiveClosed = archive.Close();
886 bool gzipClosed = gzip.Close();
887 return ok && archiveOk && archiveClosed && gzipClosed && aOut.IsOk();
888 }
889
890 wxZipOutputStream archive( aOut );
891 bool ok = ( aTopDir.IsEmpty() || archive.PutNextDirEntry( aTopDir ) )
892 && writeArchiveContents( archive, sources );
893 bool archiveOk = archive.IsOk() && archive.GetLastError() == wxSTREAM_NO_ERROR;
894 bool archiveClosed = archive.Close();
895 return ok && archiveOk && archiveClosed && aOut.IsOk();
896}
897
898
899bool WriteDirectoryArchive( const wxString& aSourceDir, const wxString& aArchive,
900 ARCHIVE_FORMAT aFormat, const wxString& aTopDir, wxString* aError,
901 const ARCHIVE_STREAM_FACTORY& aOpen )
902{
903 wxString tempPath;
904 wxString error;
905 FILE* fp = KIPLATFORM::IO::OpenUniqueSiblingTempFile( aArchive, wxS( "wb" ), &tempPath, &error );
906
907 if( !fp )
908 {
909 if( aError )
910 *aError = error.IsEmpty() ? _( "Cannot create temporary archive file" ) : error;
911
912 return false;
913 }
914
915 // Use a large I/O buffer for cloud-synced folders
916 // See KIPLATFORM::IO::CLOUD_SYNC_BUFFER_SIZE
917 setvbuf( fp, nullptr, _IOFBF, KIPLATFORM::IO::CLOUD_SYNC_BUFFER_SIZE );
918
919 bool ok = false;
920
921 {
922 wxFFile file( fp );
923
924 try
925 {
926 std::unique_ptr<wxOutputStream> output = aOpen ? aOpen( file )
927 : std::make_unique<wxFFileOutputStream>( file );
928
929 if( output )
930 ok = WriteDirectoryArchive( aSourceDir, *output, aFormat, aTopDir );
931 }
932 catch( const std::exception& exception )
933 {
934 ok = false;
935 error = wxString::FromUTF8( exception.what() );
936 }
937
938 bool writeOk = ok;
939 bool streamError = file.Error();
940 FILE* raw = file.Detach();
941 bool flushed = KIPLATFORM::IO::FlushToDisk( raw );
942 bool closed = fclose( raw ) == 0;
943 ok = writeOk && !streamError && flushed && closed;
944
945 if( !writeOk || streamError )
946 {
947 if( error.IsEmpty() )
948 error = _( "Write error" );
949 }
950 else if( !flushed || !closed )
951 {
952 error = _( "Cannot flush or close temporary file" );
953 }
954 }
955
956 if( ok )
957 {
958 ok = KIPLATFORM::IO::CommitTempFile( tempPath, aArchive, &error );
959
960 if( !ok && error.IsEmpty() )
961 error = _( "Cannot replace archive" );
962 }
963
964 if( !ok && wxFileExists( tempPath ) )
965 {
966 if( !wxRemoveFile( tempPath ) )
967 error += _( "\nCannot remove temporary archive file" );
968 }
969
970 if( aError )
971 *aError = error;
972
973 return ok;
974}
975
976
977std::filesystem::path ToFsPath( const wxString& aPath )
978{
979#ifdef __WXMSW__
980 return std::filesystem::path( std::wstring( aPath.wc_str() ) );
981#else
982 return std::filesystem::path( aPath.utf8_string() );
983#endif
984}
985
986
987wxString FromFsPath( const std::filesystem::path& aPath )
988{
989#ifdef __WXMSW__
990 return wxString( aPath.wstring() );
991#else
992 std::u8string utf8 = aPath.u8string();
993 return wxString::FromUTF8( reinterpret_cast<const char*>( utf8.data() ), utf8.size() );
994#endif
995}
996
997
999{
1000 if( wxDirExists( m_path ) )
1001 wxFileName::Rmdir( m_path, wxPATH_RMDIR_RECURSIVE );
1002 else if( wxFileExists( m_path ) )
1003 wxRemoveFile( m_path );
1004}
1005
1006
1007bool SCOPED_TEMP_PATH::MakeFile( const wxString& aPrefix )
1008{
1009 m_path = wxFileName::CreateTempFileName( aPrefix );
1010 return !m_path.IsEmpty();
1011}
1012
1013
1014bool SCOPED_TEMP_PATH::MakeDirectory( const wxString& aPrefix, int aPermissions )
1015{
1016 SCOPED_TEMP_PATH tempFile;
1017
1018 if( !tempFile.MakeFile( aPrefix ) || !wxRemoveFile( tempFile.Path() ) )
1019 return false;
1020
1021 wxString path = tempFile.Path();
1022
1023 // Stop owning the name before mkdir so a collision is never removed.
1024 tempFile.m_path.clear();
1025
1026 // Non-recursive creation rejects an existing file, directory or symlink.
1027 if( !wxFileName::Mkdir( path, aPermissions, 0 ) )
1028 return false;
1029
1030 m_path = path;
1031 return true;
1032}
1033
1034
1035namespace
1036{
1037
1038
1039// Best-effort canonicalisation. Empty path means "couldn't resolve"
1040// (broken symlink, ELOOP, etc.); callers treat that as "skip rather than
1041// risk recursing".
1042std::filesystem::path canonicalPath( const std::filesystem::path& aPath )
1043{
1044 std::error_code ec;
1045 std::filesystem::path canon = std::filesystem::weakly_canonical( aPath, ec );
1046
1047 return ec ? std::filesystem::path() : canon;
1048}
1049
1050
1051// True if @p aAncestor is equal to or an ancestor of @p aDescendant. Both
1052// must already be canonical so that "/a/b" and "/a/b/c" share a prefix
1053// component-wise.
1054bool isAncestorOrSame( const std::filesystem::path& aAncestor,
1055 const std::filesystem::path& aDescendant )
1056{
1057 auto a = aAncestor.begin();
1058 auto d = aDescendant.begin();
1059
1060 for( ; a != aAncestor.end() && d != aDescendant.end(); ++a, ++d )
1061 {
1062 if( *a != *d )
1063 return false;
1064 }
1065
1066 return a == aAncestor.end();
1067}
1068
1069
1070// records files dirs or both into aOutput loop-safe via DIR_LOOP_GUARD
1071class LOOP_SAFE_COLLECTOR : public wxDirTraverser
1072{
1073public:
1074 LOOP_SAFE_COLLECTOR( wxArrayString& aOutput, const wxString& aRoot, bool aCollectFiles,
1075 bool aCollectDirs ) :
1076 m_output( aOutput ),
1077 m_guard( aRoot, DIR_LOOP_POLICY::BLOCK_ROOT_ESCAPE ),
1078 m_collectFiles( aCollectFiles ),
1079 m_collectDirs( aCollectDirs )
1080 {
1081 }
1082
1083 wxDirTraverseResult OnFile( const wxString& aFilename ) override
1084 {
1085 if( m_collectFiles )
1086 m_output.Add( aFilename );
1087
1088 return wxDIR_CONTINUE;
1089 }
1090
1091 wxDirTraverseResult OnDir( const wxString& aDirname ) override
1092 {
1093 if( !m_guard.ShouldDescend( aDirname ) )
1094 return wxDIR_IGNORE;
1095
1096 if( m_collectDirs )
1097 m_output.Add( aDirname );
1098
1099 return wxDIR_CONTINUE;
1100 }
1101
1102private:
1103 wxArrayString& m_output;
1104 DIR_LOOP_GUARD m_guard;
1105 bool m_collectFiles;
1106 bool m_collectDirs;
1107};
1108
1109
1110void traverseLoopSafe( const wxString& aRoot, wxArrayString& aOutput, bool aCollectFiles,
1111 bool aCollectDirs, const wxString& aFileSpec, int aFlags )
1112{
1113 wxDir dir( aRoot );
1114
1115 if( !dir.IsOpened() )
1116 return;
1117
1118 LOOP_SAFE_COLLECTOR collector( aOutput, aRoot, aCollectFiles, aCollectDirs );
1119 dir.Traverse( collector, aFileSpec, aFlags );
1120}
1121
1122} // namespace
1123
1124
1125DIR_LOOP_GUARD::DIR_LOOP_GUARD( const wxString& aRoot, DIR_LOOP_POLICY aPolicy ) :
1126 m_root( canonicalPath( ToFsPath( aRoot ) ) ),
1127 m_policy( aPolicy )
1128{
1129 m_visited.reserve( 256 );
1130
1131 if( !m_root.empty() )
1132 m_visited.insert( m_root.generic_string() );
1133}
1134
1135
1136bool DIR_LOOP_GUARD::ShouldDescend( const wxString& aDir )
1137{
1138 const std::filesystem::path raw = ToFsPath( aDir );
1139 std::filesystem::path key;
1140
1142 {
1143 // confine fears any resolution outside the subtree so resolve every candidate
1144 // a symlinked ancestor could otherwise smuggle an ordinary looking child out
1145 const std::filesystem::path canon = canonicalPath( raw );
1146
1147 if( canon.empty() )
1148 return false;
1149
1150 if( !m_root.empty() && !isAncestorOrSame( m_root, canon ) )
1151 return false;
1152
1153 key = canon;
1154 }
1155 else
1156 {
1157 // escape only fears an upward link a real subdir cant be an ancestor of root
1158 // so skip the per-component resolve and canonicalize actual links only
1159 std::error_code ec;
1160 const bool isLink = std::filesystem::is_symlink( raw, ec );
1161
1162 if( isLink && !ec )
1163 {
1164 const std::filesystem::path canon = canonicalPath( raw );
1165
1166 if( canon.empty() )
1167 return false;
1168
1169 if( !m_root.empty() && isAncestorOrSame( canon, m_root ) )
1170 return false;
1171
1172 key = canon;
1173 }
1174 else
1175 {
1176 key = raw.lexically_normal();
1177 }
1178 }
1179
1180 return m_visited.insert( key.generic_string() ).second;
1181}
1182
1183
1184void CollectFilesLoopSafe( const wxString& aRoot, wxArrayString& aFiles, const wxString& aFileSpec,
1185 int aFlags )
1186{
1187 // Force wxDIR_FILES so files are reported and wxDIR_DIRS so Traverse descends
1188 // into subdirectories; the collector keeps directories out of the file list
1189 // and breaks loops. aFlags carries the caller's wxDIR_HIDDEN choice.
1190 traverseLoopSafe( aRoot, aFiles, true, false, aFileSpec, aFlags | wxDIR_FILES | wxDIR_DIRS );
1191}
1192
1193
1194void CollectSubdirsLoopSafe( const wxString& aRoot, wxArrayString& aDirs, int aFlags )
1195{
1196 traverseLoopSafe( aRoot, aDirs, false, true, wxEmptyString, aFlags | wxDIR_DIRS );
1197}
const char * name
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
Definition arraydim.h:27
bool ShouldDescend(const wxString &aDir)
DIR_LOOP_POLICY m_policy
Definition gestfich.h:273
std::unordered_set< std::string > m_visited
Definition gestfich.h:274
bool IsRooted() const
Definition gestfich.h:267
DIR_LOOP_GUARD(const wxString &aRoot, DIR_LOOP_POLICY aPolicy=DIR_LOOP_POLICY::CONFINE_TO_ROOT)
std::filesystem::path m_root
Definition gestfich.h:272
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:432
static bool RunningFromBuildDir()
True when KiCad runs from its build tree or KICAD_RUN_FROM_BUILD_DIR is set.
Definition paths.cpp:743
static std::vector< wxString > GetToolDirectories(const wxString &aExecutableDir)
Return the directories holding tools shipped alongside KiCad, most specific first.
Definition paths.cpp:689
static wxString GetExecutableDir()
Return the directory holding the running executable itself.
Definition paths.cpp:669
virtual const wxString & GetKicadEnvVariable() const
Definition pgm_base.h:171
virtual void ReadPdfBrowserInfos()
Read the PDF browser choice from the common configuration.
Definition pgm_base.cpp:932
virtual const wxString & GetPdfBrowserName() const
Definition pgm_base.h:177
virtual const wxString & GetExecutablePath() const
Definition pgm_base.cpp:926
bool Finish() override
Runs prettification over the buffered bytes, writes them to the sibling temp file,...
Definition richio.cpp:710
bool MakeDirectory(const wxString &aPrefix, int aPermissions=wxS_DIR_DEFAULT)
Create an empty directory with a unique name after aPrefix.
bool MakeFile(const wxString &aPrefix)
Create an empty file with a unique name after aPrefix.
SCOPED_TEMP_PATH()=default
wxString m_path
Definition gestfich.h:80
const wxString & Path() const
Definition gestfich.h:77
std::unique_ptr< SEXPR > ParseFromFile(const std::string &aFilename)
size_t GetNumberOfChildren() const
Definition sexpr.cpp:72
bool IsList() const
Definition sexpr.h:49
SEXPR * GetChild(size_t aIndex) const
Definition sexpr.cpp:50
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
std::string utf8(const wxString &aText)
#define _(s)
wxString FromFsPath(const std::filesystem::path &aPath)
Definition gestfich.cpp:987
static wxString & envPathEntry(wxEnvVariableHashMap &aEnv)
Definition gestfich.cpp:289
static bool pathListContains(const wxString &aPathList, const wxString &aDir)
Definition gestfich.cpp:318
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.
Definition gestfich.cpp:861
wxString FindKicadFile(const wxString &shortname)
Search the executable file shortname in KiCad binary path and return full file name if found or short...
Definition gestfich.cpp:72
wxString QuoteFullPath(wxFileName &fn, wxPathFormat format)
Quote return value of wxFileName::GetFullPath().
Definition gestfich.cpp:506
int ExecuteCommandThroughShell(const wxString &aCommand, wxProcess *aProcess)
Run a user-supplied command line through the platform shell so glob expansion, pipes,...
Definition gestfich.cpp:334
void CopySexprFile(const wxString &aSrcPath, const wxString &aDestPath, std::function< bool(const std::string &token, wxString &value)> aCallback, wxString &aErrors)
Definition gestfich.cpp:443
static const wxChar PATH_LIST_SEPARATOR
Definition gestfich.cpp:284
bool OpenPDF(const wxString &file)
Run the PDF viewer and display a PDF file.
Definition gestfich.cpp:380
void KiCopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
Definition gestfich.cpp:416
int ExecuteFile(const wxString &aEditorName, const wxString &aFileName, wxProcess *aCallback, bool aFileForKicad)
Call the executable file aEditorName with the parameter aFileName.
Definition gestfich.cpp:170
bool RmDirRecursive(const wxString &aFileName, wxString *aErrors)
Remove the directory aDirName and all its contents including subdirectories and their files.
Definition gestfich.cpp:512
void QuoteString(wxString &string)
Add un " to the start and the end of string (if not already done).
Definition gestfich.cpp:62
bool CopyFilesOrDirectory(const wxString &aSourcePath, const wxString &aDestDir, bool aAllowOverwrites, wxString &aErrors, std::vector< wxString > &aPathsWritten)
Definition gestfich.cpp:614
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.
Definition gestfich.cpp:977
static void traverseSEXPR(SEXPR::SEXPR *aNode, const std::function< void(SEXPR::SEXPR *)> &aVisitor)
Definition gestfich.cpp:431
bool CopyDirectory(const wxString &aSourceDir, const wxString &aDestDir, const std::vector< wxString > &aPathsWithOverwriteDisallowed, wxString &aErrors)
Copy a directory and its contents to another directory.
Definition gestfich.cpp:560
bool AddDirectoryToZip(wxZipOutputStream &aZip, const wxString &aSourceDir, wxString &aErrors, const wxString &aParentDir)
Add a directory and its contents to a zip file.
Definition gestfich.cpp:737
static wxString normalizedDir(const wxString &aPath)
Definition gestfich.cpp:305
ARCHIVE_FORMAT
Definition gestfich.h:51
std::function< std::unique_ptr< wxOutputStream >(wxFFile &)> ARCHIVE_STREAM_FACTORY
Definition gestfich.h:83
KICOMMON_API std::filesystem::path ToFsPath(const wxString &aPath)
Give aPath to std::filesystem without a detour through the C locale.
Definition gestfich.cpp:977
DIR_LOOP_POLICY
Definition gestfich.h:252
std::string source
bool LaunchExternal(const wxString &aPath)
Launches the given file or folder in the host OS.
FILE * OpenUniqueSiblingTempFile(const wxString &aTargetPath, const wxString &aMode, wxString *aTempPathOut, wxString *aError=nullptr)
Opens a fresh sibling temp file next to aTargetPath with exclusive-create semantics (POSIX O_CREAT|O_...
Definition common/io.cpp:67
bool CommitTempFile(const wxString &aTempPath, const wxString &aTargetPath, wxString *aError=nullptr)
Completes an atomic save.
static constexpr size_t CLOUD_SYNC_BUFFER_SIZE
Buffer size for file I/O operations on cloud-synced folders.
Definition io.h:169
bool FlushToDisk(FILE *aFp)
Flushes user-space buffers for aFp and forces the kernel/filesystem to commit the file's data blocks ...
Definition unix/io.cpp:182
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
std::string path