KiCad PCB EDA Suite
Loading...
Searching...
No Matches
string_utils.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
24
25#include <clocale>
26#include <cmath>
27#include <map>
28#include <core/map_helpers.h>
29#include <fmt/core.h>
30#include <ki_exception.h>
31#include <macros.h>
32#include <core/kicad_algo.h>
33#include <string_utils.h>
34#include <widgets/kistatusbar.h>
35#include <wx_filename.h>
36#include <fmt/chrono.h>
37#include <harfbuzz/hb.h>
38#include <wx/log.h>
39#include <wx/regex.h>
40#include <wx/tokenzr.h>
42#include "locale_io.h"
43#include <wx/event.h>
44#include <wx/uri.h>
45#include <project.h>
46#include <common.h>
47
48
54static constexpr std::string_view illegalFileNameChars = "\\/:\"<>|*?";
55
56static const wxChar defaultVariantName[] = wxT( "< Default >" );
57
58
59// Checks if a full filename is valid, i.e. does not contains illegal chars
60bool IsFullFileNameValid( const wxString& aFullFilename )
61{
62
63 // Test for forbidden chars in aFullFilename.
64 // '\'and '/' are allowed here because aFullFilename can be a full path, and
65 // ':' is allowed on Windows as second char in string.
66 // So remove allowed separators from string to test
67 wxString filtered_fullpath = aFullFilename;
68
69#ifdef __WINDOWS__
70 // On MSW, the list returned by wxFileName::GetForbiddenChars() contains separators
71 // '\'and '/'
72 filtered_fullpath.Replace( "/", "_" );
73 filtered_fullpath.Replace( "\\", "_" );
74
75 // A disk identifier is allowed, and therefore remove its separator
76 if( filtered_fullpath.Length() > 1 && filtered_fullpath[1] == ':' )
77 filtered_fullpath[1] = ' ';
78#endif
79
80 if( wxString::npos != filtered_fullpath.find_first_of( wxFileName::GetForbiddenChars() ) )
81 return false;
82
83 return true;
84}
85
86
87wxString ConvertToNewOverbarNotation( const wxString& aOldStr )
88{
89 wxString newStr;
90 bool inOverbar = false;
91
92 // Don't get tripped up by the legacy empty-string token.
93 if( aOldStr == wxT( "~" ) )
94 return aOldStr;
95
96 newStr.reserve( aOldStr.length() );
97
98 for( wxString::const_iterator chIt = aOldStr.begin(); chIt != aOldStr.end(); ++chIt )
99 {
100 if( *chIt == '~' )
101 {
102 wxString::const_iterator lookahead = chIt + 1;
103
104 if( lookahead != aOldStr.end() && *lookahead == '~' )
105 {
106 if( ++lookahead != aOldStr.end() && *lookahead == '{' )
107 {
108 // This way the subsequent opening curly brace will not start an
109 // overbar.
110 newStr << wxT( "~~{}" );
111 continue;
112 }
113
114 // Two subsequent tildes mean a tilde.
115 newStr << wxT( "~" );
116 ++chIt;
117 continue;
118 }
119 else if( lookahead != aOldStr.end() && *lookahead == '{' )
120 {
121 // Could mean the user wants "{" with an overbar, but more likely this
122 // is a case of double notation conversion. Bail out.
123 return aOldStr;
124 }
125 else
126 {
127 if( inOverbar )
128 {
129 newStr << wxT( "}" );
130 inOverbar = false;
131 }
132 else
133 {
134 newStr << wxT( "~{" );
135 inOverbar = true;
136 }
137
138 continue;
139 }
140 }
141 else if( ( *chIt == ' ' || *chIt == '}' || *chIt == ')' ) && inOverbar )
142 {
143 // Spaces were used to terminate overbar as well
144 newStr << wxT( "}" );
145 inOverbar = false;
146 }
147
148 newStr << *chIt;
149 }
150
151 // Explicitly end the overbar even if there was no terminating '~' in the aOldStr.
152 if( inOverbar )
153 newStr << wxT( "}" );
154
155 return newStr;
156}
157
158
159bool ConvertSmartQuotesAndDashes( wxString* aString )
160{
161 bool retVal = false;
162
163 for( wxString::iterator ii = aString->begin(); ii != aString->end(); ++ii )
164 {
165 if( *ii == L'\u2018' || *ii == L'\u2019' )
166 {
167 *ii = '\'';
168 retVal = true;
169 }
170 if( *ii == L'\u201C' || *ii == L'\u201D' )
171 {
172 *ii = '"';
173 retVal = true;
174 }
175 if( *ii == L'\u2013' || *ii == L'\u2014' )
176 {
177 *ii = '-';
178 retVal = true;
179 }
180 }
181
182 return retVal;
183}
184
185
187static wxUint32 codePointAt( const wxString& aText, size_t aPos, size_t& aUnits )
188{
189 const wxUint32 high = aText[aPos].GetValue();
190
191 if( high >= 0xD800 && high <= 0xDBFF && aPos + 1 < aText.length() )
192 {
193 const wxUint32 low = aText[aPos + 1].GetValue();
194
195 if( low >= 0xDC00 && low <= 0xDFFF )
196 {
197 aUnits = 2;
198 return 0x10000 + ( ( high - 0xD800 ) << 10 ) + ( low - 0xDC00 );
199 }
200 }
201
202 aUnits = 1;
203 return high;
204}
205
206
208static bool extendsCluster( wxUint32 aCodePoint )
209{
210 // Variation selectors, including the ideographic ones used in CJK names
211 if( ( aCodePoint >= 0xFE00 && aCodePoint <= 0xFE0F ) || ( aCodePoint >= 0xE0100 && aCodePoint <= 0xE01EF ) )
212 return true;
213
214 switch( hb_unicode_general_category( hb_unicode_funcs_get_default(), aCodePoint ) )
215 {
216 case HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK:
217 case HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK:
218 case HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK: return true;
219 default: return false;
220 }
221}
222
223
224static bool isVirama( wxUint32 aCodePoint )
225{
226 return hb_unicode_combining_class( hb_unicode_funcs_get_default(), aCodePoint )
227 == HB_UNICODE_COMBINING_CLASS_VIRAMA;
228}
229
230
231std::vector<wxString> SplitGraphemeClusters( const wxString& aText )
232{
233 std::vector<wxString> clusters;
234 size_t pos = 0;
235
236 while( pos < aText.length() )
237 {
238 const size_t start = pos;
239 size_t units = 0;
240 bool joinNext = false;
241
242 codePointAt( aText, pos, units );
243 pos += units;
244
245 while( pos < aText.length() )
246 {
247 const wxUint32 next = codePointAt( aText, pos, units );
248 const bool extender = extendsCluster( next );
249
250 if( !joinNext && !extender )
251 break;
252
253 // A virama binds the next base, carried through any marks before it
254 joinNext = isVirama( next ) || ( joinNext && extender );
255 pos += units;
256 }
257
258 clusters.push_back( aText.Mid( start, pos - start ) );
259 }
260
261 return clusters;
262}
263
264
265wxString EscapeString( const wxString& aSource, ESCAPE_CONTEXT aContext )
266{
267 wxString converted;
268
269 converted.reserve( aSource.length() );
270
271 for( wxUniChar c: aSource )
272 {
273 if( aContext == CTX_NETNAME )
274 {
275 if( c == '/' )
276 converted += wxT( "{slash}" );
277 else if( c == '\n' || c == '\r' )
278 converted += wxEmptyString; // drop
279 else
280 converted += c;
281 }
282 else if( aContext == CTX_LIBID || aContext == CTX_LEGACY_LIBID )
283 {
284 // We no longer escape '/' in LIB_IDs, but we used to
285 if( c == '/' && aContext == CTX_LEGACY_LIBID )
286 converted += wxT( "{slash}" );
287 else if( c == '\\' )
288 converted += wxT( "{backslash}" );
289 else if( c == '<' )
290 converted += wxT( "{lt}" );
291 else if( c == '>' )
292 converted += wxT( "{gt}" );
293 else if( c == ':' )
294 converted += wxT( "{colon}" );
295 else if( c == '\"' )
296 converted += wxT( "{dblquote}" );
297 else if( c == '\n' || c == '\r' )
298 converted += wxEmptyString; // drop
299 else
300 converted += c;
301 }
302 else if( aContext == CTX_IPC )
303 {
304 if( c == '/' )
305 converted += wxT( "{slash}" );
306 else if( c == ',' )
307 converted += wxT( "{comma}" );
308 else if( c == '\"' )
309 converted += wxT( "{dblquote}" );
310 else
311 converted += c;
312 }
313 else if( aContext == CTX_QUOTED_STR )
314 {
315 if( c == '\"' )
316 converted += wxT( "{dblquote}" );
317 else
318 converted += c;
319 }
320 else if( aContext == CTX_JS_STR )
321 {
322 if( c >= 0x7F || c == '\'' || c == '"' || c == '\\' || c == '(' || c == ')' )
323 {
324 unsigned int code = c;
325 char buffer[16];
326 snprintf( buffer, sizeof(buffer), "\\u%4.4X", code );
327 converted += buffer;
328 }
329 else
330 {
331 converted += c;
332 }
333 }
334 else if( aContext == CTX_LINE )
335 {
336 if( c == '\n' || c == '\r' )
337 converted += wxT( "{return}" );
338 else
339 converted += c;
340 }
341 else if( aContext == CTX_FILENAME )
342 {
343 if( c == '/' )
344 converted += wxT( "{slash}" );
345 else if( c == '\\' )
346 converted += wxT( "{backslash}" );
347 else if( c == '\"' )
348 converted += wxT( "{dblquote}" );
349 else if( c == '<' )
350 converted += wxT( "{lt}" );
351 else if( c == '>' )
352 converted += wxT( "{gt}" );
353 else if( c == '|' )
354 converted += wxT( "{bar}" );
355 else if( c == ':' )
356 converted += wxT( "{colon}" );
357 else if( c == '\t' )
358 converted += wxT( "{tab}" );
359 else if( c == '\n' || c == '\r' )
360 converted += wxT( "{return}" );
361 else
362 converted += c;
363 }
364 else if( aContext == CTX_NO_SPACE )
365 {
366 if( c == ' ' )
367 converted += wxT( "{space}" );
368 else
369 converted += c;
370 }
371 else if( aContext == CTX_CSV )
372 {
373 if( c == ',' )
374 converted += wxT( "{comma}" );
375 else if( c == '\n' || c == '\r' )
376 converted += wxT( "{return}" );
377 else
378 converted += c;
379 }
380 else if( aContext == CTX_REGEX )
381 {
382 const wxString regExCtrlChars = wxT( ".^$*+?{}()[]~|\\" );
383
384 if( regExCtrlChars.Contains( c ) )
385 converted += wxT( "\\" );
386
387 converted += c;
388 }
389 else
390 {
391 converted += c;
392 }
393 }
394
395 return converted;
396}
397
398
399wxString UnescapeString( const wxString& aSource )
400{
401 size_t sourceLen = aSource.length();
402
403 // smallest escape string is three characters, shortcut everything else
404 if( sourceLen <= 2 )
405 {
406 return aSource;
407 }
408
409 wxString newbuf;
410 newbuf.reserve( sourceLen );
411
412 wxUniChar prev = 0;
413 wxUniChar ch = 0;
414
415 for( size_t i = 0; i < sourceLen; ++i )
416 {
417 prev = ch;
418 ch = aSource[i];
419
420 if( ch == '{' )
421 {
422 wxString token;
423 int depth = 1;
424 bool terminated = false;
425
426 for( i = i + 1; i < sourceLen; ++i )
427 {
428 ch = aSource[i];
429
430 if( ch == '{' )
431 depth++;
432 else if( ch == '}' )
433 depth--;
434
435 if( depth <= 0 )
436 {
437 terminated = true;
438 break;
439 }
440 else
441 {
442 token << ch;
443 }
444 }
445
446 if( !terminated )
447 {
448 newbuf << wxT( "{" ) << UnescapeString( token );
449 }
450 else if( prev == '$' || prev == '~' || prev == '^' || prev == '_' )
451 {
452 newbuf << wxT( "{" ) << UnescapeString( token ) << wxT( "}" );
453 }
454 else if( token == wxT( "dblquote" ) ) newbuf << wxT( "\"" );
455 else if( token == wxT( "quote" ) ) newbuf << wxT( "'" );
456 else if( token == wxT( "lt" ) ) newbuf << wxT( "<" );
457 else if( token == wxT( "gt" ) ) newbuf << wxT( ">" );
458 else if( token == wxT( "backslash" ) ) newbuf << wxT( "\\" );
459 else if( token == wxT( "slash" ) ) newbuf << wxT( "/" );
460 else if( token == wxT( "bar" ) ) newbuf << wxT( "|" );
461 else if( token == wxT( "comma" ) ) newbuf << wxT( "," );
462 else if( token == wxT( "colon" ) ) newbuf << wxT( ":" );
463 else if( token == wxT( "space" ) ) newbuf << wxT( " " );
464 else if( token == wxT( "dollar" ) ) newbuf << wxT( "$" );
465 else if( token == wxT( "tab" ) ) newbuf << wxT( "\t" );
466 else if( token == wxT( "return" ) ) newbuf << wxT( "\n" );
467 else if( token == wxT( "brace" ) ) newbuf << wxT( "{" );
468 else
469 {
470 newbuf << wxT( "{" ) << UnescapeString( token ) << wxT( "}" );
471 }
472 }
473 else
474 {
475 newbuf << ch;
476 }
477 }
478
479 return newbuf;
480}
481
482
483wxString TitleCaps( const wxString& aString )
484{
485 wxArrayString words;
486 wxString result;
487
488 wxStringSplit( aString, words, ' ' );
489
490 result.reserve( aString.length() );
491
492 for( const wxString& word : words )
493 {
494 if( !result.IsEmpty() )
495 result += wxT( " " );
496
497 result += word.Capitalize();
498 }
499
500 return result;
501}
502
503
504wxString InitialCaps( const wxString& aString )
505{
506 wxArrayString words;
507 wxString result;
508
509 wxStringSplit( aString, words, ' ' );
510
511 result.reserve( aString.length() );
512
513 for( const wxString& word : words )
514 {
515 if( result.IsEmpty() )
516 result += word.Capitalize();
517 else
518 result += wxT( " " ) + word.Lower();
519 }
520
521 return result;
522}
523
524
525int ReadDelimitedText( wxString* aDest, const char* aSource )
526{
527 std::string utf8; // utf8 but without escapes and quotes.
528 bool inside = false;
529 const char* start = aSource;
530 char cc;
531
532 while( (cc = *aSource++) != 0 )
533 {
534 if( cc == '"' )
535 {
536 if( inside )
537 break; // 2nd double quote is end of delimited text
538
539 inside = true; // first delimiter found, make note, do not copy
540 }
541
542 else if( inside )
543 {
544 if( cc == '\\' )
545 {
546 cc = *aSource++;
547
548 if( !cc )
549 break;
550
551 // do no copy the escape byte if it is followed by \ or "
552 if( cc != '"' && cc != '\\' )
553 utf8 += '\\';
554
555 utf8 += cc;
556 }
557 else
558 {
559 utf8 += cc;
560 }
561 }
562 }
563
564 *aDest = From_UTF8( utf8.c_str() );
565
566 return aSource - start;
567}
568
569
570int ReadDelimitedText( char* aDest, const char* aSource, int aDestSize )
571{
572 if( aDestSize <= 0 )
573 return 0;
574
575 bool inside = false;
576 const char* start = aSource;
577 char* limit = aDest + aDestSize - 1;
578 char cc;
579
580 while( ( cc = *aSource++ ) != 0 && aDest < limit )
581 {
582 if( cc == '"' )
583 {
584 if( inside )
585 break; // 2nd double quote is end of delimited text
586
587 inside = true; // first delimiter found, make note, do not copy
588 }
589 else if( inside )
590 {
591 if( cc == '\\' )
592 {
593 cc = *aSource++;
594
595 if( !cc )
596 break;
597
598 // do no copy the escape byte if it is followed by \ or "
599 if( cc != '"' && cc != '\\' )
600 *aDest++ = '\\';
601
602 if( aDest < limit )
603 *aDest++ = cc;
604 }
605 else
606 {
607 *aDest++ = cc;
608 }
609 }
610 }
611
612 *aDest = 0;
613
614 return aSource - start;
615}
616
617
618std::string EscapedUTF8( const wxString& aString )
619{
620 wxString str = aString;
621
622 // No new-lines allowed in quoted strings
623 str.Replace( wxT( "\r\n" ), wxT( "\r" ) );
624 str.Replace( wxT( "\n" ), wxT( "\r" ) );
625
626 std::string utf8 = TO_UTF8( aString );
627
628 std::string ret;
629
630 ret.reserve( utf8.length() + 2 );
631
632 ret += '"';
633
634 for( std::string::const_iterator it = utf8.begin(); it!=utf8.end(); ++it )
635 {
636 // this escaping strategy is designed to be compatible with ReadDelimitedText():
637 if( *it == '"' )
638 {
639 ret += '\\';
640 ret += '"';
641 }
642 else if( *it == '\\' )
643 {
644 ret += '\\'; // double it up
645 ret += '\\';
646 }
647 else
648 {
649 ret += *it;
650 }
651 }
652
653 ret += '"';
654
655 return ret;
656}
657
658
659wxString EscapeHTML( const wxString& aString )
660{
661 wxString converted;
662
663 converted.reserve( aString.length() );
664
665 for( wxUniChar c : aString )
666 {
667 if( c == '\"' )
668 converted += wxT( "&quot;" );
669 else if( c == '\'' )
670 converted += wxT( "&apos;" );
671 else if( c == '&' )
672 converted += wxT( "&amp;" );
673 else if( c == '<' )
674 converted += wxT( "&lt;" );
675 else if( c == '>' )
676 converted += wxT( "&gt;" );
677 else
678 converted += c;
679 }
680
681 return converted;
682}
683
684
685wxString UnescapeHTML( const wxString& aString )
686{
687 // clang-format off
688 static const std::map<wxString, wxString> c_replacements = {
689 { wxS( "quot" ), wxS( "\"" ) },
690 { wxS( "apos" ), wxS( "'" ) },
691 { wxS( "amp" ), wxS( "&" ) },
692 { wxS( "lt" ), wxS( "<" ) },
693 { wxS( "gt" ), wxS( ">" ) }
694 };
695 // clang-format on
696
697 // Construct regex
698 wxString regexStr = "&(#(\\d*)|#x([a-zA-Z0-9]{4})";
699
700 for( auto& [key, value] : c_replacements )
701 regexStr << '|' << key;
702
703 regexStr << ");";
704
705 wxRegEx regex( regexStr );
706
707 // Process matches
708 size_t start = 0;
709 size_t len = 0;
710
711 wxString result;
712 wxString str = aString;
713
714 while( regex.Matches( str ) )
715 {
716 std::vector<wxString> matches;
717 regex.GetMatch( &start, &len );
718
719 result << str.Left( start );
720
721 wxString code = regex.GetMatch( str, 1 );
722 wxString codeDec = regex.GetMatch( str, 2 );
723 wxString codeHex = regex.GetMatch( str, 3 );
724
725 if( !codeDec.IsEmpty() || !codeHex.IsEmpty() )
726 {
727 unsigned long codeVal = 0;
728
729 if( !codeDec.IsEmpty() )
730 codeDec.ToCULong( &codeVal );
731 else if( !codeHex.IsEmpty() )
732 codeHex.ToCULong( &codeVal, 16 );
733
734 if( codeVal != 0 )
735 result << wxUniChar( codeVal );
736 }
737 else if( auto val = get_opt( c_replacements, code ) )
738 {
739 result << *val;
740 }
741
742 str = str.Mid( start + len );
743 }
744
745 result << str;
746
747 return result;
748}
749
750
751wxString RemoveHTMLTags( const wxString& aInput )
752{
753 wxString str = aInput;
754 wxRegEx( wxS( "<[^>]*>" ) ).ReplaceAll( &str, wxEmptyString );
755
756 return str;
757}
758
759
760wxString LinkifyHTML( wxString aStr )
761{
762 static wxRegEx regex( wxS( "\\b(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\(\\)\\s\u00b6])" ),
763 wxRE_ICASE );
764
765 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
766
767 return aStr;
768}
769
770
771bool IsURL( wxString aStr )
772{
773 static wxRegEx regex( wxS( "(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\s\u00b6])" ),
774 wxRE_ICASE );
775
776 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
777
778 return regex.Matches( aStr );
779}
780
781
782bool NoPrintableChars( const wxString& aString )
783{
784 wxString tmp = aString;
785
786 return tmp.Trim( true ).Trim( false ).IsEmpty();
787}
788
789
790int PrintableCharCount( const wxString& aString )
791{
792 int char_count = 0;
793 int overbarDepth = -1;
794 int superSubDepth = -1;
795 int braceNesting = 0;
796
797 for( auto chIt = aString.begin(), end = aString.end(); chIt < end; ++chIt )
798 {
799 if( *chIt == '\t' )
800 {
801 // We don't format tabs in bitmap text (where this is currently used), so just
802 // drop them from the count.
803 continue;
804 }
805 else if( *chIt == '^' && superSubDepth == -1 )
806 {
807 auto lookahead = chIt;
808
809 if( ++lookahead != end && *lookahead == '{' )
810 {
811 chIt = lookahead;
812 superSubDepth = braceNesting;
813 braceNesting++;
814 continue;
815 }
816 }
817 else if( *chIt == '_' && superSubDepth == -1 )
818 {
819 auto lookahead = chIt;
820
821 if( ++lookahead != end && *lookahead == '{' )
822 {
823 chIt = lookahead;
824 superSubDepth = braceNesting;
825 braceNesting++;
826 continue;
827 }
828 }
829 else if( *chIt == '~' && overbarDepth == -1 )
830 {
831 auto lookahead = chIt;
832
833 if( ++lookahead != end && *lookahead == '{' )
834 {
835 chIt = lookahead;
836 overbarDepth = braceNesting;
837 braceNesting++;
838 continue;
839 }
840 }
841 else if( *chIt == '{' )
842 {
843 braceNesting++;
844 }
845 else if( *chIt == '}' )
846 {
847 if( braceNesting > 0 )
848 braceNesting--;
849
850 if( braceNesting == superSubDepth )
851 {
852 superSubDepth = -1;
853 continue;
854 }
855
856 if( braceNesting == overbarDepth )
857 {
858 overbarDepth = -1;
859 continue;
860 }
861 }
862
863 char_count++;
864 }
865
866 return char_count;
867}
868
869
870char* StrPurge( char* text )
871{
872 static const char whitespace[] = " \t\n\r\f\v";
873
874 if( text )
875 {
876 while( *text && strchr( whitespace, *text ) )
877 ++text;
878
879 char* cp = text + strlen( text ) - 1;
880
881 while( cp >= text && strchr( whitespace, *cp ) )
882 *cp-- = '\0';
883 }
884
885 return text;
886}
887
888
889char* GetLine( FILE* File, char* Line, int* LineNum, int SizeLine )
890{
891 do {
892 if( fgets( Line, SizeLine, File ) == nullptr )
893 return nullptr;
894
895 if( LineNum )
896 *LineNum += 1;
897
898 } while( Line[0] == '#' || Line[0] == '\n' || Line[0] == '\r' || Line[0] == 0 );
899
900 strtok( Line, "\n\r" );
901 return Line;
902}
903
904
906{
907 return wxDateTime::Now().FormatISOCombined( 'T' );
908}
909
910
911int StrNumCmp( const wxString& aString1, const wxString& aString2, CMP_T aCaseSensitivity )
912{
913 int nb1 = 0, nb2 = 0;
914
915 auto str1 = aString1.begin();
916 auto str2 = aString2.begin();
917
918 const auto str1End = aString1.end();
919 const auto str2End = aString2.end();
920
921 while( str1 != str1End && str2 != str2End )
922 {
923 wxUniChar c1 = *str1;
924 wxUniChar c2 = *str2;
925
926 if( wxIsdigit( c1 ) && wxIsdigit( c2 ) ) // Both characters are digits, do numeric compare.
927 {
928 nb1 = 0;
929 nb2 = 0;
930
931 do
932 {
933 c1 = *str1;
934 nb1 = nb1 * 10 + (int) c1 - '0';
935 ++str1;
936 } while( str1 != str1End && wxIsdigit( *str1 ) );
937
938 do
939 {
940 c2 = *str2;
941 nb2 = nb2 * 10 + (int) c2 - '0';
942 ++str2;
943 } while( str2 != str2End && wxIsdigit( *str2 ) );
944
945 if( nb1 < nb2 )
946 return -1;
947
948 if( nb1 > nb2 )
949 return 1;
950
951 c1 = ( str1 != str1End ) ? *str1 : wxUniChar( 0 );
952 c2 = ( str2 != str2End ) ? *str2 : wxUniChar( 0 );
953 }
954
955 // Any numerical comparisons to here are identical.
956 if( aCaseSensitivity == CMP_T::IGNORE_CASE )
957 {
958 if( c1 != c2 )
959 {
960 wxUniChar uc1 = wxToupper( c1 );
961 wxUniChar uc2 = wxToupper( c2 );
962
963 if( uc1 != uc2 )
964 return uc1 < uc2 ? -1 : 1;
965 }
966 }
967 else
968 {
969 if( c1 < c2 )
970 return -1;
971
972 if( c1 > c2 )
973 return 1;
974 }
975
976 if( str1 != str1End )
977 ++str1;
978
979 if( str2 != str2End )
980 ++str2;
981 }
982
983 if( str1 == str1End && str2 != str2End )
984 {
985 return -1; // Identical to here but aString1 is longer.
986 }
987 else if( str1 != str1End && str2 == str2End )
988 {
989 return 1; // Identical to here but aString2 is longer.
990 }
991
992 return 0;
993}
994
995
996bool WildCompareString( const wxString& pattern, const wxString& string_to_tst, bool case_sensitive )
997{
998 const wxChar* cp = nullptr;
999 const wxChar* mp = nullptr;
1000 const wxChar* wild = nullptr;
1001 const wxChar* str = nullptr;
1002 wxString _pattern, _string_to_tst;
1003
1004 if( case_sensitive )
1005 {
1006 wild = pattern.GetData();
1007 str = string_to_tst.GetData();
1008 }
1009 else
1010 {
1011 _pattern = pattern;
1012 _pattern.MakeUpper();
1013 _string_to_tst = string_to_tst;
1014 _string_to_tst.MakeUpper();
1015 wild = _pattern.GetData();
1016 str = _string_to_tst.GetData();
1017 }
1018
1019 while( ( *str ) && ( *wild != '*' ) )
1020 {
1021 if( ( *wild != *str ) && ( *wild != '?' ) )
1022 return false;
1023
1024 wild++;
1025 str++;
1026 }
1027
1028 while( *str )
1029 {
1030 if( *wild == '*' )
1031 {
1032 if( !*++wild )
1033 return true;
1034
1035 mp = wild;
1036 cp = str + 1;
1037 }
1038 else if( ( *wild == *str ) || ( *wild == '?' ) )
1039 {
1040 wild++;
1041 str++;
1042 }
1043 else
1044 {
1045 wild = mp;
1046 str = cp++;
1047 }
1048 }
1049
1050 while( *wild == '*' )
1051 {
1052 wild++;
1053 }
1054
1055 return !*wild;
1056}
1057
1058
1059bool ApplyModifier( double& value, const wxString& aString )
1060{
1062 static const wxString modifiers( wxT( "afpnuµμmLRFkKMGTPE" ) );
1063
1064 if( !aString.length() )
1065 return false;
1066
1067 wxChar modifier;
1068 wxString units;
1069
1070 if( aString.Strip() == wxT( "m" ) )
1071 {
1072 // a single m is meters, not milli-undefineds
1073 return true;
1074 }
1075 else if( aString.Strip() == wxT( "mils" ) )
1076 {
1077 value *= 0.0000254;
1078 return true;
1079 }
1080 else if( aString.Strip() == wxT( "in" ) )
1081 {
1082 value *= 0.0254;
1083 return true;
1084 }
1085 if( modifiers.Find( aString[ 0 ] ) >= 0 )
1086 {
1087 modifier = aString[ 0 ];
1088 units = aString.Mid( 1 ).Trim();
1089 }
1090 else
1091 {
1092 modifier = ' ';
1093 units = aString.Mid( 0 ).Trim();
1094 }
1095
1096 if( units.length()
1097 && !units.IsSameAs( wxT( "F" ), false )
1098 && !units.IsSameAs( wxT( "hz" ), false )
1099 && !units.IsSameAs( wxT( "Ω" ), false )
1100 && !units.IsSameAs( wxT( "W" ), false )
1101 && !units.IsSameAs( wxT( "V" ), false )
1102 && !units.IsSameAs( wxT( "A" ), false )
1103 && !units.IsSameAs( wxT( "H" ), false )
1104 && !units.IsSameAs( wxT( "s" ), false )
1105 && !units.IsSameAs( wxT( "m" ), false ) )
1106 {
1107 return false;
1108 }
1109
1110 // Note: most of these are SI, but some (L, R, F) are IEC 60062.
1111 if( modifier == 'a' )
1112 value *= 1.0e-18;
1113 else if( modifier == 'f' )
1114 value *= 1.0e-15;
1115 if( modifier == 'p' )
1116 value *= 1.0e-12;
1117 if( modifier == 'n' )
1118 value *= 1.0e-9;
1120 else if( modifier == 'u' || modifier == wxS( "µ" )[0] || modifier == wxS( "μ" )[0] )
1121 value *= 1.0e-6;
1122 else if( modifier == 'm' || modifier == 'L' )
1123 value *= 1.0e-3;
1124 else if( modifier == 'R' || modifier == 'F' )
1125 ; // unity scalar
1126 else if( modifier == 'c' ) // primarily for cm
1127 value *= 1.0e2;
1128 else if( modifier == 'k' || modifier == 'K' )
1129 value *= 1.0e3;
1130 else if( modifier == 'M' )
1131 value *= 1.0e6;
1132 else if( modifier == 'G' )
1133 value *= 1.0e9;
1134 else if( modifier == 'T' )
1135 value *= 1.0e12;
1136 else if( modifier == 'P' )
1137 value *= 1.0e15;
1138 else if( modifier == 'E' )
1139 value *= 1.0e18;
1140
1141 return true;
1142}
1143
1144
1145bool convertSeparators( wxString* value )
1146{
1147 // Note: fetching the decimal separator from the current locale isn't a silver bullet because
1148 // it assumes the current computer's locale is the same as the locale the schematic was
1149 // authored in -- something that isn't true, for instance, when sharing designs through
1150 // DIYAudio.com.
1151 //
1152 // Some values are self-describing: multiple instances of a single separator character must be
1153 // thousands separators; a single instance of each character must be a thousands separator
1154 // followed by a decimal separator; etc.
1155 //
1156 // Only when presented with an ambiguous value do we fall back on the current locale.
1157
1158 value->Replace( wxS( " " ), wxEmptyString );
1159
1160 wxChar ambiguousSeparator = '?';
1161 wxChar thousandsSeparator = '?';
1162 bool thousandsSeparatorFound = false;
1163 wxChar decimalSeparator = '?';
1164 bool decimalSeparatorFound = false;
1165 int digits = 0;
1166
1167 for( int ii = (int) value->length() - 1; ii >= 0; --ii )
1168 {
1169 wxChar c = value->GetChar( ii );
1170
1171 if( c >= '0' && c <= '9' )
1172 {
1173 digits += 1;
1174 }
1175 else if( c == '.' || c == ',' )
1176 {
1177 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1178 {
1179 // We've previously found a non-ambiguous separator...
1180
1181 if( c == decimalSeparator )
1182 {
1183 if( thousandsSeparatorFound )
1184 return false; // decimal before thousands
1185 else if( decimalSeparatorFound )
1186 return false; // more than one decimal
1187 else
1188 decimalSeparatorFound = true;
1189 }
1190 else if( c == thousandsSeparator )
1191 {
1192 if( digits != 3 )
1193 return false; // thousands not followed by 3 digits
1194 else
1195 thousandsSeparatorFound = true;
1196 }
1197 }
1198 else if( ambiguousSeparator != '?' )
1199 {
1200 // We've previously found a separator, but we don't know for sure which...
1201
1202 if( c == ambiguousSeparator )
1203 {
1204 // They both must be thousands separators
1205 thousandsSeparator = ambiguousSeparator;
1206 thousandsSeparatorFound = true;
1207 decimalSeparator = c == '.' ? ',' : '.';
1208 }
1209 else
1210 {
1211 // The first must have been a decimal, and this must be a thousands.
1212 decimalSeparator = ambiguousSeparator;
1213 decimalSeparatorFound = true;
1214 thousandsSeparator = c;
1215 thousandsSeparatorFound = true;
1216 }
1217 }
1218 else
1219 {
1220 // This is the first separator...
1221
1222 // If it's preceded by a '0' (only), or if it's followed by some number of
1223 // digits not equal to 3, then it -must- be a decimal separator.
1224 //
1225 // In all other cases we don't really know what it is yet.
1226
1227 if( ( ii == 1 && value->GetChar( 0 ) == '0' ) || digits != 3 )
1228 {
1229 decimalSeparator = c;
1230 decimalSeparatorFound = true;
1231 thousandsSeparator = c == '.' ? ',' : '.';
1232 }
1233 else
1234 {
1235 ambiguousSeparator = c;
1236 }
1237 }
1238
1239 digits = 0;
1240 }
1241 else
1242 {
1243 digits = 0;
1244 }
1245 }
1246
1247 // If we found nothing definitive then we have to look at the current locale
1248 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1249 {
1250 const struct lconv* lc = localeconv();
1251
1252 decimalSeparator = lc->decimal_point[0];
1253 thousandsSeparator = decimalSeparator == '.' ? ',' : '.';
1254 }
1255
1256 // Convert to C-locale
1257 value->Replace( thousandsSeparator, wxEmptyString );
1258 value->Replace( decimalSeparator, '.' );
1259
1260 return true;
1261}
1262
1263
1264// Return true if aStr can be parsed as a numeric value (including units and scalers, so
1265// something like "4K7Ω" will return true).
1266bool QuacksLikeADuck( const wxString& aStr, double* aValue )
1267{
1268 if( aValue )
1269 *aValue = NAN;
1270
1271 wxString str = UnescapeString( aStr );
1272
1273 wxString beforeDigits, digits, afterDigits;
1274 SplitString( str, &beforeDigits, &digits, &afterDigits );
1275
1276 if( !beforeDigits.Trim( true ).Trim( false ).IsEmpty() )
1277 return false;
1278
1279 double number = 0;
1280 convertSeparators( &digits );
1281
1282 if( !digits.ToCDouble( &number ) )
1283 return false;
1284
1285 if( !afterDigits.IsEmpty() && !ApplyModifier( number, afterDigits ) )
1286 return false;
1287
1288 if( aValue )
1289 *aValue = number;
1290
1291 return true;
1292}
1293
1294
1295int ValueStringCompare( const wxString& strFWord, const wxString& strSWord )
1296{
1297 // Compare unescaped text
1298 wxString fWord = UnescapeString( strFWord );
1299 wxString sWord = UnescapeString( strSWord );
1300
1301 // The different sections of the two strings
1302 wxString strFWordBeg, strFWordMid, strFWordEnd;
1303 wxString strSWordBeg, strSWordMid, strSWordEnd;
1304
1305 // Split the two strings into separate parts
1306 SplitString( fWord, &strFWordBeg, &strFWordMid, &strFWordEnd );
1307 SplitString( sWord, &strSWordBeg, &strSWordMid, &strSWordEnd );
1308
1309 // Compare the Beginning section of the strings
1310 int isEqual = strFWordBeg.CmpNoCase( strSWordBeg );
1311
1312 if( isEqual > 0 )
1313 {
1314 return 1;
1315 }
1316 else if( isEqual < 0 )
1317 {
1318 return -1;
1319 }
1320 else
1321 {
1322 // If the first sections are equal compare their digits
1323 double lFirstNumber = 0;
1324 double lSecondNumber = 0;
1325 bool endingIsModifier = false;
1326
1327 convertSeparators( &strFWordMid );
1328 convertSeparators( &strSWordMid );
1329
1330 strFWordMid.ToCDouble( &lFirstNumber );
1331 strSWordMid.ToCDouble( &lSecondNumber );
1332
1333 endingIsModifier |= ApplyModifier( lFirstNumber, strFWordEnd );
1334 endingIsModifier |= ApplyModifier( lSecondNumber, strSWordEnd );
1335
1336 if( lFirstNumber > lSecondNumber )
1337 return 1;
1338 else if( lFirstNumber < lSecondNumber )
1339 return -1;
1340 // If the first two sections are equal and the endings are modifiers then compare them
1341 else if( !endingIsModifier )
1342 return strFWordEnd.CmpNoCase( strSWordEnd );
1343 // Ran out of things to compare; they must match
1344 else
1345 return 0;
1346 }
1347}
1348
1349
1350int SplitString( const wxString& strToSplit,
1351 wxString* strBeginning,
1352 wxString* strDigits,
1353 wxString* strEnd )
1354{
1355 static const wxString separators( wxT( ".," ) );
1356 wxUniChar infix = 0;
1357
1358 // Clear all the return strings
1359 strBeginning->Empty();
1360 strDigits->Empty();
1361 strEnd->Empty();
1362
1363 // There no need to do anything if the string is empty
1364 if( strToSplit.length() == 0 )
1365 return 0;
1366
1367 // Starting at the end of the string look for the first digit
1368 int ii;
1369
1370 for( ii = (strToSplit.length() - 1); ii >= 0; ii-- )
1371 {
1372 if( wxIsdigit( strToSplit[ii] ) )
1373 break;
1374 }
1375
1376 // If there were no digits then just set the single string
1377 if( ii < 0 )
1378 {
1379 *strBeginning = strToSplit;
1380 }
1381 else
1382 {
1383 // Since there is at least one digit this is the trailing string
1384 *strEnd = strToSplit.substr( ii + 1 );
1385
1386 // Go to the end of the digits
1387 int position = ii + 1;
1388
1389 for( ; ii >= 0; ii-- )
1390 {
1391 double scale;
1392 wxUniChar c = strToSplit[ii];
1393
1394 if( wxIsdigit( c ) )
1395 {
1396 continue;
1397 }
1398 // This can be tricky to get to parse things like 4K7 (or just K7)
1399 // but not G4W
1400 if(
1401 // Only allow one infix character e.g. 4K7, not 4KK7
1402 infix == 0
1403 // Allowed only it isn't the first character, or nothing follows it,
1404 // e.g. K7 but not K7X
1405 && ( ii > 0 || strEnd->IsEmpty() )
1406 // Also make sure its a valid SI separator, e.g. 4K7 but not 4X7
1408 // Finally make that the combo makes sense e.g. T9G fails because TG is not a valid combo,
1409 // but unfortunately cursed constructions like 1u5F are indeed found in the wild
1410 && ApplyModifier( scale, c + *strEnd ) )
1411 {
1412 infix = c;
1413 continue;
1414 }
1415 else if( separators.Find( strToSplit[ii] ) >= 0 )
1416 {
1417 continue;
1418 }
1419 else
1420 {
1421 break;
1422 }
1423 }
1424
1425 // If all that was left was digits, then just set the digits string
1426 if( ii < 0 )
1427 {
1428 *strDigits = strToSplit.substr( 0, position );
1429 }
1430 // Otherwise everything else is part of the preamble
1431 else
1432 {
1433 *strDigits = strToSplit.substr( ii + 1, position - ii - 1 );
1434 *strBeginning = strToSplit.substr( 0, ii + 1 );
1435 }
1436
1437 if( infix > 0 )
1438 {
1439 strDigits->Replace( infix, '.' );
1440 *strEnd = infix + *strEnd;
1441 }
1442 }
1443
1444 return 0;
1445}
1446
1447
1448int GetTrailingInt( const wxString& aStr )
1449{
1450 int number = 0;
1451 int base = 1;
1452
1453 // Trim and extract the trailing numeric part
1454 int index = aStr.Len() - 1;
1455
1456 while( index >= 0 )
1457 {
1458 const char chr = aStr.GetChar( index );
1459
1460 if( chr < '0' || chr > '9' )
1461 break;
1462
1463 number += ( chr - '0' ) * base;
1464 base *= 10;
1465 index--;
1466 }
1467
1468 return number;
1469}
1470
1471
1473{
1474 return wxString::FromUTF8( illegalFileNameChars.data(), illegalFileNameChars.length() );
1475}
1476
1477
1478bool ReplaceIllegalFileNameChars( std::string& aName, int aReplaceChar )
1479{
1480 size_t first_illegal_pos = aName.find_first_of( illegalFileNameChars );
1481
1482 if( first_illegal_pos == std::string::npos )
1483 {
1484 return false;
1485 }
1486
1487 std::string result;
1488 // result will be at least equal to original, add 16 in case of hex replacements
1489 result.reserve( aName.length() + 16 );
1490 // append the valid part
1491 result.append( aName, 0, first_illegal_pos );
1492
1493 for( size_t i = first_illegal_pos; i < aName.length(); ++i )
1494 {
1495 char c = aName[i];
1496
1497 // Check if this specific char is illegal
1498 if( illegalFileNameChars.find( c ) != std::string_view::npos )
1499 {
1500 if( aReplaceChar )
1501 {
1502 result.push_back( aReplaceChar );
1503 }
1504 else
1505 {
1506 fmt::format_to( std::back_inserter( result ), "%{:02x}", static_cast<unsigned char>( c ) );
1507 }
1508 }
1509 else
1510 {
1511 result.push_back( c );
1512 }
1513 }
1514
1515 aName = std::move( result );
1516 return true;
1517}
1518
1519
1520bool ReplaceIllegalFileNameChars( wxString& aName, int aReplaceChar )
1521{
1522 bool changed = false;
1523 wxString result;
1524 result.reserve( aName.Length() );
1525 wxString illWChars = GetIllegalFileNameWxChars();
1526
1527 for( wxString::iterator it = aName.begin(); it != aName.end(); ++it )
1528 {
1529 if( illWChars.Find( *it ) != wxNOT_FOUND )
1530 {
1531 if( aReplaceChar )
1532 result += aReplaceChar;
1533 else
1534 result += wxString::Format( "%%%02x", *it );
1535
1536 changed = true;
1537 }
1538 else
1539 {
1540 result += *it;
1541 }
1542 }
1543
1544 if( changed )
1545 aName = std::move( result );
1546
1547 return changed;
1548}
1549
1550
1551void wxStringSplit( const wxString& aText, wxArrayString& aStrings, wxChar aSplitter )
1552{
1553 wxString tmp;
1554
1555 for( unsigned ii = 0; ii < aText.Length(); ii++ )
1556 {
1557 if( aText[ii] == aSplitter )
1558 {
1559 aStrings.Add( tmp );
1560 tmp.Clear();
1561 }
1562 else
1563 {
1564 tmp << aText[ii];
1565 }
1566 }
1567
1568 if( !tmp.IsEmpty() )
1569 aStrings.Add( tmp );
1570}
1571
1572
1573void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed )
1574{
1575 struct lconv* lc = localeconv();
1576 char sep = lc->decimal_point[0];
1577 unsigned sep_pos = aStringValue.Find( sep );
1578
1579 if( sep_pos > 0 )
1580 {
1581 // We want to keep at least aTrailingZeroAllowed digits after the separator
1582 unsigned min_len = sep_pos + aTrailingZeroAllowed + 1;
1583
1584 while( aStringValue.Len() > min_len )
1585 {
1586 if( aStringValue.Last() == '0' )
1587 aStringValue.RemoveLast();
1588 else
1589 break;
1590 }
1591 }
1592}
1593
1594
1595std::string FormatDouble2Str( double aValue )
1596{
1597 std::string buf;
1598
1599 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1600 {
1601 buf = fmt::format( "{:.16f}", aValue );
1602
1603 // remove trailing zeros (and the decimal marker if needed)
1604 while( !buf.empty() && buf[buf.size() - 1] == '0' )
1605 {
1606 buf.pop_back();
1607 }
1608
1609 // if the value was really small
1610 // we may have just stripped all the zeros after the decimal
1611 if( buf[buf.size() - 1] == '.' )
1612 {
1613 buf.pop_back();
1614 }
1615 }
1616 else
1617 {
1618 buf = fmt::format( "{:.10g}", aValue );
1619 }
1620
1621 return buf;
1622}
1623
1624
1625wxString FormatTrimmedDecimal( double aValue, int aPrecision )
1626{
1627 wxString str = wxString::FromCDouble( aValue, aPrecision );
1628 int dot = str.Find( '.' );
1629
1630 // Keep one zero after the last significant digit and never trim the integer part
1631 while( dot != wxNOT_FOUND && (int) str.length() - dot > 2 && str.EndsWith( wxT( "00" ) ) )
1632 str.RemoveLast();
1633
1634 // Rounded zero has no meaningful sign
1635 if( str.StartsWith( wxS( "-" ) )
1636 && str.find_first_not_of( wxS( "0." ), 1 ) == wxString::npos )
1637 {
1638 str.Remove( 0, 1 );
1639 }
1640
1641 return str;
1642}
1643
1644
1645std::string UIDouble2Str( double aValue )
1646{
1647 char buf[50];
1648 int len;
1649
1650 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1651 {
1652 // For these small values, %f works fine,
1653 // and %g gives an exponent
1654 len = snprintf( buf, sizeof( buf ), "%.16f", aValue );
1655
1656 while( --len > 0 && buf[len] == '0' )
1657 buf[len] = '\0';
1658
1659 if( buf[len] == '.' || buf[len] == ',' )
1660 buf[len] = '\0';
1661 else
1662 ++len;
1663 }
1664 else
1665 {
1666 // For these values, %g works fine, and sometimes %f
1667 // gives a bad value (try aValue = 1.222222222222, with %.16f format!)
1668 len = snprintf( buf, sizeof( buf ), "%.10g", aValue );
1669 }
1670
1671 return std::string( buf, len );
1672}
1673
1674
1675wxString From_UTF8( const char* cstring )
1676{
1677 // Convert an expected UTF8 encoded C string to a wxString
1678 wxString line = wxString::FromUTF8( cstring );
1679
1680 if( line.IsEmpty() ) // happens when cstring is not a valid UTF8 sequence
1681 {
1682 line = wxConvCurrent->cMB2WC( cstring ); // try to use locale conversion
1683
1684 if( line.IsEmpty() )
1685 line = wxString::From8BitData( cstring ); // try to use native string
1686 }
1687
1688 return line;
1689}
1690
1691
1692wxString From_UTF8( const std::string& aString )
1693{
1694 // Convert an expected UTF8 encoded std::string to a wxString
1695 wxString line = wxString::FromUTF8( aString );
1696
1697 if( line.IsEmpty() ) // happens when aString is not a valid UTF8 sequence
1698 {
1699 line = wxConvCurrent->cMB2WC( aString.c_str() ); // try to use locale conversion
1700
1701 if( line.IsEmpty() )
1702 line = wxString::From8BitData( aString.c_str() ); // try to use native string
1703 }
1704
1705 return line;
1706}
1707
1708
1709wxString NormalizeFileUri( const wxString& aFileUri )
1710{
1711 wxString uriPathAndFileName;
1712
1713 wxCHECK( aFileUri.StartsWith( wxS( "file://" ), &uriPathAndFileName ), aFileUri );
1714
1715 wxString tmp = uriPathAndFileName;
1716 wxString retv = wxS( "file://" );
1717
1718 tmp.Replace( wxS( "\\" ), wxS( "/" ) );
1719 tmp.Replace( wxS( ":" ), wxS( "" ) );
1720
1721 if( !tmp.IsEmpty() && tmp[0] != '/' )
1722 tmp = wxS( "/" ) + tmp;
1723
1724 retv += tmp;
1725
1726 return retv;
1727}
1728
1729
1730wxString ConvertPathToFileUri( const wxString& aPath, const PROJECT* aProject )
1731{
1732 if( aPath.IsEmpty() || aPath == wxS( "~" ) )
1733 return aPath;
1734
1735 bool looksLikePath = aPath.StartsWith( wxS( "/" ) ) || aPath.StartsWith( wxS( "${" ) )
1736 || aPath.StartsWith( wxS( "./" ) ) || aPath.StartsWith( wxS( "../" ) );
1737
1738#ifdef __WINDOWS__
1739 looksLikePath = looksLikePath || ( aPath.Length() >= 2 && wxIsalpha( aPath[0] ) && aPath[1] == ':' )
1740 || aPath.StartsWith( wxS( "\\\\" ) ) || aPath.StartsWith( wxS( ".\\" ) )
1741 || aPath.StartsWith( wxS( "..\\" ) );
1742#endif
1743
1744 if( !looksLikePath )
1745 {
1746 wxURI uri( aPath );
1747
1748 if( uri.HasScheme() )
1749 return aPath;
1750
1751 return aPath; // Not a path, return unchanged
1752 }
1753
1754 // Resolve env vars
1755 wxString resolved = aPath;
1756
1757 if( aProject )
1758 resolved = ResolveUriByEnvVars( aPath, aProject );
1759
1760 wxFileName fname( resolved );
1761
1762 if( !fname.IsAbsolute() && aProject && !aProject->GetProjectPath().IsEmpty() )
1763 {
1764 fname.MakeAbsolute( aProject->GetProjectPath() );
1765 resolved = fname.GetFullPath();
1766 }
1767
1768 // Only convert if the file actually exists
1769 bool isUNC = resolved.StartsWith( wxS( "\\\\" ) );
1770
1771 if( !isUNC && !wxFileExists( resolved ) && !wxDirExists( resolved ) )
1772 return aPath;
1773
1774 if( aPath.StartsWith( wxS( "/" ) ) )
1775 return wxS( "file://" ) + aPath;
1776
1777 if( aPath.StartsWith( wxS( "${" ) ) )
1778 return wxS( "file://" ) + aPath;
1779
1780 if( aPath.StartsWith( wxS( "./" ) ) || aPath.StartsWith( wxS( "../" ) ) )
1781 return wxS( "file://" ) + aPath;
1782
1783#ifdef __WINDOWS__
1784 if( aPath.StartsWith( wxS( "\\\\" ) ) )
1785 {
1786 wxString path = aPath.Mid( 2 );
1787 path.Replace( wxS( "\\" ), wxS( "/" ) );
1788 return wxS( "file://" ) + path;
1789 }
1790
1791 if( aPath.Length() >= 2 && wxIsalpha( aPath[0] ) && aPath[1] == ':' )
1792 {
1793 wxString path = aPath;
1794 path.Replace( wxS( "\\" ), wxS( "/" ) );
1795 return wxS( "file:///" ) + path;
1796 }
1797
1798 if( aPath.StartsWith( wxS( ".\\" ) ) || aPath.StartsWith( wxS( "..\\" ) ) )
1799 {
1800 wxString path = aPath;
1801 path.Replace( wxS( "\\" ), wxS( "/" ) );
1802 return wxS( "file://" ) + path;
1803 }
1804#endif
1805
1806 return aPath;
1807}
1808
1809
1810namespace
1811{
1812 // Characters that carry structural meaning inside stacked pin notation and therefore must be
1813 // backslash-escaped when they appear literally inside an individual pin number.
1814 bool IsStackedPinSpecialChar( wxUniChar aChar )
1815 {
1816 return aChar == '[' || aChar == ']' || aChar == ',' || aChar == '-' || aChar == '\\';
1817 }
1818
1819
1820 // A backslash starts an escape sequence only when it precedes one of the structural characters.
1821 // Any other backslash is a literal character, which keeps legacy notation that happened to use
1822 // an un-escaped backslash (e.g. [A\B,C]) intact.
1823 bool IsEscapeAt( const wxString& aText, size_t aIndex )
1824 {
1825 return aText[aIndex] == '\\' && aIndex + 1 < aText.length()
1826 && IsStackedPinSpecialChar( aText[aIndex + 1] );
1827 }
1828
1829
1830 // Split the inner part of a stacked notation string on commas, honouring backslash escaping so
1831 // that a literal comma in a pin number (written "\,") does not start a new item. The returned
1832 // parts are still escaped; call UnescapeStackedPinItem() to recover the literal pin number.
1833 std::vector<wxString> SplitStackedPinItems( const wxString& aInner )
1834 {
1835 std::vector<wxString> parts;
1836 wxString current;
1837
1838 for( size_t i = 0; i < aInner.length(); ++i )
1839 {
1840 if( IsEscapeAt( aInner, i ) )
1841 {
1842 current << aInner[i] << aInner[i + 1];
1843 ++i;
1844 }
1845 else if( aInner[i] == ',' )
1846 {
1847 parts.push_back( current );
1848 current.clear();
1849 }
1850 else
1851 {
1852 current << aInner[i];
1853 }
1854 }
1855
1856 parts.push_back( current );
1857 return parts;
1858 }
1859
1860
1861 int FindUnescaped( const wxString& aText, wxUniChar aChar )
1862 {
1863 for( size_t i = 0; i < aText.length(); ++i )
1864 {
1865 if( IsEscapeAt( aText, i ) )
1866 ++i;
1867 else if( aText[i] == aChar )
1868 return static_cast<int>( i );
1869 }
1870
1871 return wxNOT_FOUND;
1872 }
1873
1874
1875 // A backslash that does not precede a structural character is a literal and is left untouched.
1876 wxString UnescapeStackedPinItem( const wxString& aItem )
1877 {
1878 wxString out;
1879
1880 for( size_t i = 0; i < aItem.length(); ++i )
1881 {
1882 if( IsEscapeAt( aItem, i ) )
1883 out << aItem[++i];
1884 else
1885 out << aItem[i];
1886 }
1887
1888 return out;
1889 }
1890
1891
1892 // Extract (prefix, numericValue) where numericValue = -1 if no numeric suffix
1893 std::pair<wxString, long> ParseAlphaNumericPin( const wxString& pinNum )
1894 {
1895 wxString prefix;
1896 long numValue = -1;
1897
1898 size_t numStart = pinNum.length();
1899 for( int i = static_cast<int>( pinNum.length() ) - 1; i >= 0; --i )
1900 {
1901 if( !wxIsdigit( pinNum[i] ) )
1902 {
1903 numStart = i + 1;
1904 break;
1905 }
1906 if( i == 0 )
1907 numStart = 0; // all digits
1908 }
1909
1910 if( numStart < pinNum.length() )
1911 {
1912 prefix = pinNum.Left( numStart );
1913 wxString numericPart = pinNum.Mid( numStart );
1914 numericPart.ToLong( &numValue );
1915 }
1916
1917 return { prefix, numValue };
1918 }
1919}
1920
1921wxString EscapeStackedPinItem( const wxString& aPinNumber )
1922{
1923 wxString escaped;
1924
1925 for( wxUniChar ch : aPinNumber )
1926 {
1927 if( IsStackedPinSpecialChar( ch ) )
1928 escaped << '\\';
1929
1930 escaped << ch;
1931 }
1932
1933 return escaped;
1934}
1935
1936
1937std::vector<wxString> SplitStackedPinDisplayItems( const wxString& aInner )
1938{
1939 std::vector<wxString> items;
1940
1941 for( const wxString& part : SplitStackedPinItems( aInner ) )
1942 items.push_back( UnescapeStackedPinItem( part ) );
1943
1944 return items;
1945}
1946
1947
1948std::vector<wxString> ExpandStackedPinNotation( const wxString& aPinName, bool* aValid )
1949{
1950 if( aValid )
1951 *aValid = true;
1952
1953 std::vector<wxString> expanded;
1954
1955 const bool hasOpenBracket = aPinName.Contains( wxT( "[" ) );
1956 const bool hasCloseBracket = aPinName.Contains( wxT( "]" ) );
1957
1958 if( hasOpenBracket || hasCloseBracket )
1959 {
1960 if( !aPinName.StartsWith( wxT( "[" ) ) || !aPinName.EndsWith( wxT( "]" ) ) )
1961 {
1962 if( aValid )
1963 *aValid = false;
1964 expanded.push_back( aPinName );
1965 return expanded;
1966 }
1967 }
1968
1969 if( !aPinName.StartsWith( wxT( "[" ) ) || !aPinName.EndsWith( wxT( "]" ) ) )
1970 {
1971 expanded.push_back( aPinName );
1972 return expanded;
1973 }
1974
1975 const wxString inner = aPinName.Mid( 1, aPinName.Length() - 2 );
1976
1977 for( wxString part : SplitStackedPinItems( inner ) )
1978 {
1979 part.Trim( true ).Trim( false );
1980
1981 if( part.empty() )
1982 continue;
1983
1984 // A range (e.g. A1-A4) is only recognized on an unescaped dash; an escaped dash is a
1985 // literal character inside a single pin number.
1986 int dashPos = FindUnescaped( part, '-' );
1987 if( dashPos != wxNOT_FOUND )
1988 {
1989 wxString startTxt = UnescapeStackedPinItem( part.Left( dashPos ) );
1990 wxString endTxt = UnescapeStackedPinItem( part.Mid( dashPos + 1 ) );
1991 startTxt.Trim( true ).Trim( false );
1992 endTxt.Trim( true ).Trim( false );
1993
1994 auto [startPrefix, startVal] = ParseAlphaNumericPin( startTxt );
1995 auto [endPrefix, endVal] = ParseAlphaNumericPin( endTxt );
1996
1997 if( startPrefix != endPrefix || startVal == -1 || endVal == -1 || startVal > endVal )
1998 {
1999 if( aValid )
2000 *aValid = false;
2001 expanded.clear();
2002 expanded.push_back( aPinName );
2003 return expanded;
2004 }
2005
2006 for( long ii = startVal; ii <= endVal; ++ii )
2007 {
2008 if( startPrefix.IsEmpty() )
2009 expanded.emplace_back( wxString::Format( wxT( "%ld" ), ii ) );
2010 else
2011 expanded.emplace_back( wxString::Format( wxT( "%s%ld" ), startPrefix, ii ) );
2012 }
2013 }
2014 else
2015 {
2016 expanded.push_back( UnescapeStackedPinItem( part ) );
2017 }
2018 }
2019
2020 if( expanded.empty() )
2021 {
2022 expanded.push_back( aPinName );
2023 if( aValid )
2024 *aValid = false;
2025 }
2026
2027 return expanded;
2028}
2029
2030
2031int CountStackedPinNotation( const wxString& aPinName, bool* aValid )
2032{
2033 size_t len = aPinName.length();
2034
2035 // An empty pin number is a single (valid) pin; guard before indexing below.
2036 if( len == 0 )
2037 {
2038 if( aValid )
2039 *aValid = true;
2040
2041 return 1;
2042 }
2043
2044 if( !aValid )
2045 {
2046 // Fastest path when we're not interested in validity
2047 if( len < 3 )
2048 return 1;
2049 }
2050 else
2051 {
2052 *aValid = true;
2053
2054 // Fast path: if no brackets, it's a single pin
2055 const bool hasOpenBracket = aPinName.Contains( wxT( "[" ) );
2056 const bool hasCloseBracket = aPinName.Contains( wxT( "]" ) );
2057
2058 if( hasOpenBracket || hasCloseBracket )
2059 {
2060 if( aPinName[0] != '[' || aPinName[len - 1] != ']' )
2061 {
2062 *aValid = false;
2063 return 1;
2064 }
2065 }
2066 }
2067
2068 if( aPinName[0] != '[' || aPinName[len - 1] != ']' )
2069 return 1;
2070
2071 const wxString inner = aPinName.Mid( 1, aPinName.Length() - 2 );
2072
2073 int count = 0;
2074
2075 for( wxString part : SplitStackedPinItems( inner ) )
2076 {
2077 part.Trim( true ).Trim( false );
2078
2079 if( part.empty() )
2080 continue;
2081
2082 int dashPos = FindUnescaped( part, '-' );
2083 if( dashPos != wxNOT_FOUND )
2084 {
2085 wxString startTxt = UnescapeStackedPinItem( part.Left( dashPos ) );
2086 wxString endTxt = UnescapeStackedPinItem( part.Mid( dashPos + 1 ) );
2087 startTxt.Trim( true ).Trim( false );
2088 endTxt.Trim( true ).Trim( false );
2089
2090 auto [startPrefix, startVal] = ParseAlphaNumericPin( startTxt );
2091 auto [endPrefix, endVal] = ParseAlphaNumericPin( endTxt );
2092
2093 if( startPrefix != endPrefix || startVal == -1 || endVal == -1 || startVal > endVal )
2094 {
2095 if( aValid )
2096 *aValid = false;
2097
2098 return 1;
2099 }
2100
2101 // Count pins in the range
2102 count += static_cast<int>( endVal - startVal + 1 );
2103 }
2104 else
2105 {
2106 // Single pin
2107 ++count;
2108 }
2109 }
2110
2111 if( count == 0 )
2112 {
2113 if( aValid )
2114 *aValid = false;
2115
2116 return 1;
2117 }
2118
2119 return count;
2120}
2121
2122
2124{
2125 return wxString( defaultVariantName );
2126}
2127
2128
2129wxString GetVariantFileToken( const wxString& aVariantName )
2130{
2131 if( aVariantName.IsEmpty() || aVariantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
2132 return wxString();
2133
2134 wxString token = aVariantName;
2135 ReplaceIllegalFileNameChars( token, '_' );
2136 return token;
2137}
2138
2139
2140wxString ExpandVariantOutputPath( const wxString& aPath, const wxString& aVariantToken )
2141{
2142 wxString expanded = aPath;
2143 expanded.Replace( wxS( "${VARIANT}" ), aVariantToken );
2144 return expanded;
2145}
2146
2147
2148int SortVariantNames( const wxString& aLhs, const wxString& aRhs )
2149{
2150 if( ( aLhs == defaultVariantName ) && ( aRhs != defaultVariantName ) )
2151 return -1;
2152
2153 if( ( aLhs != defaultVariantName ) && ( aRhs == defaultVariantName ) )
2154 return 1;
2155
2156 return StrNumCmp( aLhs, aRhs );
2157}
2158
2159
2160wxString ExtractLibraryLoadException( const IO_ERROR& aException )
2161{
2162 wxString err;
2163
2164 // Errors are separated by newlines. We want to keep:
2165 // - Lines starting with "Library '" (library-level errors)
2166 // - Lines containing "Expecting" (file error location)
2167 // And strip:
2168 // - Lines starting with "from " (internal code location info)
2169 wxStringTokenizer tokenizer( aException.What(), wxS( "\n" ), wxTOKEN_STRTOK );
2170#if 0
2171 while( tokenizer.HasMoreTokens() )
2172 {
2173 wxString line = tokenizer.GetNextToken();
2174
2175 // Skip internal code location lines (e.g., "from pcb_io_kicad_sexpr_parser.cpp : ...")
2176 if( line.StartsWith( wxS( "from " ) ) )
2177 continue;
2178
2179 if( line.StartsWith( wxS( "Library '" ) ) || line.Contains( wxS( "Expecting" ) ) )
2180 messages.push_back( KI_ERROR( static_cast<SEVERITY>( aSeverity ), line ) );
2181 }
2182#endif
2183 return err;
2184}
2185
2186
2187bool IsAutoGeneratedNetName( const wxString& aNetName )
2188{
2189 return aNetName.StartsWith( wxS( "unconnected-(" ) ) || aNetName.StartsWith( wxS( "Net-(" ) );
2190}
int index
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
Holds a structured error message.
Definition ki_error.h:38
static bool IsOldSchoolDecimalSeparator(wxUniChar ch, double *siScaler)
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
const wxString ResolveUriByEnvVars(const wxString &aUri, const PROJECT *aProject)
Replace any environment and/or text variables in URIs.
Definition common.cpp:790
std::string utf8(const wxString &aText)
This file contains miscellaneous commonly used macros and functions.
std::optional< V > get_opt(const std::map< wxString, V > &aMap, const wxString &aKey)
Definition map_helpers.h:30
CITER next(CITER it)
Definition ptree.cpp:120
SEVERITY
const int scale
int StrNumCmp(const wxString &aString1, const wxString &aString2, CMP_T aCaseSensitivity)
Compare two strings with alphanumerical content.
static wxUint32 codePointAt(const wxString &aText, size_t aPos, size_t &aUnits)
The code point at aPos in aText, joining a UTF-16 surrogate pair. aUnits receives how many units it s...
wxString RemoveHTMLTags(const wxString &aInput)
Removes HTML tags from a string.
wxString EscapeHTML(const wxString &aString)
Return a new wxString escaped for embedding in HTML.
bool WildCompareString(const wxString &pattern, const wxString &string_to_tst, bool case_sensitive)
Compare a string against wild card (* and ?) pattern using the usual rules.
wxString GetDefaultVariantName()
std::vector< wxString > ExpandStackedPinNotation(const wxString &aPinName, bool *aValid)
Expand stacked pin notation like [1,2,3], [1-4], [A1-A4], or [AA1-AA3,AB4,CD12-CD14] into individual ...
wxString ConvertToNewOverbarNotation(const wxString &aOldStr)
Convert the old ~...~ overbar notation to the new ~{...} one.
wxString ExpandVariantOutputPath(const wxString &aPath, const wxString &aVariantToken)
int GetTrailingInt(const wxString &aStr)
Gets the trailing int, if any, from a string.
wxString UnescapeString(const wxString &aSource)
wxString LinkifyHTML(wxString aStr)
Wraps links in HTML tags.
bool convertSeparators(wxString *value)
wxString GetIllegalFileNameWxChars()
wxString From_UTF8(const char *cstring)
int SortVariantNames(const wxString &aLhs, const wxString &aRhs)
bool ConvertSmartQuotesAndDashes(wxString *aString)
Convert curly quotes and em/en dashes to straight quotes and dashes.
static const wxChar defaultVariantName[]
wxString ConvertPathToFileUri(const wxString &aPath, const PROJECT *aProject)
Convert a file path to a file:// URI.
bool IsAutoGeneratedNetName(const wxString &aNetName)
Recognize the reserved prefixes used for generated pin-net names.
void wxStringSplit(const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
Split aString to a string list separated at aSplitter.
wxString FormatTrimmedDecimal(double aValue, int aPrecision)
Format a value to aPrecision decimal digits and strip trailing zeros, keeping one digit after the dec...
bool QuacksLikeADuck(const wxString &aStr, double *aValue)
int ReadDelimitedText(wxString *aDest, const char *aSource)
Copy bytes from aSource delimited string segment to aDest wxString.
wxString TitleCaps(const wxString &aString)
Capitalize the first letter in each word.
std::vector< wxString > SplitGraphemeClusters(const wxString &aText)
Split text into the units a reader sees as one character.
std::string UIDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 We want to avoid scientific ...
static constexpr std::string_view illegalFileNameChars
Illegal file name characters used to ensure file names will be valid on all supported platforms.
std::vector< wxString > SplitStackedPinDisplayItems(const wxString &aInner)
Split the inner part of a stacked notation string (the text between the brackets) into its individual...
static bool isVirama(wxUint32 aCodePoint)
std::string FormatDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 This function is intended in...
bool ReplaceIllegalFileNameChars(std::string &aName, int aReplaceChar)
Checks aName for illegal file name characters.
wxString EscapeStackedPinItem(const wxString &aPinNumber)
Escape the characters that carry structural meaning inside stacked pin notation ('[',...
int PrintableCharCount(const wxString &aString)
Return the number of printable (ie: non-formatting) chars.
std::string EscapedUTF8(const wxString &aString)
Return an 8 bit UTF8 string given aString in Unicode form.
char * GetLine(FILE *File, char *Line, int *LineNum, int SizeLine)
Read one line line from aFile.
bool ApplyModifier(double &value, const wxString &aString)
wxString GetVariantFileToken(const wxString &aVariantName)
wxString InitialCaps(const wxString &aString)
Capitalize only the first word.
wxString NormalizeFileUri(const wxString &aFileUri)
Normalize file path aFileUri to URI convention.
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
wxString GetISO8601CurrentDateTime()
int ValueStringCompare(const wxString &strFWord, const wxString &strSWord)
Compare strings like the strcmp function but handle numbers and modifiers within the string text corr...
static bool extendsCluster(wxUint32 aCodePoint)
True for a code point drawn as part of the one before it.
int SplitString(const wxString &strToSplit, wxString *strBeginning, wxString *strDigits, wxString *strEnd)
Break a string into three parts: he alphabetic preamble, the numeric part, and any alphabetic ending.
bool IsFullFileNameValid(const wxString &aFullFilename)
Checks if a full filename is valid, i.e.
void StripTrailingZeros(wxString &aStringValue, unsigned aTrailingZeroAllowed)
Remove trailing zeros from a string containing a converted float number.
int CountStackedPinNotation(const wxString &aPinName, bool *aValid)
Count the number of pins represented by stacked pin notation.
char * StrPurge(char *text)
Remove leading and training spaces, tabs and end of line chars in text.
bool NoPrintableChars(const wxString &aString)
Return true if the string is empty or contains only whitespace.
wxString ExtractLibraryLoadException(const IO_ERROR &aException)
Parse library load error messages, extracting user-facing information while stripping internal code l...
wxString UnescapeHTML(const wxString &aString)
Return a new wxString unescaped from HTML format.
bool IsURL(wxString aStr)
Performs a URL sniff-test on a string.
CMP_T
@ IGNORE_CASE
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
ESCAPE_CONTEXT
Escape/Unescape routines to safely encode reserved-characters in various contexts.
@ CTX_FILENAME
@ CTX_QUOTED_STR
@ CTX_LINE
@ CTX_NO_SPACE
@ CTX_LIBID
@ CTX_NETNAME
@ CTX_CSV
@ CTX_IPC
@ CTX_REGEX
@ CTX_LEGACY_LIBID
@ CTX_JS_STR
std::string path
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.