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