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