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