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