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
31#include <pgm_base.h>
32#include <confirm.h>
33#include <core/arraydim.h>
34#include <gestfich.h>
35#include <string_utils.h>
36#include <launch_ext.h>
37#include "wx/tokenzr.h"
38#include <richio.h>
39#include <sexpr/sexpr.h>
40#include <sexpr/sexpr_parser.h>
41
42#include <wx/wfstream.h>
43#include <wx/fs_zip.h>
44#include <wx/zipstrm.h>
45
46#include <filesystem>
47#include <string>
48#include <system_error>
49#include <unordered_set>
50#include <core/kicad_algo.h>
51
52void QuoteString( wxString& string )
53{
54 if( !string.StartsWith( wxT( "\"" ) ) )
55 {
56 string.Prepend ( wxT( "\"" ) );
57 string.Append ( wxT( "\"" ) );
58 }
59}
60
61
62wxString FindKicadFile( const wxString& shortname )
63{
64 // Test the presence of the file in the directory shortname of
65 // the KiCad binary path.
66#ifndef __WXMAC__
67 wxString fullFileName = Pgm().GetExecutablePath() + shortname;
68#else
69 wxString fullFileName = Pgm().GetExecutablePath() + wxT( "Contents/MacOS/" ) + shortname;
70#endif
71 if( wxFileExists( fullFileName ) )
72 return fullFileName;
73
74 if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
75 {
76 wxFileName buildDir( Pgm().GetExecutablePath(), shortname );
77
78#ifdef __WXMAC__
79 if( !buildDir.GetDirs().IsEmpty()
80 && buildDir.GetDirs().Last().Lower().EndsWith( wxT( ".app" ) ) )
81 {
82 buildDir.RemoveLastDir();
83 }
84#endif
85 buildDir.RemoveLastDir();
86#ifndef __WXMSW__
87 buildDir.AppendDir( shortname );
88#else
89 buildDir.AppendDir( shortname.BeforeLast( '.' ) );
90#endif
91
92 if( buildDir.GetDirs().Last() == "pl_editor" )
93 {
94 buildDir.RemoveLastDir();
95 buildDir.AppendDir( "pagelayout_editor" );
96 }
97
98#ifdef __WXMAC__
99 buildDir.AppendDir( shortname + wxT( ".app" ) );
100 buildDir.AppendDir( wxT( "Contents" ) );
101 buildDir.AppendDir( wxT( "MacOS" ) );
102#endif
103
104 if( wxFileExists( buildDir.GetFullPath() ) )
105 return buildDir.GetFullPath();
106 }
107
108 // Test the presence of the file in the directory shortname
109 // defined by the environment variable KiCad.
110 if( Pgm().IsKicadEnvVariableDefined() )
111 {
112 fullFileName = Pgm().GetKicadEnvVariable() + shortname;
113
114 if( wxFileExists( fullFileName ) )
115 return fullFileName;
116 }
117
118#if defined( __WINDOWS__ )
119 // KiCad can be installed highly portably on Windows, anywhere and concurrently
120 // either the "kicad file" is immediately adjacent to the exe or it's not a valid install
121 return shortname;
122#else
123
124 // Path list for KiCad binary files
125 const static wxChar* possibilities[] = {
126#if defined( __WXMAC__ )
127 // all internal paths are relative to main bundle kicad.app
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/" ),
134#else
135 wxT( "/usr/bin/" ),
136 wxT( "/usr/local/bin/" ),
137 wxT( "/usr/local/kicad/bin/" ),
138#endif
139 };
140
141 // find binary file from possibilities list:
142 for( unsigned i=0; i<arrayDim(possibilities); ++i )
143 {
144#ifndef __WXMAC__
145 fullFileName = possibilities[i] + shortname;
146#else
147 // make relative paths absolute
148 fullFileName = Pgm().GetExecutablePath() + possibilities[i] + shortname;
149#endif
150
151 if( wxFileExists( fullFileName ) )
152 return fullFileName;
153 }
154
155 return shortname;
156
157#endif
158}
159
160
161int ExecuteFile( const wxString& aEditorName, const wxString& aFileName, wxProcess* aCallback,
162 bool aFileForKicad )
163{
164 wxString fullEditorName;
165 std::vector<wxString> params;
166
167#ifdef __UNIX__
168 wxString param;
169 bool inSingleQuotes = false;
170 bool inDoubleQuotes = false;
171
172 auto pushParam =
173 [&]()
174 {
175 if( !param.IsEmpty() )
176 {
177 params.push_back( param );
178 param.clear();
179 }
180 };
181
182 for( wxUniChar ch : aEditorName )
183 {
184 if( inSingleQuotes )
185 {
186 if( ch == '\'' )
187 {
188 pushParam();
189 inSingleQuotes = false;
190 continue;
191 }
192 else
193 {
194 param += ch;
195 }
196 }
197 else if( inDoubleQuotes )
198 {
199 if( ch == '"' )
200 {
201 pushParam();
202 inDoubleQuotes = false;
203 }
204 else
205 {
206 param += ch;
207 }
208 }
209 else if( ch == '\'' )
210 {
211 pushParam();
212 inSingleQuotes = true;
213 }
214 else if( ch == '"' )
215 {
216 pushParam();
217 inDoubleQuotes = true;
218 }
219 else if( ch == ' ' )
220 {
221 pushParam();
222 }
223 else
224 {
225 param += ch;
226 }
227 }
228
229 pushParam();
230
231 if( aFileForKicad )
232 fullEditorName = FindKicadFile( params[0] );
233 else
234 fullEditorName = params[0];
235
236 params.erase( params.begin() );
237#else
238
239 if( aFileForKicad )
240 fullEditorName = FindKicadFile( aEditorName );
241 else
242 fullEditorName = aEditorName;
243#endif
244
245 if( wxFileExists( fullEditorName ) )
246 {
247 std::vector<const wchar_t*> args;
248
249 args.emplace_back( fullEditorName.wc_str() );
250
251 if( !params.empty() )
252 {
253 for( const wxString& p : params )
254 args.emplace_back( p.wc_str() );
255 }
256
257 if( !aFileName.IsEmpty() )
258 args.emplace_back( aFileName.wc_str() );
259
260 args.emplace_back( nullptr );
261
262 return wxExecute( const_cast<wchar_t**>( args.data() ), wxEXEC_ASYNC, aCallback );
263 }
264
265 wxString msg;
266 msg.Printf( _( "Command '%s' could not be found." ), fullEditorName );
267 DisplayErrorMessage( nullptr, msg );
268 return -1;
269}
270
271
272int ExecuteCommandThroughShell( const wxString& aCommand, wxProcess* aProcess )
273{
274#ifdef __WXMSW__
275 wxExecuteEnv env;
276 wxGetEnvMap( &env.env );
277
278 // Prepend the app bin path so that KiCad's python is used by default
279 wxString binPath = wxFileName( wxStandardPaths::Get().GetExecutablePath() ).GetPath();
280 env.env["PATH"] = binPath + wxS( ';' ) + env.env["PATH"];
281
282 // The array form of wxExecute is unusable with cmd.exe. wx joins the argv elements back into a
283 // single command line, wrapping any element containing spaces in double quotes and escaping
284 // embedded quotes with backslashes. cmd.exe does not understand backslash-escaped quotes and
285 // applies its own quote-stripping rules to the /c argument, which mangles absolute paths that
286 // contain spaces or quotes. Build the command line ourselves and let cmd.exe's /s rule strip
287 // exactly the outer quote pair, passing everything between through verbatim. /d disables any
288 // AutoRun registry commands so job execution is not machine-dependent.
289 wxString shellCmd = wxS( "cmd.exe /d /s /c \"" ) + aCommand + wxS( "\"" );
290
291 return static_cast<int>( wxExecute( shellCmd, wxEXEC_SYNC, aProcess, &env ) );
292#else
293 // Invoke /bin/sh -c so glob expansion, pipes, and other shell features work. The string form of
294 // wxExecute would call execvp() directly, bypassing the shell. Hold the wchar buffers in named
295 // locals so the argv pointers stay valid on wxUSE_UNICODE_UTF8 builds where wc_str() is a temp.
296 wxWCharBuffer shell = wxString( wxS( "/bin/sh" ) ).wc_str();
297 wxWCharBuffer flag = wxString( wxS( "-c" ) ).wc_str();
298 wxWCharBuffer command = aCommand.wc_str();
299
300 const wchar_t* argv[] = { shell.data(), flag.data(), command.data(), nullptr };
301
302 return static_cast<int>( wxExecute( argv, wxEXEC_SYNC, aProcess ) );
303#endif
304}
305
306
307bool OpenPDF( const wxString& file )
308{
309 wxString msg;
310 wxString filename = file;
311
313
314 if( Pgm().UseSystemPdfBrowser() )
315 {
316 if( !LaunchExternal( filename ) )
317 {
318 msg.Printf( _( "Unable to find a PDF viewer for '%s'." ), filename );
319 DisplayErrorMessage( nullptr, msg );
320 return false;
321 }
322 }
323 else
324 {
325 const wchar_t* args[3];
326
327 args[0] = Pgm().GetPdfBrowserName().wc_str();
328 args[1] = filename.wc_str();
329 args[2] = nullptr;
330
331 if( wxExecute( const_cast<wchar_t**>( args ) ) == -1 )
332 {
333 msg.Printf( _( "Problem while running the PDF viewer '%s'." ), args[0] );
334 DisplayErrorMessage( nullptr, msg );
335 return false;
336 }
337 }
338
339 return true;
340}
341
342
343void KiCopyFile( const wxString& aSrcPath, const wxString& aDestPath, wxString& aErrors )
344{
345 if( !wxCopyFile( aSrcPath, aDestPath ) )
346 {
347 wxString msg;
348
349 if( !aErrors.IsEmpty() )
350 aErrors += "\n";
351
352 msg.Printf( _( "Cannot copy file '%s'." ), aDestPath );
353 aErrors += msg;
354 }
355}
356
357
358static void traverseSEXPR( SEXPR::SEXPR* aNode, const std::function<void( SEXPR::SEXPR* )>& aVisitor )
359{
360 aVisitor( aNode );
361
362 if( aNode->IsList() )
363 {
364 for( unsigned i = 0; i < aNode->GetNumberOfChildren(); i++ )
365 traverseSEXPR( aNode->GetChild( i ), aVisitor );
366 }
367}
368
369
370void CopySexprFile( const wxString& aSrcPath, const wxString& aDestPath,
371 std::function<bool( const std::string& token, wxString& value )> aCallback,
372 wxString& aErrors )
373{
374 bool success = false;
375
376 try
377 {
378 SEXPR::PARSER parser;
379 std::unique_ptr<SEXPR::SEXPR> sexpr( parser.ParseFromFile( TO_UTF8( aSrcPath ) ) );
380
381 traverseSEXPR( sexpr.get(),
382 [&]( SEXPR::SEXPR* node )
383 {
384 if( node->IsList() && node->GetNumberOfChildren() > 1 && node->GetChild( 0 )->IsSymbol() )
385 {
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 ) );
389 wxString path;
390
391 if( pathNode )
392 path = pathNode->m_value;
393 else if( symNode )
394 path = symNode->m_value;
395
396 if( aCallback( token, path ) )
397 {
398 if( pathNode )
399 pathNode->m_value = path;
400 else if( symNode )
401 symNode->m_value = path;
402 }
403 }
404 } );
405
406
407 // Pass through the pretifier to ensure format is the same as when a file is saved by a frame
408 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( aDestPath );
409
410 // Format as a string to prevent format string attacks
411 formatter.Print( "%s", sexpr->AsString( 0 ).c_str() );
412
413 success = formatter.Finish();
414 }
415 catch( ... )
416 {
417 success = false;
418 }
419
420 if( !success )
421 {
422 wxString msg;
423
424 if( !aErrors.empty() )
425 aErrors += wxS( "\n" );
426
427 msg.Printf( _( "Cannot copy file '%s'." ), aDestPath );
428 aErrors += msg;
429 }
430}
431
432
433wxString QuoteFullPath( wxFileName& fn, wxPathFormat format )
434{
435 return wxT( "\"" ) + fn.GetFullPath( format ) + wxT( "\"" );
436}
437
438
439bool RmDirRecursive( const wxString& aFileName, wxString* aErrors )
440{
441 namespace fs = std::filesystem;
442
443 std::string rmDir = aFileName.ToStdString();
444
445 if( rmDir.length() < 3 )
446 {
447 if( aErrors )
448 *aErrors = _( "Invalid directory name, cannot remove root" );
449
450 return false;
451 }
452
453 if( !fs::exists( rmDir ) )
454 {
455 if( aErrors )
456 *aErrors = wxString::Format( _( "Directory '%s' does not exist" ), aFileName );
457
458 return false;
459 }
460
461 fs::path path( rmDir );
462
463 if( !fs::is_directory( path ) )
464 {
465 if( aErrors )
466 *aErrors = wxString::Format( _( "'%s' is not a directory" ), aFileName );
467
468 return false;
469 }
470
471 try
472 {
473 fs::remove_all( path );
474 }
475 catch( const fs::filesystem_error& e )
476 {
477 if( aErrors )
478 *aErrors = wxString::Format( _( "Error removing directory '%s': %s" ), aFileName, e.what() );
479
480 return false;
481 }
482
483 return true;
484}
485
486
487bool CopyDirectory( const wxString& aSourceDir, const wxString& aDestDir,
488 const std::vector<wxString>& aPathsWithOverwriteDisallowed, wxString& aErrors )
489{
490 wxDir dir( aSourceDir );
491
492 if( !dir.IsOpened() )
493 {
494 aErrors += wxString::Format( _( "Could not open source directory: %s" ), aSourceDir );
495 aErrors += wxT( "\n" );
496 return false;
497 }
498
499 if( !wxFileName::Mkdir( aDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
500 {
501 aErrors += wxString::Format( _( "Could not create destination directory: %s" ), aDestDir );
502 aErrors += wxT( "\n" );
503 return false;
504 }
505
506 wxString filename;
507 bool cont = dir.GetFirst( &filename );
508
509 while( cont )
510 {
511 wxString sourcePath = dir.GetNameWithSep() + filename;
512 wxString destPath = aDestDir + wxFileName::GetPathSeparator() + filename;
513
514 if( wxFileName::DirExists( sourcePath ) )
515 {
516 // Recursively copy subdirectories
517 if( !CopyDirectory( sourcePath, destPath, aPathsWithOverwriteDisallowed, aErrors ) )
518 return false;
519 }
520 else
521 {
522 // Copy files
523 if( alg::contains( aPathsWithOverwriteDisallowed, sourcePath ) && wxFileExists( destPath ) )
524 {
525 // Presumably user does not want an error on a no-overwrite condition....
526 }
527 else if( !wxCopyFile( sourcePath, destPath ) )
528 {
529 aErrors += wxString::Format( _( "Could not copy file: %s to %s" ), sourcePath, destPath );
530 return false;
531 }
532 }
533
534 cont = dir.GetNext( &filename );
535 }
536
537 return true;
538}
539
540
541bool CopyFilesOrDirectory( const wxString& aSourcePath, const wxString& aDestDir, bool aAllowOverwrites,
542 wxString& aErrors, std::vector<wxString>& aPathsWritten )
543{
544 // Parse source path and determine if it's a directory
545 wxFileName sourceFn( aSourcePath );
546 wxString sourcePath = sourceFn.GetFullPath();
547 bool isSourceDirectory = wxFileName::DirExists( sourcePath );
548 wxString baseDestDir = aDestDir;
549
550 auto performCopy =
551 [&]( const wxString& src, const wxString& dest ) -> bool
552 {
553 if( wxCopyFile( src, dest, aAllowOverwrites ) )
554 {
555 aPathsWritten.push_back( dest );
556 return true;
557 }
558
559 aErrors += wxString::Format( _( "Could not copy file: %s to %s" ), src, dest );
560 aErrors += wxT( "\n" );
561 return false;
562 };
563
564 auto processEntries =
565 [&]( const wxString& srcDir, const wxString& pattern, const wxString& destDir ) -> bool
566 {
567 wxDir dir( srcDir );
568
569 if( !dir.IsOpened() )
570 {
571 aErrors += wxString::Format( _( "Could not open source directory: %s" ), srcDir );
572 aErrors += wxT( "\n" );
573 return false;
574 }
575
576 wxString filename;
577 bool success = true;
578
579 // Find all entries matching pattern (files + directories + hidden items)
580 bool cont = dir.GetFirst( &filename, pattern, wxDIR_FILES | wxDIR_DIRS | wxDIR_HIDDEN );
581
582 while( cont )
583 {
584 const wxString entrySrc = srcDir + wxFileName::GetPathSeparator() + filename;
585 const wxString entryDest = destDir + wxFileName::GetPathSeparator() + filename;
586
587 if( !filename.Matches( wxT( "~*.lck" ) ) && !filename.Matches( wxT( "*.lck" ) ) )
588 {
589 if( wxFileName::DirExists( entrySrc ) )
590 {
591 // Recursively process subdirectories
592 if( !CopyFilesOrDirectory( entrySrc, destDir, aAllowOverwrites, aErrors, aPathsWritten ) )
593 {
594 aErrors += wxString::Format( _( "Could not copy directory: %s to %s" ),
595 entrySrc, entryDest );
596 aErrors += wxT( "\n" );
597
598 success = false;
599 }
600 }
601 else
602 {
603 // Copy individual files
604 if( !performCopy( entrySrc, entryDest ) )
605 {
606 success = false;
607 }
608 }
609 }
610
611 cont = dir.GetNext( &filename );
612 }
613
614 return success;
615 };
616
617 // If copying a directory, append its name to destination path
618 if( isSourceDirectory )
619 {
620 wxString sourceDirName = sourceFn.GetFullName();
621 baseDestDir = wxFileName( aDestDir, sourceDirName ).GetFullPath();
622 }
623
624 // Create destination directory hierarchy
625 if( !wxFileName::Mkdir( baseDestDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
626 {
627 aErrors += wxString::Format( _( "Could not create destination directory: %s" ), baseDestDir );
628 aErrors += wxT( "\n" );
629
630 return false;
631 }
632
633 // Execute appropriate copy operation based on source type
634 if( !isSourceDirectory )
635 {
636 const wxString fileName = sourceFn.GetFullName();
637
638 // Handle wildcard patterns in filenames
639 if( fileName.Contains( '*' ) || fileName.Contains( '?' ) )
640 {
641 const wxString dirPath = sourceFn.GetPath();
642
643 if( !wxFileName::DirExists( dirPath ) )
644 {
645 aErrors += wxString::Format( _( "Source directory does not exist: %s" ), dirPath );
646 aErrors += wxT( "\n" );
647
648 return false;
649 }
650
651 // Process all matching files in source directory
652 return processEntries( dirPath, fileName, baseDestDir );
653 }
654
655 // Single file copy operation
656 return performCopy( sourcePath, wxFileName( baseDestDir, fileName ).GetFullPath() );
657 }
658
659 // Full directory copy operation
660 return processEntries( sourcePath, wxEmptyString, baseDestDir );
661}
662
663
664bool AddDirectoryToZip( wxZipOutputStream& aZip, const wxString& aSourceDir, wxString& aErrors,
665 const wxString& aParentDir )
666{
667 wxDir dir( aSourceDir );
668
669 if( !dir.IsOpened() )
670 {
671 aErrors += wxString::Format( _( "Could not open source directory: %s" ), aSourceDir );
672 aErrors += "\n";
673 return false;
674 }
675
676 wxString filename;
677 bool cont = dir.GetFirst( &filename );
678
679 while( cont )
680 {
681 wxString sourcePath = aSourceDir + wxFileName::GetPathSeparator() + filename;
682 wxString zipPath = aParentDir + filename;
683
684 if( wxFileName::DirExists( sourcePath ) )
685 {
686 // Add directory entry to the ZIP file
687 aZip.PutNextDirEntry( zipPath + "/" );
688
689 // Recursively add subdirectories
690 if( !AddDirectoryToZip( aZip, sourcePath, aErrors, zipPath + "/" ) )
691 return false;
692 }
693 else
694 {
695 // Add file entry to the ZIP file
696 aZip.PutNextEntry( zipPath );
697 wxFFileInputStream fileStream( sourcePath );
698
699 if( !fileStream.IsOk() )
700 {
701 aErrors += wxString::Format( _( "Could not read file: %s" ), sourcePath );
702 return false;
703 }
704
705 aZip.Write( fileStream );
706 }
707
708 cont = dir.GetNext( &filename );
709 }
710
711 return true;
712}
713
714
715namespace
716{
717
718std::filesystem::path toFsPath( const wxString& aPath )
719{
720#ifdef __WXMSW__
721 return std::filesystem::path( std::wstring( aPath.wc_str() ) );
722#else
723 return std::filesystem::path( aPath.utf8_string() );
724#endif
725}
726
727
728// Best-effort canonicalisation. Empty path means "couldn't resolve"
729// (broken symlink, ELOOP, etc.); callers treat that as "skip rather than
730// risk recursing".
731std::filesystem::path canonicalPath( const std::filesystem::path& aPath )
732{
733 std::error_code ec;
734 std::filesystem::path canon = std::filesystem::weakly_canonical( aPath, ec );
735
736 return ec ? std::filesystem::path() : canon;
737}
738
739
740// True if @p aAncestor is equal to or an ancestor of @p aDescendant. Both
741// must already be canonical so that "/a/b" and "/a/b/c" share a prefix
742// component-wise.
743bool isAncestorOrSame( const std::filesystem::path& aAncestor,
744 const std::filesystem::path& aDescendant )
745{
746 auto a = aAncestor.begin();
747 auto d = aDescendant.begin();
748
749 for( ; a != aAncestor.end() && d != aDescendant.end(); ++a, ++d )
750 {
751 if( *a != *d )
752 return false;
753 }
754
755 return a == aAncestor.end();
756}
757
758
759// records files dirs or both into aOutput loop-safe via DIR_LOOP_GUARD
760class LOOP_SAFE_COLLECTOR : public wxDirTraverser
761{
762public:
763 LOOP_SAFE_COLLECTOR( wxArrayString& aOutput, const wxString& aRoot, bool aCollectFiles,
764 bool aCollectDirs ) :
765 m_output( aOutput ),
766 m_guard( aRoot, DIR_LOOP_POLICY::BLOCK_ROOT_ESCAPE ),
767 m_collectFiles( aCollectFiles ),
768 m_collectDirs( aCollectDirs )
769 {
770 }
771
772 wxDirTraverseResult OnFile( const wxString& aFilename ) override
773 {
774 if( m_collectFiles )
775 m_output.Add( aFilename );
776
777 return wxDIR_CONTINUE;
778 }
779
780 wxDirTraverseResult OnDir( const wxString& aDirname ) override
781 {
782 if( !m_guard.ShouldDescend( aDirname ) )
783 return wxDIR_IGNORE;
784
785 if( m_collectDirs )
786 m_output.Add( aDirname );
787
788 return wxDIR_CONTINUE;
789 }
790
791private:
792 wxArrayString& m_output;
793 DIR_LOOP_GUARD m_guard;
794 bool m_collectFiles;
795 bool m_collectDirs;
796};
797
798
799void traverseLoopSafe( const wxString& aRoot, wxArrayString& aOutput, bool aCollectFiles,
800 bool aCollectDirs, const wxString& aFileSpec, int aFlags )
801{
802 wxDir dir( aRoot );
803
804 if( !dir.IsOpened() )
805 return;
806
807 LOOP_SAFE_COLLECTOR collector( aOutput, aRoot, aCollectFiles, aCollectDirs );
808 dir.Traverse( collector, aFileSpec, aFlags );
809}
810
811} // namespace
812
813
814DIR_LOOP_GUARD::DIR_LOOP_GUARD( const wxString& aRoot, DIR_LOOP_POLICY aPolicy ) :
815 m_root( canonicalPath( toFsPath( aRoot ) ) ),
816 m_policy( aPolicy )
817{
818 m_visited.reserve( 256 );
819
820 if( !m_root.empty() )
821 m_visited.insert( m_root.generic_string() );
822}
823
824
825bool DIR_LOOP_GUARD::ShouldDescend( const wxString& aDir )
826{
827 const std::filesystem::path raw = toFsPath( aDir );
828 std::filesystem::path key;
829
831 {
832 // confine fears any resolution outside the subtree so resolve every candidate
833 // a symlinked ancestor could otherwise smuggle an ordinary looking child out
834 const std::filesystem::path canon = canonicalPath( raw );
835
836 if( canon.empty() )
837 return false;
838
839 if( !m_root.empty() && !isAncestorOrSame( m_root, canon ) )
840 return false;
841
842 key = canon;
843 }
844 else
845 {
846 // escape only fears an upward link a real subdir cant be an ancestor of root
847 // so skip the per-component resolve and canonicalize actual links only
848 std::error_code ec;
849 const bool isLink = std::filesystem::is_symlink( raw, ec );
850
851 if( isLink && !ec )
852 {
853 const std::filesystem::path canon = canonicalPath( raw );
854
855 if( canon.empty() )
856 return false;
857
858 if( !m_root.empty() && isAncestorOrSame( canon, m_root ) )
859 return false;
860
861 key = canon;
862 }
863 else
864 {
865 key = raw.lexically_normal();
866 }
867 }
868
869 return m_visited.insert( key.generic_string() ).second;
870}
871
872
873void CollectFilesLoopSafe( const wxString& aRoot, wxArrayString& aFiles, const wxString& aFileSpec,
874 int aFlags )
875{
876 // Force wxDIR_FILES so files are reported and wxDIR_DIRS so Traverse descends
877 // into subdirectories; the collector keeps directories out of the file list
878 // and breaks loops. aFlags carries the caller's wxDIR_HIDDEN choice.
879 traverseLoopSafe( aRoot, aFiles, true, false, aFileSpec, aFlags | wxDIR_FILES | wxDIR_DIRS );
880}
881
882
883void CollectSubdirsLoopSafe( const wxString& aRoot, wxArrayString& aDirs, int aFlags )
884{
885 traverseLoopSafe( aRoot, aDirs, false, true, wxEmptyString, aFlags | wxDIR_DIRS );
886}
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
Definition arraydim.h:27
bool ShouldDescend(const wxString &aDir)
Definition gestfich.cpp:825
DIR_LOOP_POLICY m_policy
Definition gestfich.h:221
std::unordered_set< std::string > m_visited
Definition gestfich.h:222
DIR_LOOP_GUARD(const wxString &aRoot, DIR_LOOP_POLICY aPolicy=DIR_LOOP_POLICY::CONFINE_TO_ROOT)
Definition gestfich.cpp:814
std::filesystem::path m_root
Definition gestfich.h:220
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:418
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:894
virtual const wxString & GetPdfBrowserName() const
Definition pgm_base.h:177
virtual const wxString & GetExecutablePath() const
Definition pgm_base.cpp:888
bool Finish() override
Runs prettification over the buffered bytes, writes them to the sibling temp file,...
Definition richio.cpp:690
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.
#define _(s)
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:62
wxString QuoteFullPath(wxFileName &fn, wxPathFormat format)
Quote return value of wxFileName::GetFullPath().
Definition gestfich.cpp:433
int ExecuteCommandThroughShell(const wxString &aCommand, wxProcess *aProcess)
Run a user-supplied command line through the platform shell so glob expansion, pipes,...
Definition gestfich.cpp:272
void CopySexprFile(const wxString &aSrcPath, const wxString &aDestPath, std::function< bool(const std::string &token, wxString &value)> aCallback, wxString &aErrors)
Definition gestfich.cpp:370
bool OpenPDF(const wxString &file)
Run the PDF viewer and display a PDF file.
Definition gestfich.cpp:307
void KiCopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
Definition gestfich.cpp:343
int ExecuteFile(const wxString &aEditorName, const wxString &aFileName, wxProcess *aCallback, bool aFileForKicad)
Call the executable file aEditorName with the parameter aFileName.
Definition gestfich.cpp:161
bool RmDirRecursive(const wxString &aFileName, wxString *aErrors)
Remove the directory aDirName and all its contents including subdirectories and their files.
Definition gestfich.cpp:439
void QuoteString(wxString &string)
Add un " to the start and the end of string (if not already done).
Definition gestfich.cpp:52
bool CopyFilesOrDirectory(const wxString &aSourcePath, const wxString &aDestDir, bool aAllowOverwrites, wxString &aErrors, std::vector< wxString > &aPathsWritten)
Definition gestfich.cpp:541
void CollectSubdirsLoopSafe(const wxString &aRoot, wxArrayString &aDirs, int aFlags)
Recursively collect every subdirectory under aRoot using the same loop detection as CollectFilesLoopS...
Definition gestfich.cpp:883
void CollectFilesLoopSafe(const wxString &aRoot, wxArrayString &aFiles, const wxString &aFileSpec, int aFlags)
Recursively collect every file under aRoot, deduplicating subdirectories by their resolved path.
Definition gestfich.cpp:873
static void traverseSEXPR(SEXPR::SEXPR *aNode, const std::function< void(SEXPR::SEXPR *)> &aVisitor)
Definition gestfich.cpp:358
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:487
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:664
DIR_LOOP_POLICY
Definition gestfich.h:200
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.
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