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 && aContext != FOR_URI )
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 bool aAllowEscapes = true )
522{
523 // If the same string is inserted twice, we have a loop
524 if( aSet )
525 {
526 if( auto [_, result] = aSet->insert( str ); !result )
527 return str;
528 }
529
530 size_t strlen = str.length();
531
532 wxString strResult;
533 strResult.Alloc( strlen ); // best guess (improves performance)
534
535 auto readEnvironment = []( const wxString& aName, wxString* aValue ) -> bool
536 {
537 const bool found = wxGetEnv( aName, aValue );
538
540 environment->RecordEnvironmentVariable( aName, found ? std::optional<wxString>( *aValue ) : std::nullopt );
541
542 return found;
543 };
544
545 auto getVersionedEnvVar =
546 [&]( const wxString& aMatch, wxString& aResult ) -> bool
547 {
548 for( const wxString& var : ENV_VAR::GetPredefinedEnvVars() )
549 {
550 if( var.Matches( aMatch ) )
551 {
552 wxString value;
553
554 if( !readEnvironment( var, &value ) )
555 continue;
556
557 aResult += value;
558 return true;
559 }
560 }
561
562 return false;
563 };
564
565 for( size_t n = 0; n < strlen; n++ )
566 {
567 wxUniChar str_n = str[n];
568
569 switch( str_n.GetValue() )
570 {
571#ifdef __WINDOWS__
572 case wxT( '%' ):
573#endif // __WINDOWS__
574 case wxT( '$' ):
575 {
576 char controlChar = str_n.GetValue();
577 Bracket bracket;
578
579#ifdef __WINDOWS__
580 if( str_n == wxT( '%' ) )
581 {
582 bracket = Bracket_Windows;
583 }
584 else
585#endif // __WINDOWS__
586 if( n == strlen - 1 )
587 {
588 bracket = Bracket_None;
589 }
590 else
591 {
592 switch( str[n + 1].GetValue() )
593 {
594 case wxT( '(' ):
595 bracket = Bracket_Normal;
596 str_n = str[++n]; // skip the bracket
597 break;
598
599 case wxT( '{' ):
600 bracket = Bracket_Curly;
601 str_n = str[++n]; // skip the bracket
602 break;
603
604 default:
605 bracket = Bracket_None;
606 }
607 }
608
609 size_t m = n + 1;
610
611 if( m >= strlen )
612 break;
613
614 wxUniChar str_m = str[m];
615
616 while( wxIsalnum( str_m ) || str_m == wxT( '_' ) || str_m == wxT( ':' ) )
617 {
618 if( ++m == strlen )
619 {
620 str_m = 0;
621 break;
622 }
623
624 str_m = str[m];
625 }
626
627 wxString strVarName( str.c_str() + n + 1, m - n - 1 );
628
629 if( controlChar == '$' && bracket == Bracket_Curly && ( strVarName == wxT( "DRC_WARNING" )
630 || strVarName == wxT( "DRC_ERROR" )
631 || strVarName == wxT( "ERC_WARNING" )
632 || strVarName == wxT( "ERC_ERROR" ) ) )
633 {
634 // These aren't environment variables; pass them through unchanged
635 strResult << controlChar << bracket << strVarName << str_m;
636 n = m;
637 break;
638 }
639
640 // NB: use wxGetEnv instead of wxGetenv as otherwise variables
641 // set through wxSetEnv may not be read correctly!
642 bool expanded = false;
643 wxString tmp = strVarName;
644
645 if( aProject && aProject->TextVarResolver( &tmp ) )
646 {
647 strResult += tmp;
648 expanded = true;
649 }
650 else if( readEnvironment( strVarName, &tmp ) )
651 {
652 strResult += tmp;
653 expanded = true;
654 }
655 // Replace unmatched older variables with current locations
656 // If the user has the older location defined, that will be matched
657 // first above. But if they do not, this will ensure that their board still
658 // displays correctly
659 else if( strVarName.Contains( "KISYS3DMOD" )
660 || ENV_VAR::IsVersionedEnvVar( strVarName, "3DMODEL_DIR" ) )
661 {
662 if( getVersionedEnvVar( "KICAD*_3DMODEL_DIR", strResult ) )
663 expanded = true;
664 }
665 else if( strVarName == "KICAD_SYMBOL_DIR"
666 || ENV_VAR::IsVersionedEnvVar( strVarName, "SYMBOL_DIR" ) )
667 {
668 if( getVersionedEnvVar( "KICAD*_SYMBOL_DIR", strResult ) )
669 expanded = true;
670 }
671 else if( ENV_VAR::IsVersionedEnvVar( strVarName, "FOOTPRINT_DIR" ) )
672 {
673 if( getVersionedEnvVar( "KICAD*_FOOTPRINT_DIR", strResult ) )
674 expanded = true;
675 }
676 else if( ENV_VAR::IsVersionedEnvVar( strVarName, "3RD_PARTY" ) )
677 {
678 if( getVersionedEnvVar( "KICAD*_3RD_PARTY", strResult ) )
679 expanded = true;
680 }
681 else
682 {
683 // variable doesn't exist => don't change anything
684#ifdef __WINDOWS__
685 if( bracket != Bracket_Windows )
686#endif
687 if( bracket != Bracket_None )
688 strResult << str[n - 1];
689
690 strResult << str_n << strVarName;
691 }
692
693 // When a versioned-wildcard branch matched but no env var was found, emit
694 // the original ${VARNAME} text so the closing-bracket handler can append the
695 // closing bracket. Without this, the handler emits only '}', producing a
696 // garbage path like "}/Device.kicad_sym" instead of the full unexpanded var.
697 if( !expanded && bracket != Bracket_None )
698 {
699 auto isVersionedWildcard =
700 strVarName.Contains( wxT( "KISYS3DMOD" ) )
701 || strVarName == wxT( "KICAD_SYMBOL_DIR" )
702 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "3DMODEL_DIR" ) )
703 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "SYMBOL_DIR" ) )
704 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "FOOTPRINT_DIR" ) )
705 || ENV_VAR::IsVersionedEnvVar( strVarName, wxT( "3RD_PARTY" ) );
706
707 if( isVersionedWildcard )
708 {
709#ifdef __WINDOWS__
710 if( bracket != Bracket_Windows )
711#endif
712 strResult << str[n - 1];
713
714 strResult << str_n << strVarName;
715 }
716 }
717
718 // check the closing bracket
719 if( bracket != Bracket_None )
720 {
721 if( m == strlen || str_m != (wxChar) bracket )
722 {
723 // under MSW it's common to have '%' characters in the registry
724 // and it's annoying to have warnings about them each time, so
725 // ignore them silently if they are not used for env vars
726 //
727 // under Unix, OTOH, this warning could be useful for the user to
728 // understand why isn't the variable expanded as intended
729#ifndef __WINDOWS__
730 wxLogWarning( _( "Environment variables expansion failed: missing '%c' "
731 "at position %u in '%s'." ),
732 (char) bracket, (unsigned int) ( m + 1 ), str.c_str() );
733#endif // __WINDOWS__
734 }
735 else
736 {
737 // skip closing bracket unless the variables wasn't expanded
738 if( !expanded )
739 strResult << (wxChar) bracket;
740
741 m++;
742 }
743 }
744
745 n = m - 1; // skip variable name
746 }
747 break;
748
749 case wxT( '\\' ):
750 // backslash can be used to suppress special meaning of % and $
751 if( aAllowEscapes && n < strlen - 1 && ( str[n + 1] == wxT( '%' ) || str[n + 1] == wxT( '$' ) ) )
752 {
753 strResult += str_n;
754 str_n = str[++n];
755 strResult += str_n;
756 break;
757 }
758
760
761 default:
762 strResult += str_n;
763 }
764 }
765
766 std::set<wxString> loop_check;
767 size_t first_pos = strResult.find_first_of( wxS( "{(%" ) );
768 size_t last_pos = strResult.find_last_of( wxS( "})%" ) );
769
770 if( first_pos != strResult.npos && last_pos != strResult.npos && first_pos != last_pos )
771 strResult = KIwxExpandEnvVars( strResult, aProject, aSet ? aSet : &loop_check, aAllowEscapes );
772
773 return strResult;
774}
775
776
777const wxString ExpandEnvVarSubstitutions( const wxString& aString, const PROJECT* aProject, bool aAllowEscapes )
778{
779 // wxGetenv( wchar_t* ) is not re-entrant on linux.
780 // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
781 static std::mutex getenv_mutex;
782
783 std::lock_guard<std::mutex> lock( getenv_mutex );
784
785 // We reserve the right to do this another way, by providing our own member function.
786 return KIwxExpandEnvVars( aString, aProject, nullptr, aAllowEscapes );
787}
788
789
790const wxString ResolveUriByEnvVars( const wxString& aUri, const PROJECT* aProject )
791{
792 wxString uri = ExpandTextVars( aUri, aProject, FOR_URI );
793
794 return ExpandEnvVarSubstitutions( uri, aProject, false );
795}
796
797
798wxString ExpandPathVariables( const wxString& aPath, const PROJECT* aProject,
799 const std::function<bool( wxString* )>* aTextResolver )
800{
801 wxString path = NormalizeFilePathForTextVars( aPath );
802
803 if( aTextResolver )
804 path = ExpandTextVars( path, aTextResolver, INTERNAL );
805 else if( aProject )
806 path = ExpandTextVars( path, aProject, INTERNAL );
807
808 path = ExpandEnvVarSubstitutions( path, aProject );
809
810 if( path == wxS( "~" ) || path.StartsWith( wxS( "~/" ) ) || path.StartsWith( wxS( "~\\" ) ) )
811 path = wxGetHomeDir() + path.Mid( 1 );
812
813 return path;
814}
815
816
817wxString ResolveProjectPath( const wxString& aPath, const PROJECT* aProject,
818 const std::function<bool( wxString* )>* aTextResolver )
819{
820 wxString path = ExpandPathVariables( aPath, aProject, aTextResolver );
821
822 if( path.IsEmpty() || !aProject || aProject->GetProjectFullName().IsEmpty() )
823 return path;
824
825 return aProject->AbsolutePath( path );
826}
827
828
829bool EnsureFileDirectoryExists( wxFileName* aTargetFullFileName, const wxString& aBaseFilename, REPORTER* aReporter )
830{
831 wxString msg;
832 wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
833
834 // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
835 // already an absolute path) absolute:
836 if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
837 {
838 if( aReporter )
839 {
840 msg.Printf( _( "Cannot make path '%s' absolute with respect to '%s'." ),
841 aTargetFullFileName->GetPath(),
842 baseFilePath );
843 aReporter->Report( msg, RPT_SEVERITY_ERROR );
844 }
845
846 return false;
847 }
848
849 // Ensure the path of aTargetFullFileName exists, and create it if needed:
850 wxString outputPath( aTargetFullFileName->GetPath() );
851
852 if( !wxFileName::DirExists( outputPath ) )
853 {
854 // Make every directory provided when the provided path doesn't exist
855 if( wxFileName::Mkdir( outputPath, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
856 {
857 if( aReporter )
858 {
859 msg.Printf( _( "Output directory '%s' created." ), outputPath );
860 aReporter->Report( msg, RPT_SEVERITY_INFO );
861 return true;
862 }
863 }
864 else
865 {
866 if( aReporter )
867 {
868 msg.Printf( _( "Cannot create output directory '%s'." ), outputPath );
869 aReporter->Report( msg, RPT_SEVERITY_ERROR );
870 }
871
872 return false;
873 }
874 }
875
876 return true;
877}
878
879
880wxString EnsureFileExtension( const wxString& aFilename, const wxString& aExtension )
881{
882 wxString newFilename( aFilename );
883
884 // It's annoying to throw up nag dialogs when the extension isn't right. Just fix it,
885 // but be careful not to destroy existing after-dot-text that isn't actually a bad
886 // extension, such as "Schematic_1.1".
887 if( newFilename.Lower().AfterLast( '.' ) != aExtension )
888 {
889 if( !newFilename.EndsWith( '.' ) )
890 newFilename.Append( '.' );
891
892 newFilename.Append( aExtension );
893 }
894
895 return newFilename;
896}
897
898
899wxString JoinExtensions( const std::vector<std::string>& aExts )
900{
901 wxString joined;
902
903 for( const std::string& ext : aExts )
904 {
905 if( !joined.empty() )
906 joined << wxS( ", " );
907
908 joined << wxS( "*." ) << ext;
909 }
910
911 return joined;
912}
913
914
922
929bool matchWild( const char* pat, const char* text, bool dot_special )
930{
931 if( !*text )
932 {
933 /* Match if both are empty. */
934 return !*pat;
935 }
936
937 const char *m = pat, *n = text, *ma = nullptr, *na = nullptr;
938 int just = 0, acount = 0, count = 0;
939
940 if( dot_special && ( *n == '.' ) )
941 {
942 /* Never match so that hidden Unix files
943 * are never found. */
944 return false;
945 }
946
947 for( ;; )
948 {
949 if( *m == '*' )
950 {
951 ma = ++m;
952 na = n;
953 just = 1;
954 acount = count;
955 }
956 else if( *m == '?' )
957 {
958 m++;
959
960 if( !*n++ )
961 return false;
962 }
963 else
964 {
965 if( *m == '\\' )
966 {
967 m++;
968
969 /* Quoting "nothing" is a bad thing */
970 if( !*m )
971 return false;
972 }
973
974 if( !*m )
975 {
976 /*
977 * If we are out of both strings or we just
978 * saw a wildcard, then we can say we have a
979 * match
980 */
981 if( !*n )
982 return true;
983
984 if( just )
985 return true;
986
987 just = 0;
988 goto not_matched;
989 }
990
991 /*
992 * We could check for *n == NULL at this point, but
993 * since it's more common to have a character there,
994 * check to see if they match first (m and n) and
995 * then if they don't match, THEN we can check for
996 * the NULL of n
997 */
998 just = 0;
999
1000 if( *m == *n )
1001 {
1002 m++;
1003 count++;
1004 n++;
1005 }
1006 else
1007 {
1008 not_matched:
1009
1010 /*
1011 * If there are no more characters in the
1012 * string, but we still need to find another
1013 * character (*m != NULL), then it will be
1014 * impossible to match it
1015 */
1016 if( !*n )
1017 return false;
1018
1019 if( ma )
1020 {
1021 m = ma;
1022 n = ++na;
1023 count = acount;
1024 }
1025 else
1026 return false;
1027 }
1028 }
1029 }
1030}
1031
1032
1034{
1036 return false;
1037
1038 // wxLogGui shows queued messages when a modal opens
1039 // A second modal inside this dialog makes GTK fail
1040 wxLog::FlushActive();
1041
1042 KICAD_MESSAGE_DIALOG dialog( nullptr,
1043 _( "This operating system is not supported "
1044 "by KiCad and its dependencies." ),
1045 _( "Unsupported Operating System" ), wxOK | wxICON_EXCLAMATION );
1046
1047 dialog.SetExtendedMessage( _( "Any issues with KiCad on this system cannot "
1048 "be reported to the official bugtracker." ) );
1049 dialog.ShowModal();
1050
1051 return true;
1052}
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 const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:270
virtual bool TextVarResolver(wxString *aToken) const
Definition project.cpp:177
virtual const wxString AbsolutePath(const wxString &aFileName) const
Fix up aFileName if it is relative to the project's directory to be an absolute path and filename.
Definition project.cpp:500
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()
wxString ExpandPathVariables(const wxString &aPath, const PROJECT *aProject, const std::function< bool(wxString *)> *aTextResolver)
Expand text variables, environment variables and a leading '~' in a user-entered file path.
Definition common.cpp:798
void FinalizeTextVarExpansion(wxString &aText, RESOLUTION_CONTEXT aContext)
Definition common.cpp:88
wxString JoinExtensions(const std::vector< std::string > &aExts)
Join a list of file extensions for use in a file dialog.
Definition common.cpp:899
wxString KIwxExpandEnvVars(const wxString &str, const PROJECT *aProject, std::set< wxString > *aSet=nullptr, bool aAllowEscapes=true)
Definition common.cpp:520
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:790
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:880
bool WarnUserIfOperatingSystemUnsupported()
Checks if the operating system is explicitly unsupported and displays a disclaimer message box.
Definition common.cpp:1033
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject, bool aAllowEscapes)
Replace any environment variable & text variable references with their values.
Definition common.cpp:777
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject, RESOLUTION_CONTEXT aContext)
Definition common.cpp:60
wxString ResolveProjectPath(const wxString &aPath, const PROJECT *aProject, const std::function< bool(wxString *)> *aTextResolver)
Expand a user-entered file path as ExpandPathVariables() does, then anchor a relative result at the p...
Definition common.cpp:817
bool matchWild(const char *pat, const char *text, bool dot_special)
Performance enhancements to file and directory operations.
Definition common.cpp:929
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:829
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:91
@ FOR_ERC_DRC
Definition common.h:95
@ FOR_GUI
Definition common.h:93
@ FOR_CANVAS
Definition common.h:92
@ FOR_NETNAME
Definition common.h:94
@ RAW_VALUE
Definition common.h:98
@ INTERNAL
Definition common.h:96
@ FOR_URI
Definition common.h:99
@ RESOLVED
Definition common.h:97
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:76
@ 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.