KiCad PCB EDA Suite
Loading...
Searching...
No Matches
common.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) 2014-2020 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 1992-2023, 2024 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, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26#include <eda_base_frame.h>
27#include <kiplatform/app.h>
28#include <project.h>
29#include <common.h>
30#include <env_vars.h>
31#include <reporter.h>
32#include <macros.h>
33#include <mutex>
34#include <wx/config.h>
35#include <wx/log.h>
36#include <wx/msgdlg.h>
37#include <wx/stdpaths.h>
38#include <wx/url.h>
39#include <wx/utils.h>
40#include <wx/regex.h>
41
42#ifdef _WIN32
43#include <Windows.h>
44#endif
45
46
48{
52#ifdef __WINDOWS__
53 Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
54#endif
56};
57
58
59wxString ExpandTextVars( const wxString& aSource, const PROJECT* aProject )
60{
61 std::function<bool( wxString* )> projectResolver =
62 [&]( wxString* token ) -> bool
63 {
64 return aProject->TextVarResolver( token );
65 };
66
67 return ExpandTextVars( aSource, &projectResolver );
68}
69
70
71wxString ExpandTextVars( const wxString& aSource,
72 const std::function<bool( wxString* )>* aResolver )
73{
74 static wxRegEx userDefinedWarningError( wxS( "^(ERC|DRC)_(WARNING|ERROR).*$" ) );
75 wxString newbuf;
76 size_t sourceLen = aSource.length();
77
78 newbuf.Alloc( sourceLen ); // best guess (improves performance)
79
80 for( size_t i = 0; i < sourceLen; ++i )
81 {
82 if( aSource[i] == '$' && i + 1 < sourceLen && aSource[i+1] == '{' )
83 {
84 wxString token;
85
86 for( i = i + 2; i < sourceLen; ++i )
87 {
88 if( aSource[i] == '}' )
89 break;
90 else
91 token.append( aSource[i] );
92 }
93
94 if( token.IsEmpty() )
95 continue;
96
97 if( userDefinedWarningError.Matches( token ) )
98 {
99 // Only show user-defined warnings/errors during ERC/DRC
100 }
101 else if( aResolver && (*aResolver)( &token ) )
102 {
103 newbuf.append( token );
104 }
105 else
106 {
107 // Token not resolved: leave the reference unchanged
108 newbuf.append( "${" + token + "}" );
109 }
110 }
111 else
112 {
113 newbuf.append( aSource[i] );
114 }
115 }
116
117 return newbuf;
118}
119
120
121wxString GetTextVars( const wxString& aSource )
122{
123 std::function<bool( wxString* )> tokenExtractor =
124 [&]( wxString* token ) -> bool
125 {
126 return true;
127 };
128
129 return ExpandTextVars( aSource, &tokenExtractor );
130}
131
132
133bool IsTextVar( const wxString& aSource )
134{
135 return aSource.StartsWith( wxS( "${" ) );
136}
137
138
139//
140// Stolen from wxExpandEnvVars and then heavily optimized
141//
142wxString KIwxExpandEnvVars( const wxString& str, const PROJECT* aProject, std::set<wxString>* aSet = nullptr )
143{
144 // If the same string is inserted twice, we have a loop
145 if( aSet )
146 {
147 if( auto [ _, result ] = aSet->insert( str ); !result )
148 return str;
149 }
150
151 size_t strlen = str.length();
152
153 wxString strResult;
154 strResult.Alloc( strlen ); // best guess (improves performance)
155
156 auto getVersionedEnvVar =
157 []( const wxString& aMatch, wxString& aResult ) -> bool
158 {
159 for ( const wxString& var : ENV_VAR::GetPredefinedEnvVars() )
160 {
161 if( var.Matches( aMatch ) )
162 {
163 const auto value = ENV_VAR::GetEnvVar<wxString>( var );
164
165 if( !value )
166 continue;
167
168 aResult += *value;
169 return true;
170 }
171 }
172
173 return false;
174 };
175
176 for( size_t n = 0; n < strlen; n++ )
177 {
178 wxUniChar str_n = str[n];
179
180 switch( str_n.GetValue() )
181 {
182#ifdef __WINDOWS__
183 case wxT( '%' ):
184#endif // __WINDOWS__
185 case wxT( '$' ):
186 {
187 Bracket bracket;
188#ifdef __WINDOWS__
189 if( str_n == wxT( '%' ) )
190 {
191 bracket = Bracket_Windows;
192 }
193 else
194#endif // __WINDOWS__
195 if( n == strlen - 1 )
196 {
197 bracket = Bracket_None;
198 }
199 else
200 {
201 switch( str[n + 1].GetValue() )
202 {
203 case wxT( '(' ):
204 bracket = Bracket_Normal;
205 str_n = str[++n]; // skip the bracket
206 break;
207
208 case wxT( '{' ):
209 bracket = Bracket_Curly;
210 str_n = str[++n]; // skip the bracket
211 break;
212
213 default:
214 bracket = Bracket_None;
215 }
216 }
217
218 size_t m = n + 1;
219
220 if( m >= strlen )
221 break;
222
223 wxUniChar str_m = str[m];
224
225 while( wxIsalnum( str_m ) || str_m == wxT( '_' ) || str_m == wxT( ':' ) )
226 {
227 if( ++m == strlen )
228 {
229 str_m = 0;
230 break;
231 }
232
233 str_m = str[m];
234 }
235
236 wxString strVarName( str.c_str() + n + 1, m - n - 1 );
237
238 // NB: use wxGetEnv instead of wxGetenv as otherwise variables
239 // set through wxSetEnv may not be read correctly!
240 bool expanded = false;
241 wxString tmp = strVarName;
242
243 if( aProject && aProject->TextVarResolver( &tmp ) )
244 {
245 strResult += tmp;
246 expanded = true;
247 }
248 else if( wxGetEnv( strVarName, &tmp ) )
249 {
250 strResult += tmp;
251 expanded = true;
252 }
253 // Replace unmatched older variables with current locations
254 // If the user has the older location defined, that will be matched
255 // first above. But if they do not, this will ensure that their board still
256 // displays correctly
257 else if( strVarName.Contains( "KISYS3DMOD") || strVarName.Matches( "KICAD*_3DMODEL_DIR" ) )
258 {
259 if( getVersionedEnvVar( "KICAD*_3DMODEL_DIR", strResult ) )
260 expanded = true;
261 }
262 else if( strVarName.Matches( "KICAD*_SYMBOL_DIR" ) )
263 {
264 if( getVersionedEnvVar( "KICAD*_SYMBOL_DIR", strResult ) )
265 expanded = true;
266 }
267 else if( strVarName.Matches( "KICAD*_FOOTPRINT_DIR" ) )
268 {
269 if( getVersionedEnvVar( "KICAD*_FOOTPRINT_DIR", strResult ) )
270 expanded = true;
271 }
272 else if( strVarName.Matches( "KICAD*_3RD_PARTY" ) )
273 {
274 if( getVersionedEnvVar( "KICAD*_3RD_PARTY", strResult ) )
275 expanded = true;
276 }
277 else
278 {
279 // variable doesn't exist => don't change anything
280#ifdef __WINDOWS__
281 if ( bracket != Bracket_Windows )
282#endif
283 if ( bracket != Bracket_None )
284 strResult << str[n - 1];
285
286 strResult << str_n << strVarName;
287 }
288
289 // check the closing bracket
290 if( bracket != Bracket_None )
291 {
292 if( m == strlen || str_m != (wxChar)bracket )
293 {
294 // under MSW it's common to have '%' characters in the registry
295 // and it's annoying to have warnings about them each time, so
296 // ignore them silently if they are not used for env vars
297 //
298 // under Unix, OTOH, this warning could be useful for the user to
299 // understand why isn't the variable expanded as intended
300#ifndef __WINDOWS__
301 wxLogWarning( _( "Environment variables expansion failed: missing '%c' "
302 "at position %u in '%s'." ),
303 (char)bracket, (unsigned int) (m + 1), str.c_str() );
304#endif // __WINDOWS__
305 }
306 else
307 {
308 // skip closing bracket unless the variables wasn't expanded
309 if( !expanded )
310 strResult << (wxChar)bracket;
311
312 m++;
313 }
314 }
315
316 n = m - 1; // skip variable name
317 str_n = str[n];
318 }
319 break;
320
321 case wxT( '\\' ):
322 // backslash can be used to suppress special meaning of % and $
323 if( n < strlen - 1 && (str[n + 1] == wxT( '%' ) || str[n + 1] == wxT( '$' )) )
324 {
325 str_n = str[++n];
326 strResult += str_n;
327
328 break;
329 }
331
332 default:
333 strResult += str_n;
334 }
335 }
336
337 std::set<wxString> loop_check;
338 auto first_pos = strResult.find_first_of( wxS( "{(%" ) );
339 auto last_pos = strResult.find_last_of( wxS( "})%" ) );
340
341 if( first_pos != strResult.npos && last_pos != strResult.npos && first_pos != last_pos )
342 strResult = KIwxExpandEnvVars( strResult, aProject, aSet ? aSet : &loop_check );
343
344 return strResult;
345}
346
347
348const wxString ExpandEnvVarSubstitutions( const wxString& aString, const PROJECT* aProject )
349{
350 // wxGetenv( wchar_t* ) is not re-entrant on linux.
351 // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
352 static std::mutex getenv_mutex;
353
354 std::lock_guard<std::mutex> lock( getenv_mutex );
355
356 // We reserve the right to do this another way, by providing our own member function.
357 return KIwxExpandEnvVars( aString, aProject );
358}
359
360
361const wxString ResolveUriByEnvVars( const wxString& aUri, const PROJECT* aProject )
362{
363 wxString uri = ExpandTextVars( aUri, aProject );
364
365 return ExpandEnvVarSubstitutions( uri, aProject );
366}
367
368
369bool EnsureFileDirectoryExists( wxFileName* aTargetFullFileName,
370 const wxString& aBaseFilename,
371 REPORTER* aReporter )
372{
373 wxString msg;
374 wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
375
376 // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
377 // already an absolute path) absolute:
378 if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
379 {
380 if( aReporter )
381 {
382 msg.Printf( _( "Cannot make path '%s' absolute with respect to '%s'." ),
383 aTargetFullFileName->GetPath(),
384 baseFilePath );
385 aReporter->Report( msg, RPT_SEVERITY_ERROR );
386 }
387
388 return false;
389 }
390
391 // Ensure the path of aTargetFullFileName exists, and create it if needed:
392 wxString outputPath( aTargetFullFileName->GetPath() );
393
394 if( !wxFileName::DirExists( outputPath ) )
395 {
396 // Make every directory provided when the provided path doesn't exist
397 if( wxFileName::Mkdir( outputPath, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
398 {
399 if( aReporter )
400 {
401 msg.Printf( _( "Output directory '%s' created." ), outputPath );
402 aReporter->Report( msg, RPT_SEVERITY_INFO );
403 return true;
404 }
405 }
406 else
407 {
408 if( aReporter )
409 {
410 msg.Printf( _( "Cannot create output directory '%s'." ), outputPath );
411 aReporter->Report( msg, RPT_SEVERITY_ERROR );
412 }
413
414 return false;
415 }
416 }
417
418 return true;
419}
420
421
422wxString EnsureFileExtension( const wxString& aFilename, const wxString& aExtension )
423{
424 wxString newFilename( aFilename );
425
426 // It's annoying to throw up nag dialogs when the extension isn't right. Just fix it,
427 // but be careful not to destroy existing after-dot-text that isn't actually a bad
428 // extension, such as "Schematic_1.1".
429 if( newFilename.Lower().AfterLast( '.' ) != aExtension )
430 {
431 if( newFilename.Last() != '.' )
432 newFilename.Append( '.' );
433
434 newFilename.Append( aExtension );
435 }
436
437 return newFilename;
438}
439
440
455bool matchWild( const char* pat, const char* text, bool dot_special )
456{
457 if( !*text )
458 {
459 /* Match if both are empty. */
460 return !*pat;
461 }
462
463 const char *m = pat,
464 *n = text,
465 *ma = nullptr,
466 *na = nullptr;
467 int just = 0,
468 acount = 0,
469 count = 0;
470
471 if( dot_special && (*n == '.') )
472 {
473 /* Never match so that hidden Unix files
474 * are never found. */
475 return false;
476 }
477
478 for(;;)
479 {
480 if( *m == '*' )
481 {
482 ma = ++m;
483 na = n;
484 just = 1;
485 acount = count;
486 }
487 else if( *m == '?' )
488 {
489 m++;
490
491 if( !*n++ )
492 return false;
493 }
494 else
495 {
496 if( *m == '\\' )
497 {
498 m++;
499
500 /* Quoting "nothing" is a bad thing */
501 if( !*m )
502 return false;
503 }
504
505 if( !*m )
506 {
507 /*
508 * If we are out of both strings or we just
509 * saw a wildcard, then we can say we have a
510 * match
511 */
512 if( !*n )
513 return true;
514
515 if( just )
516 return true;
517
518 just = 0;
519 goto not_matched;
520 }
521
522 /*
523 * We could check for *n == NULL at this point, but
524 * since it's more common to have a character there,
525 * check to see if they match first (m and n) and
526 * then if they don't match, THEN we can check for
527 * the NULL of n
528 */
529 just = 0;
530
531 if( *m == *n )
532 {
533 m++;
534 count++;
535 n++;
536 }
537 else
538 {
539 not_matched:
540
541 /*
542 * If there are no more characters in the
543 * string, but we still need to find another
544 * character (*m != NULL), then it will be
545 * impossible to match it
546 */
547 if( !*n )
548 return false;
549
550 if( ma )
551 {
552 m = ma;
553 n = ++na;
554 count = acount;
555 }
556 else
557 return false;
558 }
559 }
560 }
561}
562
563
568#if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
569
570// Convert between wxDateTime and FILETIME which is a 64-bit value representing
571// the number of 100-nanosecond intervals since January 1, 1601 UTC.
572//
573// This is the offset between FILETIME epoch and the Unix/wxDateTime Epoch.
574static wxInt64 EPOCH_OFFSET_IN_MSEC = wxLL(11644473600000);
575
576
577static void ConvertFileTimeToWx( wxDateTime* dt, const FILETIME& ft )
578{
579 wxLongLong t( ft.dwHighDateTime, ft.dwLowDateTime );
580 t /= 10000; // Convert hundreds of nanoseconds to milliseconds.
581 t -= EPOCH_OFFSET_IN_MSEC;
582
583 *dt = wxDateTime( t );
584}
585
586#endif // wxUSE_DATETIME && __WIN32__
587
588
597long long TimestampDir( const wxString& aDirPath, const wxString& aFilespec )
598{
599 long long timestamp = 0;
600
601#if defined( __WIN32__ )
602 // Win32 version.
603 // Save time by not searching for each path twice: once in wxDir.GetNext() and once in
604 // wxFileName.GetModificationTime(). Also cuts out wxWidgets' string-matching and case
605 // conversion by staying on the MSW side of things.
606 std::wstring filespec( aDirPath.t_str() );
607 filespec += '\\';
608 filespec += aFilespec.t_str();
609
610 WIN32_FIND_DATA findData;
611 wxDateTime lastModDate;
612
613 HANDLE fileHandle = ::FindFirstFile( filespec.data(), &findData );
614
615 if( fileHandle != INVALID_HANDLE_VALUE )
616 {
617 do
618 {
619 ConvertFileTimeToWx( &lastModDate, findData.ftLastWriteTime );
620 timestamp += lastModDate.GetValue().GetValue();
621
622 // Get the file size (partial) as well to check for sneaky changes.
623 timestamp += findData.nFileSizeLow;
624 }
625 while ( FindNextFile( fileHandle, &findData ) != 0 );
626 }
627
628 FindClose( fileHandle );
629#else
630 // POSIX version.
631 // Save time by not converting between encodings -- do everything on the file-system side.
632 std::string filespec( aFilespec.fn_str() );
633 std::string dir_path( aDirPath.fn_str() );
634
635 DIR* dir = opendir( dir_path.c_str() );
636
637 if( dir )
638 {
639 for( dirent* dir_entry = readdir( dir ); dir_entry; dir_entry = readdir( dir ) )
640 {
641 if( !matchWild( filespec.c_str(), dir_entry->d_name, true ) )
642 continue;
643
644 std::string entry_path = dir_path + '/' + dir_entry->d_name;
645 struct stat entry_stat;
646
647 if( wxCRT_Lstat( entry_path.c_str(), &entry_stat ) == 0 )
648 {
649 // Timestamp the source file, not the symlink
650 if( S_ISLNK( entry_stat.st_mode ) ) // wxFILE_EXISTS_SYMLINK
651 {
652 char buffer[ PATH_MAX + 1 ];
653 ssize_t pathLen = readlink( entry_path.c_str(), buffer, PATH_MAX );
654
655 if( pathLen > 0 )
656 {
657 struct stat linked_stat;
658 buffer[ pathLen ] = '\0';
659 entry_path = dir_path + buffer;
660
661 if( wxCRT_Lstat( entry_path.c_str(), &linked_stat ) == 0 )
662 {
663 entry_stat = linked_stat;
664 }
665 else
666 {
667 // if we couldn't lstat the linked file we'll have to just use
668 // the symbolic link info
669 }
670 }
671 }
672
673 if( S_ISREG( entry_stat.st_mode ) ) // wxFileExists()
674 {
675 timestamp += entry_stat.st_mtime * 1000;
676
677 // Get the file size as well to check for sneaky changes.
678 timestamp += entry_stat.st_size;
679 }
680 }
681 else
682 {
683 // if we couldn't lstat the file itself all we can do is use the name
684 timestamp += (signed) std::hash<std::string>{}( std::string( dir_entry->d_name ) );
685 }
686 }
687
688 closedir( dir );
689 }
690#endif
691
692 return timestamp;
693}
694
695
697{
699 return false;
700
701 wxMessageDialog dialog( nullptr, _( "This operating system is not supported "
702 "by KiCad and its dependencies." ),
703 _( "Unsupported Operating System" ),
704 wxOK | wxICON_EXCLAMATION );
705
706 dialog.SetExtendedMessage( _( "Any issues with KiCad on this system cannot "
707 "be reported to the official bugtracker." ) );
708 dialog.ShowModal();
709
710 return true;
711}
Container for project specific data.
Definition: project.h:64
virtual bool TextVarResolver(wxString *aToken) const
Definition: project.cpp:72
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:72
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:348
const wxString ResolveUriByEnvVars(const wxString &aUri, const PROJECT *aProject)
Replace any environment and/or text variables in URIs.
Definition: common.cpp:361
wxString EnsureFileExtension(const wxString &aFilename, const wxString &aExtension)
It's annoying to throw up nag dialogs when the extension isn't right.
Definition: common.cpp:422
bool WarnUserIfOperatingSystemUnsupported()
Checks if the operating system is explicitly unsupported and displays a disclaimer message box.
Definition: common.cpp:696
bool matchWild(const char *pat, const char *text, bool dot_special)
Performance enhancements to file and directory operations.
Definition: common.cpp:455
bool EnsureFileDirectoryExists(wxFileName *aTargetFullFileName, const wxString &aBaseFilename, REPORTER *aReporter)
Make aTargetFullFileName absolute and create the path of this file if it doesn't yet exist.
Definition: common.cpp:369
wxString KIwxExpandEnvVars(const wxString &str, const PROJECT *aProject, std::set< wxString > *aSet=nullptr)
Definition: common.cpp:142
Bracket
Definition: common.cpp:48
@ Bracket_Max
Definition: common.cpp:55
@ Bracket_None
Definition: common.cpp:49
@ Bracket_Normal
Definition: common.cpp:50
@ Bracket_Curly
Definition: common.cpp:51
bool IsTextVar(const wxString &aSource)
Returns true if the string is a text var, e.g starts with ${.
Definition: common.cpp:133
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject)
Definition: common.cpp:59
wxString GetTextVars(const wxString &aSource)
Returns any variables unexpanded, e.g.
Definition: common.cpp:121
long long TimestampDir(const wxString &aDirPath, const wxString &aFilespec)
A copy of ConvertFileTimeToWx() because wxWidgets left it as a static function private to src/common/...
Definition: common.cpp:597
The common library.
#define _(s)
Base window classes and related definitions.
Functions related to environment variables, including help functions.
This file contains miscellaneous commonly used macros and functions.
#define KI_FALLTHROUGH
The KI_FALLTHROUGH macro is to be used when switch statement cases should purposely fallthrough from ...
Definition: macros.h:83
KICOMMON_API const ENV_VAR_LIST & GetPredefinedEnvVars()
Get the list of pre-defined environment variables.
Definition: env_vars.cpp:68
bool IsOperatingSystemUnsupported()
Checks if the Operating System is explicitly unsupported and we want to prevent users from sending bu...
Definition: unix/app.cpp:58
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO