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, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <eda_base_frame.h>
23#include <kiplatform/app.h>
24#include <project.h>
25#include <common.h>
26#include <confirm.h>
27#include <env_vars.h>
28#include <advanced_config.h>
29#include <reporter.h>
30#include <macros.h>
31#include <string_utils.h>
33#include <text_var_dependency.h>
34#include <mutex>
35#include <wx/config.h>
36#include <wx/log.h>
37#include <wx/msgdlg.h>
38#include <wx/stdpaths.h>
39#include <wx/url.h>
40#include <wx/utils.h>
41#include <wx/regex.h>
42
43#ifdef _WIN32
44#include <windows.h>
45#endif
46
47
49{
53#ifdef __WINDOWS__
54 Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
55#endif
57};
58
59wxString ExpandTextVars( const wxString& aSource, const PROJECT* aProject, int aFlags )
60{
61 std::function<bool( wxString* )> projectResolver = [&]( wxString* token ) -> bool
62 {
63 return aProject->TextVarResolver( token );
64 };
65
66 return ExpandTextVars( aSource, &projectResolver, aFlags );
67}
68
69
70wxString NormalizeFilePathForTextVars( const wxString& aPath )
71{
72 wxString path = aPath;
73
74 // ExpandTextVars treats \${ and \@{ as escape sequences, which misinterprets Windows paths
75 // like "subdir\${REVISION}.csv" where the backslash is a path separator, not an escape. Only
76 // the ambiguous separator is rewritten so legitimate backslashes elsewhere are preserved.
77 path.Replace( wxT( "\\${" ), wxT( "/${" ) );
78 path.Replace( wxT( "\\@{" ), wxT( "/@{" ) );
79
80 return path;
81}
82
83
84wxString ExpandTextVars( const wxString& aSource, const std::function<bool( wxString* )>* aResolver, int aFlags,
85 int aDepth )
86{
87 wxString newbuf;
88 size_t sourceLen = aSource.length();
89
90 newbuf.Alloc( sourceLen ); // best guess (improves performance)
91
92 // Get the maximum recursion depth from advanced config
94
95 for( size_t i = 0; i < sourceLen; ++i )
96 {
97 // Skip over existing escape markers without processing their contents
98 // This prevents expanding ${} or @{} that are inside escaped expressions
99 if( i + 14 <= sourceLen && aSource.Mid( i, 14 ) == wxT( "<<<ESC_DOLLAR:" ) )
100 {
101 // Copy the entire escape marker including contents until matching closing }
102 newbuf.append( wxT( "<<<ESC_DOLLAR:" ) );
103 i += 14;
104
105 // Count braces to find the matching closing }
106 int braceCount = 1;
107 while( i < sourceLen && braceCount > 0 )
108 {
109 if( aSource[i] == '{' )
110 braceCount++;
111 else if( aSource[i] == '}' )
112 braceCount--;
113
114 newbuf.append( aSource[i] );
115 i++;
116 }
117 i--; // Back up one since the for loop will increment
118 continue;
119 }
120 else if( i + 10 <= sourceLen && aSource.Mid( i, 10 ) == wxT( "<<<ESC_AT:" ) )
121 {
122 // Copy the entire escape marker including contents until matching closing }
123 newbuf.append( wxT( "<<<ESC_AT:" ) );
124 i += 10;
125
126 // Count braces to find the matching closing }
127 int braceCount = 1;
128 while( i < sourceLen && braceCount > 0 )
129 {
130 if( aSource[i] == '{' )
131 braceCount++;
132 else if( aSource[i] == '}' )
133 braceCount--;
134
135 newbuf.append( aSource[i] );
136 i++;
137 }
138 i--; // Back up one since the for loop will increment
139 continue;
140 }
141
142 // Handle escaped variable references: \${...} or \@{...}
143 // Replace with escape markers that won't be expanded by multi-pass loops
144 // The markers will be converted back to ${...} or @{...} only at the final display stage
145 if( aSource[i] == '\\' && i + 1 < sourceLen )
146 {
147 if( ( aSource[i + 1] == '$' || aSource[i + 1] == '@' ) && i + 2 < sourceLen && aSource[i + 2] == '{' )
148 {
149 // Replace \${ with <<<ESC_DOLLAR: and \@{ with <<<ESC_AT:
150 // Using unique delimiters without braces to avoid confusing the expression evaluator
151 if( aSource[i + 1] == '$' )
152 newbuf.append( wxT( "<<<ESC_DOLLAR:" ) );
153 else
154 newbuf.append( wxT( "<<<ESC_AT:" ) );
155 i += 2;
156
157 // Copy everything until the matching closing brace, including the brace
158 int braceDepth = 1;
159 for( i = i + 1; i < sourceLen && braceDepth > 0; ++i )
160 {
161 if( aSource[i] == '{' )
162 braceDepth++;
163 else if( aSource[i] == '}' )
164 braceDepth--;
165
166 newbuf.append( aSource[i] );
167 }
168 i--; // Adjust because loop will increment
169 continue;
170 }
171 }
172
173 if( ( aSource[i] == '$' || aSource[i] == '@' ) && i + 1 < sourceLen && aSource[i + 1] == '{' )
174 {
175 bool isMathExpr = ( aSource[i] == '@' );
176 wxString token;
177 int braceDepth = 1; // Track brace depth for nested expressions like @{${VAR}}
178
179 for( i = i + 2; i < sourceLen; ++i )
180 {
181 // Skip over escape markers - don't count their braces
182 // This prevents <<<ESC_DOLLAR:X} from interfering with outer brace counting
183 if( i + 14 <= sourceLen && aSource.Mid( i, 14 ) == wxT( "<<<ESC_DOLLAR:" ) )
184 {
185 token.append( wxT( "<<<ESC_DOLLAR:" ) );
186 i += 14;
187
188 // Copy contents until matching closing brace (tracking nested braces)
189 int markerBraceCount = 1;
190
191 while( i < sourceLen && markerBraceCount > 0 )
192 {
193 if( aSource[i] == '{' )
194 markerBraceCount++;
195 else if( aSource[i] == '}' )
196 markerBraceCount--;
197
198 token.append( aSource[i] );
199 i++;
200 }
201
202 i--; // Adjust for outer loop increment
203 continue;
204 }
205 else if( i + 10 <= sourceLen && aSource.Mid( i, 10 ) == wxT( "<<<ESC_AT:" ) )
206 {
207 token.append( wxT( "<<<ESC_AT:" ) );
208 i += 10;
209
210 // Copy contents until matching closing brace (tracking nested braces)
211 int markerBraceCount = 1;
212
213 while( i < sourceLen && markerBraceCount > 0 )
214 {
215 if( aSource[i] == '{' )
216 markerBraceCount++;
217 else if( aSource[i] == '}' )
218 markerBraceCount--;
219
220 token.append( aSource[i] );
221 i++;
222 }
223
224 i--; // Adjust for outer loop increment
225 continue;
226 }
227
228 if( aSource[i] == '{' )
229 {
230 braceDepth++;
231 token.append( aSource[i] );
232 }
233 else if( aSource[i] == '}' )
234 {
235 braceDepth--;
236
237 if( braceDepth == 0 )
238 break; // Found the matching closing brace
239 else
240 token.append( aSource[i] );
241 }
242 else
243 {
244 token.append( aSource[i] );
245 }
246 }
247
248 if( token.IsEmpty() )
249 continue;
250
251 // For math expressions @{...}, recursively expand any nested ${...} variables
252 // but DON'T evaluate the math - leave that for EvaluateText() called by the user
253 if( isMathExpr )
254 {
255 if( ( token.Contains( wxT( "${" ) ) || token.Contains( wxT( "@{" ) ) ) && aDepth < maxDepth )
256 {
257 token = ExpandTextVars( token, aResolver, aFlags, aDepth + 1 );
258 }
259
260 // Return the expression with variables expanded but NOT evaluated
261 // The caller will use EvaluateText() to handle the math evaluation
262 newbuf.append( wxT( "@{" ) + token + wxT( "}" ) );
263 }
264 else // Variable reference ${...}
265 {
266 // Recursively expand nested variables BEFORE passing to resolver
267 // This ensures innermost variables are expanded first (standard evaluation order)
268 if( ( token.Contains( wxT( "${" ) ) || token.Contains( wxT( "@{" ) ) ) && aDepth < maxDepth )
269 {
270 token = ExpandTextVars( token, aResolver, aFlags, aDepth + 1 );
271
272 // Also evaluate math expressions after expanding variables
273 if( token.Contains( wxT( "@{" ) ) )
274 {
275 // Must not be static. ExpandTextVars runs on parallel workers
276 // (e.g. CONNECTION_GRAPH) and a shared evaluator races on its
277 // internal error collector.
278 EXPRESSION_EVALUATOR evaluator;
279 token = evaluator.Evaluate( token );
280 }
281 }
282
283 if( ( aFlags & FOR_ERC_DRC ) == 0
284 && ( token.StartsWith( wxS( "ERC_WARNING" ) ) || token.StartsWith( wxS( "ERC_ERROR" ) )
285 || token.StartsWith( wxS( "DRC_WARNING" ) ) || token.StartsWith( wxS( "DRC_ERROR" ) ) ) )
286 {
287 // Only show user-defined warnings/errors during ERC/DRC
288 }
289 else if( aResolver && ( *aResolver )( &token ) )
290 {
291 newbuf.append( token );
292 }
293 else
294 {
295 // Token not resolved: leave the reference unchanged
296 newbuf.append( "${" + token + "}" );
297 }
298 }
299 }
300 else
301 {
302 newbuf.append( aSource[i] );
303 }
304 }
305
306 return newbuf;
307}
308
309
310wxString ResolveTextVars( const wxString& aSource, const std::function<bool( wxString* )>* aResolver, int& aDepth )
311{
312 // Multi-pass resolution to handle nested variables like ${J601:UNIT(${ROW})}
313 // and math expressions like @{${ROW}-1}
314 wxString text = aSource;
316
317 // Must not be static. ResolveTextVars runs on parallel workers (e.g.
318 // CONNECTION_GRAPH) and a shared evaluator races on its internal error
319 // collector.
320 EXPRESSION_EVALUATOR evaluator;
321
322 while( ( text.Contains( wxT( "${" ) ) || text.Contains( wxT( "@{" ) ) ) && ++aDepth <= maxDepth )
323 {
324 // Always expand when ${} or @{} present to handle escape sequences (\${} and \@{})
325 // ExpandTextVars converts escapes to markers and expands ${} variables
326 // Don't expand if the only remaining $ or @ are in escape markers like <<<ESC_DOLLAR: or <<<ESC_AT:
327 if( text.Contains( wxT( "${" ) ) || text.Contains( wxT( "@{" ) ) )
328 text = ExpandTextVars( text, aResolver );
329
330 // Only evaluate if there are @{} expressions present (not escape markers)
331 // Don't evaluate if the only remaining @ are in escape markers like <<<ESC_AT:
332 if( text.Contains( wxT( "@{" ) ) )
333 text = evaluator.Evaluate( text ); // Evaluate math expressions
334 }
335
336 return text;
337}
338
339
340namespace
341{
342// Scan @p aText beginning at @p aStart (pointing just past an opening `${` or
343// `@{`), collect every nested and sibling reference, and advance @p aStart past
344// the matching closing brace. Returns the raw token body for the outer
345// reference so the caller can classify it. Escape markers (\${…} and \@{…})
346// are skipped. Brace nesting mirrors the ExpandTextVars state machine so
347// tokens like `${FOO:BAR(${BAZ})}` are captured as a single outer token with
348// BAZ picked up as a nested sibling.
349wxString walkRef( const wxString& aText, std::size_t& aPos, std::vector<TEXT_VAR_REF_KEY>& aOut );
350
351void collectRefsFrom( const wxString& aText, std::size_t aStart, std::size_t aEnd,
352 std::vector<TEXT_VAR_REF_KEY>& aOut )
353{
354 for( std::size_t i = aStart; i < aEnd; ++i )
355 {
356 const wxUniChar c = aText[i];
357
358 // Escape sequences: skip the whole escaped expression; its contents
359 // are a user literal, not a dependency source.
360 if( c == wxT( '\\' ) && i + 2 < aEnd && ( aText[i + 1] == wxT( '$' ) || aText[i + 1] == wxT( '@' ) )
361 && aText[i + 2] == wxT( '{' ) )
362 {
363 std::size_t j = i + 3;
364 int depth = 1;
365
366 while( j < aEnd && depth > 0 )
367 {
368 if( aText[j] == wxT( '{' ) )
369 depth++;
370 else if( aText[j] == wxT( '}' ) )
371 depth--;
372
373 ++j;
374 }
375
376 i = j - 1;
377 continue;
378 }
379
380 if( ( c == wxT( '$' ) || c == wxT( '@' ) ) && i + 1 < aEnd && aText[i + 1] == wxT( '{' ) )
381 {
382 std::size_t pos = i + 2;
383 const wxString token = walkRef( aText, pos, aOut );
384
385 // Math expressions (`@{...}`) contribute their nested variables as
386 // dependency edges but do not produce a named edge themselves — the
387 // expression text is not a resolvable source name.
388 if( c == wxT( '$' ) && !token.IsEmpty() )
389 aOut.push_back( TEXT_VAR_REF_KEY::FromToken( token ) );
390
391 // Clamp to aEnd - 1 so the outer for-loop increment doesn't go past
392 // the end on a malformed token.
393 i = ( pos > 0 ? pos - 1 : pos );
394 }
395 }
396}
397
398
399wxString walkRef( const wxString& aText, std::size_t& aPos, std::vector<TEXT_VAR_REF_KEY>& aOut )
400{
401 const std::size_t len = aText.length();
402 const std::size_t start = aPos;
403 int depth = 1;
404
405 while( aPos < len )
406 {
407 const wxUniChar c = aText[aPos];
408
409 if( c == wxT( '{' ) )
410 {
411 depth++;
412 }
413 else if( c == wxT( '}' ) )
414 {
415 depth--;
416
417 if( depth == 0 )
418 {
419 wxString body = aText.Mid( start, aPos - start );
420 aPos++; // consume the matching close-brace
421
422 // Recurse into the body so nested references are captured
423 // regardless of whether the outer resolves. ExpandTextVars'
424 // resolver path would suppress this for outer tokens beginning
425 // with ERC_WARNING / DRC_WARNING; a dependency tracker must
426 // not care about that (codex finding 3).
427 collectRefsFrom( body, 0, body.length(), aOut );
428 return body;
429 }
430 }
431
432 aPos++;
433 }
434
435 // Malformed token (ran off the end without a matching close-brace).
436 // Recurse into the partial body so nested inner references are still
437 // captured — `${FOO${BAR}` at EOF must still produce a BAR dependency.
438 wxString partial = aText.Mid( start, aPos - start );
439 collectRefsFrom( partial, 0, partial.length(), aOut );
440 return partial;
441}
442}
443
444
445std::vector<TEXT_VAR_REF_KEY> ExtractTextVarReferences( const wxString& aSource )
446{
447 std::vector<TEXT_VAR_REF_KEY> refs;
448
449 // Fast path: no reference syntax at all.
450 if( !aSource.Contains( wxT( "${" ) ) && !aSource.Contains( wxT( "@{" ) ) )
451 return refs;
452
453 collectRefsFrom( aSource, 0, aSource.length(), refs );
454 return refs;
455}
456
457
458wxString GetGeneratedFieldDisplayName( const wxString& aSource )
459{
460 std::function<bool( wxString* )> tokenExtractor = [&]( wxString* token ) -> bool
461 {
462 *token = *token; // token value is the token name
463 return true;
464 };
465
466 return ExpandTextVars( aSource, &tokenExtractor );
467}
468
469
470bool IsGeneratedField( const wxString& aSource )
471{
472 // Per-thread regex. Callers include parallel ERC/connection-graph workers.
473 thread_local wxRegEx expr( wxS( "^\\$\\{\\w*\\}$" ) );
474 return expr.Matches( aSource );
475}
476
477
478wxString DescribeRef( const wxString& aRef )
479{
480 if( aRef.IsEmpty() )
481 return wxT( "<i>" ) + _( "unannotated footprint" ) + wxT( " </i>" );
482 else
483 return EscapeHTML( aRef );
484}
485
486
487//
488// Stolen from wxExpandEnvVars and then heavily optimized
489//
490wxString KIwxExpandEnvVars( const wxString& str, const PROJECT* aProject, std::set<wxString>* aSet = nullptr )
491{
492 // If the same string is inserted twice, we have a loop
493 if( aSet )
494 {
495 if( auto [_, result] = aSet->insert( str ); !result )
496 return str;
497 }
498
499 size_t strlen = str.length();
500
501 wxString strResult;
502 strResult.Alloc( strlen ); // best guess (improves performance)
503
504 auto getVersionedEnvVar = []( const wxString& aMatch, wxString& aResult ) -> bool
505 {
506 for( const wxString& var : ENV_VAR::GetPredefinedEnvVars() )
507 {
508 if( var.Matches( aMatch ) )
509 {
510 const auto value = ENV_VAR::GetEnvVar<wxString>( var );
511
512 if( !value )
513 continue;
514
515 aResult += *value;
516 return true;
517 }
518 }
519
520 return false;
521 };
522
523 for( size_t n = 0; n < strlen; n++ )
524 {
525 wxUniChar str_n = str[n];
526
527 switch( str_n.GetValue() )
528 {
529#ifdef __WINDOWS__
530 case wxT( '%' ):
531#endif // __WINDOWS__
532 case wxT( '$' ):
533 {
534 Bracket bracket;
535#ifdef __WINDOWS__
536 if( str_n == wxT( '%' ) )
537 {
538 bracket = Bracket_Windows;
539 }
540 else
541#endif // __WINDOWS__
542 if( n == strlen - 1 )
543 {
544 bracket = Bracket_None;
545 }
546 else
547 {
548 switch( str[n + 1].GetValue() )
549 {
550 case wxT( '(' ):
551 bracket = Bracket_Normal;
552 str_n = str[++n]; // skip the bracket
553 break;
554
555 case wxT( '{' ):
556 bracket = Bracket_Curly;
557 str_n = str[++n]; // skip the bracket
558 break;
559
560 default: bracket = Bracket_None;
561 }
562 }
563
564 size_t m = n + 1;
565
566 if( m >= strlen )
567 break;
568
569 wxUniChar str_m = str[m];
570
571 while( wxIsalnum( str_m ) || str_m == wxT( '_' ) || str_m == wxT( ':' ) )
572 {
573 if( ++m == strlen )
574 {
575 str_m = 0;
576 break;
577 }
578
579 str_m = str[m];
580 }
581
582 wxString strVarName( str.c_str() + n + 1, m - n - 1 );
583
584 // NB: use wxGetEnv instead of wxGetenv as otherwise variables
585 // set through wxSetEnv may not be read correctly!
586 bool expanded = false;
587 wxString tmp = strVarName;
588
589 if( aProject && aProject->TextVarResolver( &tmp ) )
590 {
591 strResult += tmp;
592 expanded = true;
593 }
594 else if( wxGetEnv( strVarName, &tmp ) )
595 {
596 strResult += tmp;
597 expanded = true;
598 }
599 // Replace unmatched older variables with current locations
600 // If the user has the older location defined, that will be matched
601 // first above. But if they do not, this will ensure that their board still
602 // displays correctly
603 else if( strVarName.Contains( "KISYS3DMOD" )
604 || ENV_VAR::IsVersionedEnvVar( strVarName, "3DMODEL_DIR" ) )
605 {
606 if( getVersionedEnvVar( "KICAD*_3DMODEL_DIR", strResult ) )
607 expanded = true;
608 }
609 else if( strVarName == "KICAD_SYMBOL_DIR"
610 || ENV_VAR::IsVersionedEnvVar( strVarName, "SYMBOL_DIR" ) )
611 {
612 if( getVersionedEnvVar( "KICAD*_SYMBOL_DIR", strResult ) )
613 expanded = true;
614 }
615 else if( ENV_VAR::IsVersionedEnvVar( strVarName, "FOOTPRINT_DIR" ) )
616 {
617 if( getVersionedEnvVar( "KICAD*_FOOTPRINT_DIR", strResult ) )
618 expanded = true;
619 }
620 else if( ENV_VAR::IsVersionedEnvVar( strVarName, "3RD_PARTY" ) )
621 {
622 if( getVersionedEnvVar( "KICAD*_3RD_PARTY", strResult ) )
623 expanded = true;
624 }
625 else
626 {
627 // variable doesn't exist => don't change anything
628#ifdef __WINDOWS__
629 if( bracket != Bracket_Windows )
630#endif
631 if( bracket != Bracket_None )
632 strResult << str[n - 1];
633
634 strResult << str_n << strVarName;
635 }
636
637 // When a versioned-wildcard branch matched but no env var was found, emit
638 // the original ${VARNAME} text so the closing-bracket handler can append the
639 // closing bracket. Without this, the handler emits only '}', producing a
640 // garbage path like "}/Device.kicad_sym" instead of the full unexpanded var.
641 if( !expanded && bracket != Bracket_None )
642 {
643 auto isVersionedWildcard =
644 strVarName.Contains( wxT( "KISYS3DMOD" ) )
645 || strVarName == wxT( "KICAD_SYMBOL_DIR" )
646 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "3DMODEL_DIR" ) )
647 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "SYMBOL_DIR" ) )
648 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "FOOTPRINT_DIR" ) )
649 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "3RD_PARTY" ) );
650
651 if( isVersionedWildcard )
652 {
653#ifdef __WINDOWS__
654 if( bracket != Bracket_Windows )
655#endif
656 strResult << str[n - 1];
657
658 strResult << str_n << strVarName;
659 }
660 }
661
662 // check the closing bracket
663 if( bracket != Bracket_None )
664 {
665 if( m == strlen || str_m != (wxChar) bracket )
666 {
667 // under MSW it's common to have '%' characters in the registry
668 // and it's annoying to have warnings about them each time, so
669 // ignore them silently if they are not used for env vars
670 //
671 // under Unix, OTOH, this warning could be useful for the user to
672 // understand why isn't the variable expanded as intended
673#ifndef __WINDOWS__
674 wxLogWarning( _( "Environment variables expansion failed: missing '%c' "
675 "at position %u in '%s'." ),
676 (char) bracket, (unsigned int) ( m + 1 ), str.c_str() );
677#endif // __WINDOWS__
678 }
679 else
680 {
681 // skip closing bracket unless the variables wasn't expanded
682 if( !expanded )
683 strResult << (wxChar) bracket;
684
685 m++;
686 }
687 }
688
689 n = m - 1; // skip variable name
690 str_n = str[n];
691 }
692 break;
693
694 case wxT( '\\' ):
695 // backslash can be used to suppress special meaning of % and $
696 if( n < strlen - 1 && ( str[n + 1] == wxT( '%' ) || str[n + 1] == wxT( '$' ) ) )
697 {
698 str_n = str[++n];
699 strResult += str_n;
700
701 break;
702 }
703
705
706 default: strResult += str_n;
707 }
708 }
709
710 std::set<wxString> loop_check;
711 auto first_pos = strResult.find_first_of( wxS( "{(%" ) );
712 auto last_pos = strResult.find_last_of( wxS( "})%" ) );
713
714 if( first_pos != strResult.npos && last_pos != strResult.npos && first_pos != last_pos )
715 strResult = KIwxExpandEnvVars( strResult, aProject, aSet ? aSet : &loop_check );
716
717 return strResult;
718}
719
720
721const wxString ExpandEnvVarSubstitutions( const wxString& aString, const PROJECT* aProject )
722{
723 // wxGetenv( wchar_t* ) is not re-entrant on linux.
724 // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
725 static std::mutex getenv_mutex;
726
727 std::lock_guard<std::mutex> lock( getenv_mutex );
728
729 // We reserve the right to do this another way, by providing our own member function.
730 return KIwxExpandEnvVars( aString, aProject );
731}
732
733
734const wxString ResolveUriByEnvVars( const wxString& aUri, const PROJECT* aProject )
735{
736 wxString uri = ExpandTextVars( aUri, aProject );
737
738 return ExpandEnvVarSubstitutions( uri, aProject );
739}
740
741
742bool EnsureFileDirectoryExists( wxFileName* aTargetFullFileName, const wxString& aBaseFilename, REPORTER* aReporter )
743{
744 wxString msg;
745 wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
746
747 // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
748 // already an absolute path) absolute:
749 if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
750 {
751 if( aReporter )
752 {
753 msg.Printf( _( "Cannot make path '%s' absolute with respect to '%s'." ), aTargetFullFileName->GetPath(),
754 baseFilePath );
755 aReporter->Report( msg, RPT_SEVERITY_ERROR );
756 }
757
758 return false;
759 }
760
761 // Ensure the path of aTargetFullFileName exists, and create it if needed:
762 wxString outputPath( aTargetFullFileName->GetPath() );
763
764 if( !wxFileName::DirExists( outputPath ) )
765 {
766 // Make every directory provided when the provided path doesn't exist
767 if( wxFileName::Mkdir( outputPath, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
768 {
769 if( aReporter )
770 {
771 msg.Printf( _( "Output directory '%s' created." ), outputPath );
772 aReporter->Report( msg, RPT_SEVERITY_INFO );
773 return true;
774 }
775 }
776 else
777 {
778 if( aReporter )
779 {
780 msg.Printf( _( "Cannot create output directory '%s'." ), outputPath );
781 aReporter->Report( msg, RPT_SEVERITY_ERROR );
782 }
783
784 return false;
785 }
786 }
787
788 return true;
789}
790
791
792wxString EnsureFileExtension( const wxString& aFilename, const wxString& aExtension )
793{
794 wxString newFilename( aFilename );
795
796 // It's annoying to throw up nag dialogs when the extension isn't right. Just fix it,
797 // but be careful not to destroy existing after-dot-text that isn't actually a bad
798 // extension, such as "Schematic_1.1".
799 if( newFilename.Lower().AfterLast( '.' ) != aExtension )
800 {
801 if( !newFilename.EndsWith( '.' ) )
802 newFilename.Append( '.' );
803
804 newFilename.Append( aExtension );
805 }
806
807 return newFilename;
808}
809
810
811wxString JoinExtensions( const std::vector<std::string>& aExts )
812{
813 wxString joined;
814
815 for( const std::string& ext : aExts )
816 {
817 if( !joined.empty() )
818 joined << wxS( ", " );
819
820 joined << wxS( "*." ) << ext;
821 }
822
823 return joined;
824}
825
826
834
841bool matchWild( const char* pat, const char* text, bool dot_special )
842{
843 if( !*text )
844 {
845 /* Match if both are empty. */
846 return !*pat;
847 }
848
849 const char *m = pat, *n = text, *ma = nullptr, *na = nullptr;
850 int just = 0, acount = 0, count = 0;
851
852 if( dot_special && ( *n == '.' ) )
853 {
854 /* Never match so that hidden Unix files
855 * are never found. */
856 return false;
857 }
858
859 for( ;; )
860 {
861 if( *m == '*' )
862 {
863 ma = ++m;
864 na = n;
865 just = 1;
866 acount = count;
867 }
868 else if( *m == '?' )
869 {
870 m++;
871
872 if( !*n++ )
873 return false;
874 }
875 else
876 {
877 if( *m == '\\' )
878 {
879 m++;
880
881 /* Quoting "nothing" is a bad thing */
882 if( !*m )
883 return false;
884 }
885
886 if( !*m )
887 {
888 /*
889 * If we are out of both strings or we just
890 * saw a wildcard, then we can say we have a
891 * match
892 */
893 if( !*n )
894 return true;
895
896 if( just )
897 return true;
898
899 just = 0;
900 goto not_matched;
901 }
902
903 /*
904 * We could check for *n == NULL at this point, but
905 * since it's more common to have a character there,
906 * check to see if they match first (m and n) and
907 * then if they don't match, THEN we can check for
908 * the NULL of n
909 */
910 just = 0;
911
912 if( *m == *n )
913 {
914 m++;
915 count++;
916 n++;
917 }
918 else
919 {
920 not_matched:
921
922 /*
923 * If there are no more characters in the
924 * string, but we still need to find another
925 * character (*m != NULL), then it will be
926 * impossible to match it
927 */
928 if( !*n )
929 return false;
930
931 if( ma )
932 {
933 m = ma;
934 n = ++na;
935 count = acount;
936 }
937 else
938 return false;
939 }
940 }
941 }
942}
943
944
946{
948 return false;
949
950 KICAD_MESSAGE_DIALOG dialog( nullptr,
951 _( "This operating system is not supported "
952 "by KiCad and its dependencies." ),
953 _( "Unsupported Operating System" ), wxOK | wxICON_EXCLAMATION );
954
955 dialog.SetExtendedMessage( _( "Any issues with KiCad on this system cannot "
956 "be reported to the official bugtracker." ) );
957 dialog.ShowModal();
958
959 return true;
960}
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
High-level wrapper for evaluating mathematical and string expressions in wxString format.
wxString Evaluate(const wxString &aInput)
Main evaluation function - processes input string and evaluates all} expressions.
Container for project specific data.
Definition project.h:62
virtual bool TextVarResolver(wxString *aToken) const
Definition project.cpp:81
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)
Report a string with a given severity.
Definition reporter.h:100
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition common.cpp:721
wxString JoinExtensions(const std::vector< std::string > &aExts)
Join a list of file extensions for use in a file dialog.
Definition common.cpp:811
wxString GetGeneratedFieldDisplayName(const wxString &aSource)
Returns any variables unexpanded, e.g.
Definition common.cpp:458
const wxString ResolveUriByEnvVars(const wxString &aUri, const PROJECT *aProject)
Replace any environment and/or text variables in URIs.
Definition common.cpp:734
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:792
bool WarnUserIfOperatingSystemUnsupported()
Checks if the operating system is explicitly unsupported and displays a disclaimer message box.
Definition common.cpp:945
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:841
wxString NormalizeFilePathForTextVars(const wxString &aPath)
Normalize a file path so its text variables survive ExpandTextVars.
Definition common.cpp:70
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:742
wxString KIwxExpandEnvVars(const wxString &str, const PROJECT *aProject, std::set< wxString > *aSet=nullptr)
Definition common.cpp:490
Bracket
Definition common.cpp:49
@ Bracket_Max
Definition common.cpp:56
@ Bracket_None
Definition common.cpp:50
@ Bracket_Normal
Definition common.cpp:51
@ Bracket_Curly
Definition common.cpp:52
bool IsGeneratedField(const wxString &aSource)
Returns true if the string is generated, e.g contains a single text var reference.
Definition common.cpp:470
wxString DescribeRef(const wxString &aRef)
Returns a user-visible HTML string describing a footprint reference designator.
Definition common.cpp:478
wxString ResolveTextVars(const wxString &aSource, const std::function< bool(wxString *)> *aResolver, int &aDepth)
Multi-pass text variable expansion and math expression evaluation.
Definition common.cpp:310
std::vector< TEXT_VAR_REF_KEY > ExtractTextVarReferences(const wxString &aSource)
Lex-scan aSource and return every ${...} reference that appears, without resolving.
Definition common.cpp:445
The common library.
#define FOR_ERC_DRC
Expand '${var-name}' templates in text.
Definition common.h:95
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG
Definition confirm.h:48
#define _(s)
Base window classes and related definitions.
Functions related to environment variables, including help functions.
int m_ResolveTextRecursionDepth
The number of recursions to resolve text variables.
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:79
KICOMMON_API std::optional< VAL_TYPE > GetEnvVar(const wxString &aEnvVarName)
Get an environment variable as a specific type, if set correctly.
KICOMMON_API bool IsVersionedEnvVar(const wxString &aName, const wxString &aBaseName)
Test whether a name is a versioned KiCad environment variable for the given base, i....
Definition env_vars.cpp:87
KICOMMON_API const std::vector< wxString > & GetPredefinedEnvVars()
Get the list of pre-defined environment variables.
Definition env_vars.cpp:62
bool IsOperatingSystemUnsupported()
Checks if the Operating System is explicitly unsupported and we want to prevent users from sending bu...
Definition unix/app.cpp:70
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO
wxString EscapeHTML(const wxString &aString)
Return a new wxString escaped for embedding in HTML.
static TEXT_VAR_REF_KEY FromToken(const wxString &aToken)
Parse a raw token (the text between ${ and }) into a key using lexical classification only — no looku...
std::string path
wxString result
Test unit parsing edge cases and error handling.