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, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
28
29#include <clocale>
30#include <cmath>
31#include <map>
32#include <core/map_helpers.h>
33#include <fmt/core.h>
34#include <macros.h>
35#include <string_utils.h>
36#include <widgets/kistatusbar.h>
37#include <wx_filename.h>
38#include <fmt/chrono.h>
39#include <wx/log.h>
40#include <wx/regex.h>
41#include <wx/tokenzr.h>
43#include "locale_io.h"
44#include <wx/event.h>
45
46
52static constexpr std::string_view illegalFileNameChars = "\\/:\"<>|*?";
53
54static const wxChar defaultVariantName[] = wxT( "< Default >" );
55
56
57// Checks if a full filename is valid, i.e. does not contains illegal chars
58bool IsFullFileNameValid( const wxString& aFullFilename )
59{
60
61 // Test for forbidden chars in aFullFilename.
62 // '\'and '/' are allowed here because aFullFilename can be a full path, and
63 // ':' is allowed on Windows as second char in string.
64 // So remove allowed separators from string to test
65 wxString filtered_fullpath = aFullFilename;
66
67#ifdef __WINDOWS__
68 // On MSW, the list returned by wxFileName::GetForbiddenChars() contains separators
69 // '\'and '/'
70 filtered_fullpath.Replace( "/", "_" );
71 filtered_fullpath.Replace( "\\", "_" );
72
73 // A disk identifier is allowed, and therefore remove its separator
74 if( filtered_fullpath.Length() > 1 && filtered_fullpath[1] == ':' )
75 filtered_fullpath[1] = ' ';
76#endif
77
78 if( wxString::npos != filtered_fullpath.find_first_of( wxFileName::GetForbiddenChars() ) )
79 return false;
80
81 return true;
82}
83
84
85wxString ConvertToNewOverbarNotation( const wxString& aOldStr )
86{
87 wxString newStr;
88 bool inOverbar = false;
89
90 // Don't get tripped up by the legacy empty-string token.
91 if( aOldStr == wxT( "~" ) )
92 return aOldStr;
93
94 newStr.reserve( aOldStr.length() );
95
96 for( wxString::const_iterator chIt = aOldStr.begin(); chIt != aOldStr.end(); ++chIt )
97 {
98 if( *chIt == '~' )
99 {
100 wxString::const_iterator lookahead = chIt + 1;
101
102 if( lookahead != aOldStr.end() && *lookahead == '~' )
103 {
104 if( ++lookahead != aOldStr.end() && *lookahead == '{' )
105 {
106 // This way the subsequent opening curly brace will not start an
107 // overbar.
108 newStr << wxT( "~~{}" );
109 continue;
110 }
111
112 // Two subsequent tildes mean a tilde.
113 newStr << wxT( "~" );
114 ++chIt;
115 continue;
116 }
117 else if( lookahead != aOldStr.end() && *lookahead == '{' )
118 {
119 // Could mean the user wants "{" with an overbar, but more likely this
120 // is a case of double notation conversion. Bail out.
121 return aOldStr;
122 }
123 else
124 {
125 if( inOverbar )
126 {
127 newStr << wxT( "}" );
128 inOverbar = false;
129 }
130 else
131 {
132 newStr << wxT( "~{" );
133 inOverbar = true;
134 }
135
136 continue;
137 }
138 }
139 else if( ( *chIt == ' ' || *chIt == '}' || *chIt == ')' ) && inOverbar )
140 {
141 // Spaces were used to terminate overbar as well
142 newStr << wxT( "}" );
143 inOverbar = false;
144 }
145
146 newStr << *chIt;
147 }
148
149 // Explicitly end the overbar even if there was no terminating '~' in the aOldStr.
150 if( inOverbar )
151 newStr << wxT( "}" );
152
153 return newStr;
154}
155
156
157bool ConvertSmartQuotesAndDashes( wxString* aString )
158{
159 bool retVal = false;
160
161 for( wxString::iterator ii = aString->begin(); ii != aString->end(); ++ii )
162 {
163 if( *ii == L'\u00B4' || *ii == L'\u2018' || *ii == L'\u2019' )
164 {
165 *ii = '\'';
166 retVal = true;
167 }
168 if( *ii == L'\u201C' || *ii == L'\u201D' )
169 {
170 *ii = '"';
171 retVal = true;
172 }
173 if( *ii == L'\u2013' || *ii == L'\u2014' )
174 {
175 *ii = '-';
176 retVal = true;
177 }
178 }
179
180 return retVal;
181}
182
183
184wxString EscapeString( const wxString& aSource, ESCAPE_CONTEXT aContext )
185{
186 wxString converted;
187 std::vector<bool> braceStack; // true == formatting construct
188
189 converted.reserve( aSource.length() );
190
191 for( wxUniChar c: aSource )
192 {
193 if( aContext == CTX_NETNAME )
194 {
195 if( c == '/' )
196 converted += wxT( "{slash}" );
197 else if( c == '\n' || c == '\r' )
198 converted += wxEmptyString; // drop
199 else
200 converted += c;
201 }
202 else if( aContext == CTX_LIBID || aContext == CTX_LEGACY_LIBID )
203 {
204 // We no longer escape '/' in LIB_IDs, but we used to
205 if( c == '/' && aContext == CTX_LEGACY_LIBID )
206 converted += wxT( "{slash}" );
207 else if( c == '\\' )
208 converted += wxT( "{backslash}" );
209 else if( c == '<' )
210 converted += wxT( "{lt}" );
211 else if( c == '>' )
212 converted += wxT( "{gt}" );
213 else if( c == ':' )
214 converted += wxT( "{colon}" );
215 else if( c == '\"' )
216 converted += wxT( "{dblquote}" );
217 else if( c == '\n' || c == '\r' )
218 converted += wxEmptyString; // drop
219 else
220 converted += c;
221 }
222 else if( aContext == CTX_IPC )
223 {
224 if( c == '/' )
225 converted += wxT( "{slash}" );
226 else if( c == ',' )
227 converted += wxT( "{comma}" );
228 else if( c == '\"' )
229 converted += wxT( "{dblquote}" );
230 else
231 converted += c;
232 }
233 else if( aContext == CTX_QUOTED_STR )
234 {
235 if( c == '\"' )
236 converted += wxT( "{dblquote}" );
237 else
238 converted += c;
239 }
240 else if( aContext == CTX_JS_STR )
241 {
242 if( c >= 0x7F || c == '\'' || c == '\\' || c == '(' || c == ')' )
243 {
244 unsigned int code = c;
245 char buffer[16];
246 snprintf( buffer, sizeof(buffer), "\\u%4.4X", code );
247 converted += buffer;
248 }
249 else
250 {
251 converted += c;
252 }
253 }
254 else if( aContext == CTX_LINE )
255 {
256 if( c == '\n' || c == '\r' )
257 converted += wxT( "{return}" );
258 else
259 converted += c;
260 }
261 else if( aContext == CTX_FILENAME )
262 {
263 if( c == '/' )
264 converted += wxT( "{slash}" );
265 else if( c == '\\' )
266 converted += wxT( "{backslash}" );
267 else if( c == '\"' )
268 converted += wxT( "{dblquote}" );
269 else if( c == '<' )
270 converted += wxT( "{lt}" );
271 else if( c == '>' )
272 converted += wxT( "{gt}" );
273 else if( c == '|' )
274 converted += wxT( "{bar}" );
275 else if( c == ':' )
276 converted += wxT( "{colon}" );
277 else if( c == '\t' )
278 converted += wxT( "{tab}" );
279 else if( c == '\n' || c == '\r' )
280 converted += wxT( "{return}" );
281 else
282 converted += c;
283 }
284 else if( aContext == CTX_NO_SPACE )
285 {
286 if( c == ' ' )
287 converted += wxT( "{space}" );
288 else
289 converted += c;
290 }
291 else if( aContext == CTX_CSV )
292 {
293 if( c == ',' )
294 converted += wxT( "{comma}" );
295 else if( c == '\n' || c == '\r' )
296 converted += wxT( "{return}" );
297 else
298 converted += c;
299 }
300 else
301 {
302 converted += c;
303 }
304 }
305
306 return converted;
307}
308
309
310wxString UnescapeString( const wxString& aSource )
311{
312 size_t sourceLen = aSource.length();
313
314 // smallest escape string is three characters, shortcut everything else
315 if( sourceLen <= 2 )
316 {
317 return aSource;
318 }
319
320 wxString newbuf;
321 newbuf.reserve( sourceLen );
322
323 wxUniChar prev = 0;
324 wxUniChar ch = 0;
325
326 for( size_t i = 0; i < sourceLen; ++i )
327 {
328 prev = ch;
329 ch = aSource[i];
330
331 if( ch == '{' )
332 {
333 wxString token;
334 int depth = 1;
335 bool terminated = false;
336
337 for( i = i + 1; i < sourceLen; ++i )
338 {
339 ch = aSource[i];
340
341 if( ch == '{' )
342 depth++;
343 else if( ch == '}' )
344 depth--;
345
346 if( depth <= 0 )
347 {
348 terminated = true;
349 break;
350 }
351 else
352 {
353 token << ch;
354 }
355 }
356
357 if( !terminated )
358 {
359 newbuf << wxT( "{" ) << UnescapeString( token );
360 }
361 else if( prev == '$' || prev == '~' || prev == '^' || prev == '_' )
362 {
363 newbuf << wxT( "{" ) << UnescapeString( token ) << wxT( "}" );
364 }
365 else if( token == wxT( "dblquote" ) ) newbuf << wxT( "\"" );
366 else if( token == wxT( "quote" ) ) newbuf << wxT( "'" );
367 else if( token == wxT( "lt" ) ) newbuf << wxT( "<" );
368 else if( token == wxT( "gt" ) ) newbuf << wxT( ">" );
369 else if( token == wxT( "backslash" ) ) newbuf << wxT( "\\" );
370 else if( token == wxT( "slash" ) ) newbuf << wxT( "/" );
371 else if( token == wxT( "bar" ) ) newbuf << wxT( "|" );
372 else if( token == wxT( "comma" ) ) newbuf << wxT( "," );
373 else if( token == wxT( "colon" ) ) newbuf << wxT( ":" );
374 else if( token == wxT( "space" ) ) newbuf << wxT( " " );
375 else if( token == wxT( "dollar" ) ) newbuf << wxT( "$" );
376 else if( token == wxT( "tab" ) ) newbuf << wxT( "\t" );
377 else if( token == wxT( "return" ) ) newbuf << wxT( "\n" );
378 else if( token == wxT( "brace" ) ) newbuf << wxT( "{" );
379 else
380 {
381 newbuf << wxT( "{" ) << UnescapeString( token ) << wxT( "}" );
382 }
383 }
384 else
385 {
386 newbuf << ch;
387 }
388 }
389
390 return newbuf;
391}
392
393
394wxString TitleCaps( const wxString& aString )
395{
396 wxArrayString words;
397 wxString result;
398
399 wxStringSplit( aString, words, ' ' );
400
401 result.reserve( aString.length() );
402
403 for( const wxString& word : words )
404 {
405 if( !result.IsEmpty() )
406 result += wxT( " " );
407
408 result += word.Capitalize();
409 }
410
411 return result;
412}
413
414
415wxString InitialCaps( const wxString& aString )
416{
417 wxArrayString words;
418 wxString result;
419
420 wxStringSplit( aString, words, ' ' );
421
422 result.reserve( aString.length() );
423
424 for( const wxString& word : words )
425 {
426 if( result.IsEmpty() )
427 result += word.Capitalize();
428 else
429 result += wxT( " " ) + word.Lower();
430 }
431
432 return result;
433}
434
435
436int ReadDelimitedText( wxString* aDest, const char* aSource )
437{
438 std::string utf8; // utf8 but without escapes and quotes.
439 bool inside = false;
440 const char* start = aSource;
441 char cc;
442
443 while( (cc = *aSource++) != 0 )
444 {
445 if( cc == '"' )
446 {
447 if( inside )
448 break; // 2nd double quote is end of delimited text
449
450 inside = true; // first delimiter found, make note, do not copy
451 }
452
453 else if( inside )
454 {
455 if( cc == '\\' )
456 {
457 cc = *aSource++;
458
459 if( !cc )
460 break;
461
462 // do no copy the escape byte if it is followed by \ or "
463 if( cc != '"' && cc != '\\' )
464 utf8 += '\\';
465
466 utf8 += cc;
467 }
468 else
469 {
470 utf8 += cc;
471 }
472 }
473 }
474
475 *aDest = From_UTF8( utf8.c_str() );
476
477 return aSource - start;
478}
479
480
481int ReadDelimitedText( char* aDest, const char* aSource, int aDestSize )
482{
483 if( aDestSize <= 0 )
484 return 0;
485
486 bool inside = false;
487 const char* start = aSource;
488 char* limit = aDest + aDestSize - 1;
489 char cc;
490
491 while( ( cc = *aSource++ ) != 0 && aDest < limit )
492 {
493 if( cc == '"' )
494 {
495 if( inside )
496 break; // 2nd double quote is end of delimited text
497
498 inside = true; // first delimiter found, make note, do not copy
499 }
500 else if( inside )
501 {
502 if( cc == '\\' )
503 {
504 cc = *aSource++;
505
506 if( !cc )
507 break;
508
509 // do no copy the escape byte if it is followed by \ or "
510 if( cc != '"' && cc != '\\' )
511 *aDest++ = '\\';
512
513 if( aDest < limit )
514 *aDest++ = cc;
515 }
516 else
517 {
518 *aDest++ = cc;
519 }
520 }
521 }
522
523 *aDest = 0;
524
525 return aSource - start;
526}
527
528
529std::string EscapedUTF8( const wxString& aString )
530{
531 wxString str = aString;
532
533 // No new-lines allowed in quoted strings
534 str.Replace( wxT( "\r\n" ), wxT( "\r" ) );
535 str.Replace( wxT( "\n" ), wxT( "\r" ) );
536
537 std::string utf8 = TO_UTF8( aString );
538
539 std::string ret;
540
541 ret.reserve( utf8.length() + 2 );
542
543 ret += '"';
544
545 for( std::string::const_iterator it = utf8.begin(); it!=utf8.end(); ++it )
546 {
547 // this escaping strategy is designed to be compatible with ReadDelimitedText():
548 if( *it == '"' )
549 {
550 ret += '\\';
551 ret += '"';
552 }
553 else if( *it == '\\' )
554 {
555 ret += '\\'; // double it up
556 ret += '\\';
557 }
558 else
559 {
560 ret += *it;
561 }
562 }
563
564 ret += '"';
565
566 return ret;
567}
568
569
570wxString EscapeHTML( const wxString& aString )
571{
572 wxString converted;
573
574 converted.reserve( aString.length() );
575
576 for( wxUniChar c : aString )
577 {
578 if( c == '\"' )
579 converted += wxT( "&quot;" );
580 else if( c == '\'' )
581 converted += wxT( "&apos;" );
582 else if( c == '&' )
583 converted += wxT( "&amp;" );
584 else if( c == '<' )
585 converted += wxT( "&lt;" );
586 else if( c == '>' )
587 converted += wxT( "&gt;" );
588 else
589 converted += c;
590 }
591
592 return converted;
593}
594
595
596wxString UnescapeHTML( const wxString& aString )
597{
598 // clang-format off
599 static const std::map<wxString, wxString> c_replacements = {
600 { wxS( "quot" ), wxS( "\"" ) },
601 { wxS( "apos" ), wxS( "'" ) },
602 { wxS( "amp" ), wxS( "&" ) },
603 { wxS( "lt" ), wxS( "<" ) },
604 { wxS( "gt" ), wxS( ">" ) }
605 };
606 // clang-format on
607
608 // Construct regex
609 wxString regexStr = "&(#(\\d*)|#x([a-zA-Z0-9]{4})";
610
611 for( auto& [key, value] : c_replacements )
612 regexStr << '|' << key;
613
614 regexStr << ");";
615
616 wxRegEx regex( regexStr );
617
618 // Process matches
619 size_t start = 0;
620 size_t len = 0;
621
622 wxString result;
623 wxString str = aString;
624
625 while( regex.Matches( str ) )
626 {
627 std::vector<wxString> matches;
628 regex.GetMatch( &start, &len );
629
630 result << str.Left( start );
631
632 wxString code = regex.GetMatch( str, 1 );
633 wxString codeDec = regex.GetMatch( str, 2 );
634 wxString codeHex = regex.GetMatch( str, 3 );
635
636 if( !codeDec.IsEmpty() || !codeHex.IsEmpty() )
637 {
638 unsigned long codeVal = 0;
639
640 if( !codeDec.IsEmpty() )
641 codeDec.ToCULong( &codeVal );
642 else if( !codeHex.IsEmpty() )
643 codeHex.ToCULong( &codeVal, 16 );
644
645 if( codeVal != 0 )
646 result << wxUniChar( codeVal );
647 }
648 else if( auto val = get_opt( c_replacements, code ) )
649 {
650 result << *val;
651 }
652
653 str = str.Mid( start + len );
654 }
655
656 result << str;
657
658 return result;
659}
660
661
662wxString RemoveHTMLTags( const wxString& aInput )
663{
664 wxString str = aInput;
665 wxRegEx( wxS( "<[^>]*>" ) ).ReplaceAll( &str, wxEmptyString );
666
667 return str;
668}
669
670
671wxString LinkifyHTML( wxString aStr )
672{
673 static wxRegEx regex( wxS( "\\b(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\(\\)\\s\u00b6])" ),
674 wxRE_ICASE );
675
676 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
677
678 return aStr;
679}
680
681
682bool IsURL( wxString aStr )
683{
684 static wxRegEx regex( wxS( "(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\s\u00b6])" ),
685 wxRE_ICASE );
686
687 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
688
689 return regex.Matches( aStr );
690}
691
692
693bool NoPrintableChars( const wxString& aString )
694{
695 wxString tmp = aString;
696
697 return tmp.Trim( true ).Trim( false ).IsEmpty();
698}
699
700
701int PrintableCharCount( const wxString& aString )
702{
703 int char_count = 0;
704 int overbarDepth = -1;
705 int superSubDepth = -1;
706 int braceNesting = 0;
707
708 for( auto chIt = aString.begin(), end = aString.end(); chIt < end; ++chIt )
709 {
710 if( *chIt == '\t' )
711 {
712 // We don't format tabs in bitmap text (where this is currently used), so just
713 // drop them from the count.
714 continue;
715 }
716 else if( *chIt == '^' && superSubDepth == -1 )
717 {
718 auto lookahead = chIt;
719
720 if( ++lookahead != end && *lookahead == '{' )
721 {
722 chIt = lookahead;
723 superSubDepth = braceNesting;
724 braceNesting++;
725 continue;
726 }
727 }
728 else if( *chIt == '_' && superSubDepth == -1 )
729 {
730 auto lookahead = chIt;
731
732 if( ++lookahead != end && *lookahead == '{' )
733 {
734 chIt = lookahead;
735 superSubDepth = braceNesting;
736 braceNesting++;
737 continue;
738 }
739 }
740 else if( *chIt == '~' && overbarDepth == -1 )
741 {
742 auto lookahead = chIt;
743
744 if( ++lookahead != end && *lookahead == '{' )
745 {
746 chIt = lookahead;
747 overbarDepth = braceNesting;
748 braceNesting++;
749 continue;
750 }
751 }
752 else if( *chIt == '{' )
753 {
754 braceNesting++;
755 }
756 else if( *chIt == '}' )
757 {
758 if( braceNesting > 0 )
759 braceNesting--;
760
761 if( braceNesting == superSubDepth )
762 {
763 superSubDepth = -1;
764 continue;
765 }
766
767 if( braceNesting == overbarDepth )
768 {
769 overbarDepth = -1;
770 continue;
771 }
772 }
773
774 char_count++;
775 }
776
777 return char_count;
778}
779
780
781char* StrPurge( char* text )
782{
783 static const char whitespace[] = " \t\n\r\f\v";
784
785 if( text )
786 {
787 while( *text && strchr( whitespace, *text ) )
788 ++text;
789
790 char* cp = text + strlen( text ) - 1;
791
792 while( cp >= text && strchr( whitespace, *cp ) )
793 *cp-- = '\0';
794 }
795
796 return text;
797}
798
799
800char* GetLine( FILE* File, char* Line, int* LineNum, int SizeLine )
801{
802 do {
803 if( fgets( Line, SizeLine, File ) == nullptr )
804 return nullptr;
805
806 if( LineNum )
807 *LineNum += 1;
808
809 } while( Line[0] == '#' || Line[0] == '\n' || Line[0] == '\r' || Line[0] == 0 );
810
811 strtok( Line, "\n\r" );
812 return Line;
813}
814
815
817{
818 return wxDateTime::Now().FormatISOCombined( 'T' );
819}
820
821
822int StrNumCmp( const wxString& aString1, const wxString& aString2, bool aIgnoreCase )
823{
824 int nb1 = 0, nb2 = 0;
825
826 auto str1 = aString1.begin();
827 auto str2 = aString2.begin();
828
829 while( str1 != aString1.end() && str2 != aString2.end() )
830 {
831 wxUniChar c1 = *str1;
832 wxUniChar c2 = *str2;
833
834 if( wxIsdigit( c1 ) && wxIsdigit( c2 ) ) // Both characters are digits, do numeric compare.
835 {
836 nb1 = 0;
837 nb2 = 0;
838
839 do
840 {
841 c1 = *str1;
842 nb1 = nb1 * 10 + (int) c1 - '0';
843 ++str1;
844 } while( str1 != aString1.end() && wxIsdigit( *str1 ) );
845
846 do
847 {
848 c2 = *str2;
849 nb2 = nb2 * 10 + (int) c2 - '0';
850 ++str2;
851 } while( str2 != aString2.end() && wxIsdigit( *str2 ) );
852
853 if( nb1 < nb2 )
854 return -1;
855
856 if( nb1 > nb2 )
857 return 1;
858
859 c1 = ( str1 != aString1.end() ) ? *str1 : wxUniChar( 0 );
860 c2 = ( str2 != aString2.end() ) ? *str2 : wxUniChar( 0 );
861 }
862
863 // Any numerical comparisons to here are identical.
864 if( aIgnoreCase )
865 {
866 if( c1 != c2 )
867 {
868 wxUniChar uc1 = wxToupper( c1 );
869 wxUniChar uc2 = wxToupper( c2 );
870
871 if( uc1 != uc2 )
872 return uc1 < uc2 ? -1 : 1;
873 }
874 }
875 else
876 {
877 if( c1 < c2 )
878 return -1;
879
880 if( c1 > c2 )
881 return 1;
882 }
883
884 if( str1 != aString1.end() )
885 ++str1;
886
887 if( str2 != aString2.end() )
888 ++str2;
889 }
890
891 if( str1 == aString1.end() && str2 != aString2.end() )
892 {
893 return -1; // Identical to here but aString1 is longer.
894 }
895 else if( str1 != aString1.end() && str2 == aString2.end() )
896 {
897 return 1; // Identical to here but aString2 is longer.
898 }
899
900 return 0;
901}
902
903
904bool WildCompareString( const wxString& pattern, const wxString& string_to_tst,
905 bool case_sensitive )
906{
907 const wxChar* cp = nullptr;
908 const wxChar* mp = nullptr;
909 const wxChar* wild = nullptr;
910 const wxChar* str = nullptr;
911 wxString _pattern, _string_to_tst;
912
913 if( case_sensitive )
914 {
915 wild = pattern.GetData();
916 str = string_to_tst.GetData();
917 }
918 else
919 {
920 _pattern = pattern;
921 _pattern.MakeUpper();
922 _string_to_tst = string_to_tst;
923 _string_to_tst.MakeUpper();
924 wild = _pattern.GetData();
925 str = _string_to_tst.GetData();
926 }
927
928 while( ( *str ) && ( *wild != '*' ) )
929 {
930 if( ( *wild != *str ) && ( *wild != '?' ) )
931 return false;
932
933 wild++;
934 str++;
935 }
936
937 while( *str )
938 {
939 if( *wild == '*' )
940 {
941 if( !*++wild )
942 return true;
943
944 mp = wild;
945 cp = str + 1;
946 }
947 else if( ( *wild == *str ) || ( *wild == '?' ) )
948 {
949 wild++;
950 str++;
951 }
952 else
953 {
954 wild = mp;
955 str = cp++;
956 }
957 }
958
959 while( *wild == '*' )
960 {
961 wild++;
962 }
963
964 return !*wild;
965}
966
967
968bool ApplyModifier( double& value, const wxString& aString )
969{
971 static const wxString modifiers( wxT( "afpnuµμmLRFkKMGTPE" ) );
972
973 if( !aString.length() )
974 return false;
975
976 wxChar modifier;
977 wxString units;
978
979 if( modifiers.Find( aString[ 0 ] ) >= 0 )
980 {
981 modifier = aString[ 0 ];
982 units = aString.Mid( 1 ).Trim();
983 }
984 else
985 {
986 modifier = ' ';
987 units = aString.Mid( 0 ).Trim();
988 }
989
990 if( units.length()
991 && !units.IsSameAs( wxT( "F" ), false )
992 && !units.IsSameAs( wxT( "hz" ), false )
993 && !units.IsSameAs( wxT( "W" ), false )
994 && !units.IsSameAs( wxT( "V" ), false )
995 && !units.IsSameAs( wxT( "A" ), false )
996 && !units.IsSameAs( wxT( "H" ), false ) )
997 {
998 return false;
999 }
1000
1001 // Note: most of these are SI, but some (L, R, F) are IEC 60062.
1002 if( modifier == 'a' )
1003 value *= 1.0e-18;
1004 else if( modifier == 'f' )
1005 value *= 1.0e-15;
1006 if( modifier == 'p' )
1007 value *= 1.0e-12;
1008 if( modifier == 'n' )
1009 value *= 1.0e-9;
1010 else if( modifier == 'u' || modifier == wxS( "µ" )[0] || modifier == wxS( "μ" )[0] )
1011 value *= 1.0e-6;
1012 else if( modifier == 'm' || modifier == 'L' )
1013 value *= 1.0e-3;
1014 else if( modifier == 'R' || modifier == 'F' )
1015 ; // unity scalar
1016 else if( modifier == 'k' || modifier == 'K' )
1017 value *= 1.0e3;
1018 else if( modifier == 'M' )
1019 value *= 1.0e6;
1020 else if( modifier == 'G' )
1021 value *= 1.0e9;
1022 else if( modifier == 'T' )
1023 value *= 1.0e12;
1024 else if( modifier == 'P' )
1025 value *= 1.0e15;
1026 else if( modifier == 'E' )
1027 value *= 1.0e18;
1028
1029 return true;
1030}
1031
1032
1033bool convertSeparators( wxString* value )
1034{
1035 // Note: fetching the decimal separator from the current locale isn't a silver bullet because
1036 // it assumes the current computer's locale is the same as the locale the schematic was
1037 // authored in -- something that isn't true, for instance, when sharing designs through
1038 // DIYAudio.com.
1039 //
1040 // Some values are self-describing: multiple instances of a single separator character must be
1041 // thousands separators; a single instance of each character must be a thousands separator
1042 // followed by a decimal separator; etc.
1043 //
1044 // Only when presented with an ambiguous value do we fall back on the current locale.
1045
1046 value->Replace( wxS( " " ), wxEmptyString );
1047
1048 wxChar ambiguousSeparator = '?';
1049 wxChar thousandsSeparator = '?';
1050 bool thousandsSeparatorFound = false;
1051 wxChar decimalSeparator = '?';
1052 bool decimalSeparatorFound = false;
1053 int digits = 0;
1054
1055 for( int ii = (int) value->length() - 1; ii >= 0; --ii )
1056 {
1057 wxChar c = value->GetChar( ii );
1058
1059 if( c >= '0' && c <= '9' )
1060 {
1061 digits += 1;
1062 }
1063 else if( c == '.' || c == ',' )
1064 {
1065 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1066 {
1067 // We've previously found a non-ambiguous separator...
1068
1069 if( c == decimalSeparator )
1070 {
1071 if( thousandsSeparatorFound )
1072 return false; // decimal before thousands
1073 else if( decimalSeparatorFound )
1074 return false; // more than one decimal
1075 else
1076 decimalSeparatorFound = true;
1077 }
1078 else if( c == thousandsSeparator )
1079 {
1080 if( digits != 3 )
1081 return false; // thousands not followed by 3 digits
1082 else
1083 thousandsSeparatorFound = true;
1084 }
1085 }
1086 else if( ambiguousSeparator != '?' )
1087 {
1088 // We've previously found a separator, but we don't know for sure which...
1089
1090 if( c == ambiguousSeparator )
1091 {
1092 // They both must be thousands separators
1093 thousandsSeparator = ambiguousSeparator;
1094 thousandsSeparatorFound = true;
1095 decimalSeparator = c == '.' ? ',' : '.';
1096 }
1097 else
1098 {
1099 // The first must have been a decimal, and this must be a thousands.
1100 decimalSeparator = ambiguousSeparator;
1101 decimalSeparatorFound = true;
1102 thousandsSeparator = c;
1103 thousandsSeparatorFound = true;
1104 }
1105 }
1106 else
1107 {
1108 // This is the first separator...
1109
1110 // If it's preceded by a '0' (only), or if it's followed by some number of
1111 // digits not equal to 3, then it -must- be a decimal separator.
1112 //
1113 // In all other cases we don't really know what it is yet.
1114
1115 if( ( ii == 1 && value->GetChar( 0 ) == '0' ) || digits != 3 )
1116 {
1117 decimalSeparator = c;
1118 decimalSeparatorFound = true;
1119 thousandsSeparator = c == '.' ? ',' : '.';
1120 }
1121 else
1122 {
1123 ambiguousSeparator = c;
1124 }
1125 }
1126
1127 digits = 0;
1128 }
1129 else
1130 {
1131 digits = 0;
1132 }
1133 }
1134
1135 // If we found nothing definitive then we have to look at the current locale
1136 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1137 {
1138 const struct lconv* lc = localeconv();
1139
1140 decimalSeparator = lc->decimal_point[0];
1141 thousandsSeparator = decimalSeparator == '.' ? ',' : '.';
1142 }
1143
1144 // Convert to C-locale
1145 value->Replace( thousandsSeparator, wxEmptyString );
1146 value->Replace( decimalSeparator, '.' );
1147
1148 return true;
1149}
1150
1151
1152int ValueStringCompare( const wxString& strFWord, const wxString& strSWord )
1153{
1154 // Compare unescaped text
1155 wxString fWord = UnescapeString( strFWord );
1156 wxString sWord = UnescapeString( strSWord );
1157
1158 // The different sections of the two strings
1159 wxString strFWordBeg, strFWordMid, strFWordEnd;
1160 wxString strSWordBeg, strSWordMid, strSWordEnd;
1161
1162 // Split the two strings into separate parts
1163 SplitString( fWord, &strFWordBeg, &strFWordMid, &strFWordEnd );
1164 SplitString( sWord, &strSWordBeg, &strSWordMid, &strSWordEnd );
1165
1166 // Compare the Beginning section of the strings
1167 int isEqual = strFWordBeg.CmpNoCase( strSWordBeg );
1168
1169 if( isEqual > 0 )
1170 {
1171 return 1;
1172 }
1173 else if( isEqual < 0 )
1174 {
1175 return -1;
1176 }
1177 else
1178 {
1179 // If the first sections are equal compare their digits
1180 double lFirstNumber = 0;
1181 double lSecondNumber = 0;
1182 bool endingIsModifier = false;
1183
1184 convertSeparators( &strFWordMid );
1185 convertSeparators( &strSWordMid );
1186
1187 strFWordMid.ToCDouble( &lFirstNumber );
1188 strSWordMid.ToCDouble( &lSecondNumber );
1189
1190 endingIsModifier |= ApplyModifier( lFirstNumber, strFWordEnd );
1191 endingIsModifier |= ApplyModifier( lSecondNumber, strSWordEnd );
1192
1193 if( lFirstNumber > lSecondNumber )
1194 return 1;
1195 else if( lFirstNumber < lSecondNumber )
1196 return -1;
1197 // If the first two sections are equal and the endings are modifiers then compare them
1198 else if( !endingIsModifier )
1199 return strFWordEnd.CmpNoCase( strSWordEnd );
1200 // Ran out of things to compare; they must match
1201 else
1202 return 0;
1203 }
1204}
1205
1206
1207int SplitString( const wxString& strToSplit,
1208 wxString* strBeginning,
1209 wxString* strDigits,
1210 wxString* strEnd )
1211{
1212 static const wxString separators( wxT( ".," ) );
1213 wxUniChar infix = 0;
1214
1215 // Clear all the return strings
1216 strBeginning->Empty();
1217 strDigits->Empty();
1218 strEnd->Empty();
1219
1220 // There no need to do anything if the string is empty
1221 if( strToSplit.length() == 0 )
1222 return 0;
1223
1224 // Starting at the end of the string look for the first digit
1225 int ii;
1226
1227 for( ii = (strToSplit.length() - 1); ii >= 0; ii-- )
1228 {
1229 if( wxIsdigit( strToSplit[ii] ) )
1230 break;
1231 }
1232
1233 // If there were no digits then just set the single string
1234 if( ii < 0 )
1235 {
1236 *strBeginning = strToSplit;
1237 }
1238 else
1239 {
1240 // Since there is at least one digit this is the trailing string
1241 *strEnd = strToSplit.substr( ii + 1 );
1242
1243 // Go to the end of the digits
1244 int position = ii + 1;
1245
1246 for( ; ii >= 0; ii-- )
1247 {
1248 double scale;
1249 wxUniChar c = strToSplit[ii];
1250
1251 if( wxIsdigit( c ) )
1252 {
1253 continue;
1254 }
1255 if( infix == 0 && NUMERIC_EVALUATOR::IsOldSchoolDecimalSeparator( c, &scale ) )
1256 {
1257 infix = c;
1258 continue;
1259 }
1260 else if( separators.Find( strToSplit[ii] ) >= 0 )
1261 {
1262 continue;
1263 }
1264 else
1265 {
1266 break;
1267 }
1268 }
1269
1270 // If all that was left was digits, then just set the digits string
1271 if( ii < 0 )
1272 {
1273 *strDigits = strToSplit.substr( 0, position );
1274 }
1275 // Otherwise everything else is part of the preamble
1276 else
1277 {
1278 *strDigits = strToSplit.substr( ii + 1, position - ii - 1 );
1279 *strBeginning = strToSplit.substr( 0, ii + 1 );
1280 }
1281
1282 if( infix > 0 )
1283 {
1284 strDigits->Replace( infix, '.' );
1285 *strEnd = infix + *strEnd;
1286 }
1287 }
1288
1289 return 0;
1290}
1291
1292
1293int GetTrailingInt( const wxString& aStr )
1294{
1295 int number = 0;
1296 int base = 1;
1297
1298 // Trim and extract the trailing numeric part
1299 int index = aStr.Len() - 1;
1300
1301 while( index >= 0 )
1302 {
1303 const char chr = aStr.GetChar( index );
1304
1305 if( chr < '0' || chr > '9' )
1306 break;
1307
1308 number += ( chr - '0' ) * base;
1309 base *= 10;
1310 index--;
1311 }
1312
1313 return number;
1314}
1315
1316
1318{
1319 return wxString::FromUTF8( illegalFileNameChars.data(), illegalFileNameChars.length() );
1320}
1321
1322
1323bool ReplaceIllegalFileNameChars( std::string& aName, int aReplaceChar )
1324{
1325 size_t first_illegal_pos = aName.find_first_of( illegalFileNameChars );
1326
1327 if( first_illegal_pos == std::string::npos )
1328 {
1329 return false;
1330 }
1331
1332 std::string result;
1333 // result will be at least equal to original, add 16 in case of hex replacements
1334 result.reserve( aName.length() + 16 );
1335 // append the valid part
1336 result.append( aName, 0, first_illegal_pos );
1337
1338 for( size_t i = first_illegal_pos; i < aName.length(); ++i )
1339 {
1340 char c = aName[i];
1341
1342 // Check if this specific char is illegal
1343 if( illegalFileNameChars.find( c ) != std::string_view::npos )
1344 {
1345 if( aReplaceChar )
1346 {
1347 result.push_back( aReplaceChar );
1348 }
1349 else
1350 {
1351 fmt::format_to( std::back_inserter( result ), "%{:02x}", static_cast<unsigned char>( c ) );
1352 }
1353 }
1354 else
1355 {
1356 result.push_back( c );
1357 }
1358 }
1359
1360 aName = std::move( result );
1361 return true;
1362}
1363
1364
1365bool ReplaceIllegalFileNameChars( wxString& aName, int aReplaceChar )
1366{
1367 bool changed = false;
1368 wxString result;
1369 result.reserve( aName.Length() );
1370 wxString illWChars = GetIllegalFileNameWxChars();
1371
1372 for( wxString::iterator it = aName.begin(); it != aName.end(); ++it )
1373 {
1374 if( illWChars.Find( *it ) != wxNOT_FOUND )
1375 {
1376 if( aReplaceChar )
1377 result += aReplaceChar;
1378 else
1379 result += wxString::Format( "%%%02x", *it );
1380
1381 changed = true;
1382 }
1383 else
1384 {
1385 result += *it;
1386 }
1387 }
1388
1389 if( changed )
1390 aName = std::move( result );
1391
1392 return changed;
1393}
1394
1395
1396void wxStringSplit( const wxString& aText, wxArrayString& aStrings, wxChar aSplitter )
1397{
1398 wxString tmp;
1399
1400 for( unsigned ii = 0; ii < aText.Length(); ii++ )
1401 {
1402 if( aText[ii] == aSplitter )
1403 {
1404 aStrings.Add( tmp );
1405 tmp.Clear();
1406 }
1407 else
1408 {
1409 tmp << aText[ii];
1410 }
1411 }
1412
1413 if( !tmp.IsEmpty() )
1414 aStrings.Add( tmp );
1415}
1416
1417
1418void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed )
1419{
1420 struct lconv* lc = localeconv();
1421 char sep = lc->decimal_point[0];
1422 unsigned sep_pos = aStringValue.Find( sep );
1423
1424 if( sep_pos > 0 )
1425 {
1426 // We want to keep at least aTrailingZeroAllowed digits after the separator
1427 unsigned min_len = sep_pos + aTrailingZeroAllowed + 1;
1428
1429 while( aStringValue.Len() > min_len )
1430 {
1431 if( aStringValue.Last() == '0' )
1432 aStringValue.RemoveLast();
1433 else
1434 break;
1435 }
1436 }
1437}
1438
1439
1440std::string FormatDouble2Str( double aValue )
1441{
1442 std::string buf;
1443
1444 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1445 {
1446 buf = fmt::format( "{:.16f}", aValue );
1447
1448 // remove trailing zeros (and the decimal marker if needed)
1449 while( !buf.empty() && buf[buf.size() - 1] == '0' )
1450 {
1451 buf.pop_back();
1452 }
1453
1454 // if the value was really small
1455 // we may have just stripped all the zeros after the decimal
1456 if( buf[buf.size() - 1] == '.' )
1457 {
1458 buf.pop_back();
1459 }
1460 }
1461 else
1462 {
1463 buf = fmt::format( "{:.10g}", aValue );
1464 }
1465
1466 return buf;
1467}
1468
1469
1470std::string UIDouble2Str( double aValue )
1471{
1472 char buf[50];
1473 int len;
1474
1475 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1476 {
1477 // For these small values, %f works fine,
1478 // and %g gives an exponent
1479 len = snprintf( buf, sizeof( buf ), "%.16f", aValue );
1480
1481 while( --len > 0 && buf[len] == '0' )
1482 buf[len] = '\0';
1483
1484 if( buf[len] == '.' || buf[len] == ',' )
1485 buf[len] = '\0';
1486 else
1487 ++len;
1488 }
1489 else
1490 {
1491 // For these values, %g works fine, and sometimes %f
1492 // gives a bad value (try aValue = 1.222222222222, with %.16f format!)
1493 len = snprintf( buf, sizeof( buf ), "%.10g", aValue );
1494 }
1495
1496 return std::string( buf, len );
1497}
1498
1499
1500wxString From_UTF8( const char* cstring )
1501{
1502 // Convert an expected UTF8 encoded C string to a wxString
1503 wxString line = wxString::FromUTF8( cstring );
1504
1505 if( line.IsEmpty() ) // happens when cstring is not a valid UTF8 sequence
1506 {
1507 line = wxConvCurrent->cMB2WC( cstring ); // try to use locale conversion
1508
1509 if( line.IsEmpty() )
1510 line = wxString::From8BitData( cstring ); // try to use native string
1511 }
1512
1513 return line;
1514}
1515
1516
1517wxString From_UTF8( const std::string& aString )
1518{
1519 // Convert an expected UTF8 encoded std::string to a wxString
1520 wxString line = wxString::FromUTF8( aString );
1521
1522 if( line.IsEmpty() ) // happens when aString is not a valid UTF8 sequence
1523 {
1524 line = wxConvCurrent->cMB2WC( aString.c_str() ); // try to use locale conversion
1525
1526 if( line.IsEmpty() )
1527 line = wxString::From8BitData( aString.c_str() ); // try to use native string
1528 }
1529
1530 return line;
1531}
1532
1533
1534wxString NormalizeFileUri( const wxString& aFileUri )
1535{
1536 wxString uriPathAndFileName;
1537
1538 wxCHECK( aFileUri.StartsWith( wxS( "file://" ), &uriPathAndFileName ), aFileUri );
1539
1540 wxString tmp = uriPathAndFileName;
1541 wxString retv = wxS( "file://" );
1542
1543 tmp.Replace( wxS( "\\" ), wxS( "/" ) );
1544 tmp.Replace( wxS( ":" ), wxS( "" ) );
1545
1546 if( !tmp.IsEmpty() && tmp[0] != '/' )
1547 tmp = wxS( "/" ) + tmp;
1548
1549 retv += tmp;
1550
1551 return retv;
1552}
1553
1554
1555namespace
1556{
1557 // Extract (prefix, numericValue) where numericValue = -1 if no numeric suffix
1558 std::pair<wxString, long> ParseAlphaNumericPin( const wxString& pinNum )
1559 {
1560 wxString prefix;
1561 long numValue = -1;
1562
1563 size_t numStart = pinNum.length();
1564 for( int i = static_cast<int>( pinNum.length() ) - 1; i >= 0; --i )
1565 {
1566 if( !wxIsdigit( pinNum[i] ) )
1567 {
1568 numStart = i + 1;
1569 break;
1570 }
1571 if( i == 0 )
1572 numStart = 0; // all digits
1573 }
1574
1575 if( numStart < pinNum.length() )
1576 {
1577 prefix = pinNum.Left( numStart );
1578 wxString numericPart = pinNum.Mid( numStart );
1579 numericPart.ToLong( &numValue );
1580 }
1581
1582 return { prefix, numValue };
1583 }
1584}
1585
1586std::vector<wxString> ExpandStackedPinNotation( const wxString& aPinName, bool* aValid )
1587{
1588 if( aValid )
1589 *aValid = true;
1590
1591 std::vector<wxString> expanded;
1592
1593 const bool hasOpenBracket = aPinName.Contains( wxT( "[" ) );
1594 const bool hasCloseBracket = aPinName.Contains( wxT( "]" ) );
1595
1596 if( hasOpenBracket || hasCloseBracket )
1597 {
1598 if( !aPinName.StartsWith( wxT( "[" ) ) || !aPinName.EndsWith( wxT( "]" ) ) )
1599 {
1600 if( aValid )
1601 *aValid = false;
1602 expanded.push_back( aPinName );
1603 return expanded;
1604 }
1605 }
1606
1607 if( !aPinName.StartsWith( wxT( "[" ) ) || !aPinName.EndsWith( wxT( "]" ) ) )
1608 {
1609 expanded.push_back( aPinName );
1610 return expanded;
1611 }
1612
1613 const wxString inner = aPinName.Mid( 1, aPinName.Length() - 2 );
1614
1615 size_t start = 0;
1616 while( start < inner.length() )
1617 {
1618 size_t comma = inner.find( ',', start );
1619 wxString part = ( comma == wxString::npos ) ? inner.Mid( start ) : inner.Mid( start, comma - start );
1620 part.Trim( true ).Trim( false );
1621 if( part.empty() )
1622 {
1623 start = ( comma == wxString::npos ) ? inner.length() : comma + 1;
1624 continue;
1625 }
1626
1627 int dashPos = part.Find( '-' );
1628 if( dashPos != wxNOT_FOUND )
1629 {
1630 wxString startTxt = part.Left( dashPos );
1631 wxString endTxt = part.Mid( dashPos + 1 );
1632 startTxt.Trim( true ).Trim( false );
1633 endTxt.Trim( true ).Trim( false );
1634
1635 auto [startPrefix, startVal] = ParseAlphaNumericPin( startTxt );
1636 auto [endPrefix, endVal] = ParseAlphaNumericPin( endTxt );
1637
1638 if( startPrefix != endPrefix || startVal == -1 || endVal == -1 || startVal > endVal )
1639 {
1640 if( aValid )
1641 *aValid = false;
1642 expanded.clear();
1643 expanded.push_back( aPinName );
1644 return expanded;
1645 }
1646
1647 for( long ii = startVal; ii <= endVal; ++ii )
1648 {
1649 if( startPrefix.IsEmpty() )
1650 expanded.emplace_back( wxString::Format( wxT( "%ld" ), ii ) );
1651 else
1652 expanded.emplace_back( wxString::Format( wxT( "%s%ld" ), startPrefix, ii ) );
1653 }
1654 }
1655 else
1656 {
1657 expanded.push_back( part );
1658 }
1659
1660 if( comma == wxString::npos )
1661 break;
1662 start = comma + 1;
1663 }
1664
1665 if( expanded.empty() )
1666 {
1667 expanded.push_back( aPinName );
1668 if( aValid )
1669 *aValid = false;
1670 }
1671
1672 return expanded;
1673}
1674
1675
1676int CountStackedPinNotation( const wxString& aPinName, bool* aValid )
1677{
1678 size_t len = aPinName.length();
1679
1680 if( !aValid )
1681 {
1682 // Fastest path when we're not interested in validity
1683 if( len < 3 )
1684 return 1;
1685 }
1686 else
1687 {
1688 *aValid = true;
1689
1690 // Fast path: if no brackets, it's a single pin
1691 const bool hasOpenBracket = aPinName.Contains( wxT( "[" ) );
1692 const bool hasCloseBracket = aPinName.Contains( wxT( "]" ) );
1693
1694 if( hasOpenBracket || hasCloseBracket )
1695 {
1696 if( aPinName[0] != '[' || aPinName[len - 1] != ']' )
1697 {
1698 *aValid = false;
1699 return 1;
1700 }
1701 }
1702 }
1703
1704 if( aPinName[0] != '[' || aPinName[len - 1] != ']' )
1705 return 1;
1706
1707 const wxString inner = aPinName.Mid( 1, aPinName.Length() - 2 );
1708
1709 int count = 0;
1710 size_t start = 0;
1711
1712 while( start < inner.length() )
1713 {
1714 size_t comma = inner.find( ',', start );
1715 wxString part = ( comma == wxString::npos ) ? inner.Mid( start ) : inner.Mid( start, comma - start );
1716 part.Trim( true ).Trim( false );
1717
1718 if( part.empty() )
1719 {
1720 start = ( comma == wxString::npos ) ? inner.length() : comma + 1;
1721 continue;
1722 }
1723
1724 int dashPos = part.Find( '-' );
1725 if( dashPos != wxNOT_FOUND )
1726 {
1727 wxString startTxt = part.Left( dashPos );
1728 wxString endTxt = part.Mid( dashPos + 1 );
1729 startTxt.Trim( true ).Trim( false );
1730 endTxt.Trim( true ).Trim( false );
1731
1732 auto [startPrefix, startVal] = ParseAlphaNumericPin( startTxt );
1733 auto [endPrefix, endVal] = ParseAlphaNumericPin( endTxt );
1734
1735 if( startPrefix != endPrefix || startVal == -1 || endVal == -1 || startVal > endVal )
1736 {
1737 if( aValid )
1738 *aValid = false;
1739
1740 return 1;
1741 }
1742
1743 // Count pins in the range
1744 count += static_cast<int>( endVal - startVal + 1 );
1745 }
1746 else
1747 {
1748 // Single pin
1749 ++count;
1750 }
1751
1752 if( comma == wxString::npos )
1753 break;
1754
1755 start = comma + 1;
1756 }
1757
1758 if( count == 0 )
1759 {
1760 if( aValid )
1761 *aValid = false;
1762
1763 return 1;
1764 }
1765
1766 return count;
1767}
1768
1769
1771{
1772 return wxString( defaultVariantName );
1773}
1774
1775
1776int SortVariantNames( const wxString& aLhs, const wxString& aRhs )
1777{
1778 if( ( aLhs == defaultVariantName ) && ( aRhs != defaultVariantName ) )
1779 return -1;
1780
1781 if( ( aLhs != defaultVariantName ) && ( aRhs == defaultVariantName ) )
1782 return 1;
1783
1784 return StrNumCmp( aLhs, aRhs );
1785}
1786
1787
1788std::vector<LOAD_MESSAGE> ExtractLibraryLoadErrors( const wxString& aErrorString, int aSeverity )
1789{
1790 std::vector<LOAD_MESSAGE> messages;
1791
1792 if( aErrorString.IsEmpty() )
1793 return messages;
1794
1795 // Errors are separated by newlines. We want to keep:
1796 // - Lines starting with "Library '" (library-level errors)
1797 // - Lines containing "Expecting" (file error location)
1798 // And strip:
1799 // - Lines starting with "from " (internal code location info)
1800 wxStringTokenizer tokenizer( aErrorString, wxS( "\n" ), wxTOKEN_STRTOK );
1801
1802 while( tokenizer.HasMoreTokens() )
1803 {
1804 wxString line = tokenizer.GetNextToken();
1805
1806 // Skip internal code location lines (e.g., "from pcb_io_kicad_sexpr_parser.cpp : ...")
1807 if( line.StartsWith( wxS( "from " ) ) )
1808 continue;
1809
1810 if( line.StartsWith( wxS( "Library '" ) ) || line.Contains( wxS( "Expecting" ) ) )
1811 messages.push_back( { line, static_cast<SEVERITY>( aSeverity ) } );
1812 }
1813
1814 return messages;
1815}
1816
int index
static bool IsOldSchoolDecimalSeparator(wxUniChar ch, double *siScaler)
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:34
SEVERITY
const int scale
int StrNumCmp(const wxString &aString1, const wxString &aString2, bool aIgnoreCase)
Compare two strings with alphanumerical content.
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.
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)
std::vector< LOAD_MESSAGE > ExtractLibraryLoadErrors(const wxString &aErrorString, int aSeverity)
Parse library load error messages, extracting user-facing information while stripping internal code l...
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[]
void wxStringSplit(const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
Split aString to a string list separated at aSplitter.
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::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::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.
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 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...
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 without allocating strings.
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 UnescapeHTML(const wxString &aString)
Return a new wxString unescaped from HTML format.
bool IsURL(wxString aStr)
Performs a URL sniff-test on a string.
#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_LEGACY_LIBID
@ CTX_JS_STR
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.