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'\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 == '(' || 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 const auto str1End = aString1.end();
830 const auto str2End = aString2.end();
831
832 while( str1 != str1End && str2 != str2End )
833 {
834 wxUniChar c1 = *str1;
835 wxUniChar c2 = *str2;
836
837 if( wxIsdigit( c1 ) && wxIsdigit( c2 ) ) // Both characters are digits, do numeric compare.
838 {
839 nb1 = 0;
840 nb2 = 0;
841
842 do
843 {
844 c1 = *str1;
845 nb1 = nb1 * 10 + (int) c1 - '0';
846 ++str1;
847 } while( str1 != str1End && wxIsdigit( *str1 ) );
848
849 do
850 {
851 c2 = *str2;
852 nb2 = nb2 * 10 + (int) c2 - '0';
853 ++str2;
854 } while( str2 != str2End && wxIsdigit( *str2 ) );
855
856 if( nb1 < nb2 )
857 return -1;
858
859 if( nb1 > nb2 )
860 return 1;
861
862 c1 = ( str1 != str1End ) ? *str1 : wxUniChar( 0 );
863 c2 = ( str2 != str2End ) ? *str2 : wxUniChar( 0 );
864 }
865
866 // Any numerical comparisons to here are identical.
867 if( aIgnoreCase )
868 {
869 if( c1 != c2 )
870 {
871 wxUniChar uc1 = wxToupper( c1 );
872 wxUniChar uc2 = wxToupper( c2 );
873
874 if( uc1 != uc2 )
875 return uc1 < uc2 ? -1 : 1;
876 }
877 }
878 else
879 {
880 if( c1 < c2 )
881 return -1;
882
883 if( c1 > c2 )
884 return 1;
885 }
886
887 if( str1 != str1End )
888 ++str1;
889
890 if( str2 != str2End )
891 ++str2;
892 }
893
894 if( str1 == str1End && str2 != str2End )
895 {
896 return -1; // Identical to here but aString1 is longer.
897 }
898 else if( str1 != str1End && str2 == str2End )
899 {
900 return 1; // Identical to here but aString2 is longer.
901 }
902
903 return 0;
904}
905
906
907bool WildCompareString( const wxString& pattern, const wxString& string_to_tst,
908 bool case_sensitive )
909{
910 const wxChar* cp = nullptr;
911 const wxChar* mp = nullptr;
912 const wxChar* wild = nullptr;
913 const wxChar* str = nullptr;
914 wxString _pattern, _string_to_tst;
915
916 if( case_sensitive )
917 {
918 wild = pattern.GetData();
919 str = string_to_tst.GetData();
920 }
921 else
922 {
923 _pattern = pattern;
924 _pattern.MakeUpper();
925 _string_to_tst = string_to_tst;
926 _string_to_tst.MakeUpper();
927 wild = _pattern.GetData();
928 str = _string_to_tst.GetData();
929 }
930
931 while( ( *str ) && ( *wild != '*' ) )
932 {
933 if( ( *wild != *str ) && ( *wild != '?' ) )
934 return false;
935
936 wild++;
937 str++;
938 }
939
940 while( *str )
941 {
942 if( *wild == '*' )
943 {
944 if( !*++wild )
945 return true;
946
947 mp = wild;
948 cp = str + 1;
949 }
950 else if( ( *wild == *str ) || ( *wild == '?' ) )
951 {
952 wild++;
953 str++;
954 }
955 else
956 {
957 wild = mp;
958 str = cp++;
959 }
960 }
961
962 while( *wild == '*' )
963 {
964 wild++;
965 }
966
967 return !*wild;
968}
969
970
971bool ApplyModifier( double& value, const wxString& aString )
972{
974 static const wxString modifiers( wxT( "afpnuµμmLRFkKMGTPE" ) );
975
976 if( !aString.length() )
977 return false;
978
979 wxChar modifier;
980 wxString units;
981
982 if( modifiers.Find( aString[ 0 ] ) >= 0 )
983 {
984 modifier = aString[ 0 ];
985 units = aString.Mid( 1 ).Trim();
986 }
987 else
988 {
989 modifier = ' ';
990 units = aString.Mid( 0 ).Trim();
991 }
992
993 if( units.length()
994 && !units.IsSameAs( wxT( "F" ), false )
995 && !units.IsSameAs( wxT( "hz" ), false )
996 && !units.IsSameAs( wxT( "W" ), false )
997 && !units.IsSameAs( wxT( "V" ), false )
998 && !units.IsSameAs( wxT( "A" ), false )
999 && !units.IsSameAs( wxT( "H" ), false ) )
1000 {
1001 return false;
1002 }
1003
1004 // Note: most of these are SI, but some (L, R, F) are IEC 60062.
1005 if( modifier == 'a' )
1006 value *= 1.0e-18;
1007 else if( modifier == 'f' )
1008 value *= 1.0e-15;
1009 if( modifier == 'p' )
1010 value *= 1.0e-12;
1011 if( modifier == 'n' )
1012 value *= 1.0e-9;
1013 else if( modifier == 'u' || modifier == wxS( "µ" )[0] || modifier == wxS( "μ" )[0] )
1014 value *= 1.0e-6;
1015 else if( modifier == 'm' || modifier == 'L' )
1016 value *= 1.0e-3;
1017 else if( modifier == 'R' || modifier == 'F' )
1018 ; // unity scalar
1019 else if( modifier == 'k' || modifier == 'K' )
1020 value *= 1.0e3;
1021 else if( modifier == 'M' )
1022 value *= 1.0e6;
1023 else if( modifier == 'G' )
1024 value *= 1.0e9;
1025 else if( modifier == 'T' )
1026 value *= 1.0e12;
1027 else if( modifier == 'P' )
1028 value *= 1.0e15;
1029 else if( modifier == 'E' )
1030 value *= 1.0e18;
1031
1032 return true;
1033}
1034
1035
1036bool convertSeparators( wxString* value )
1037{
1038 // Note: fetching the decimal separator from the current locale isn't a silver bullet because
1039 // it assumes the current computer's locale is the same as the locale the schematic was
1040 // authored in -- something that isn't true, for instance, when sharing designs through
1041 // DIYAudio.com.
1042 //
1043 // Some values are self-describing: multiple instances of a single separator character must be
1044 // thousands separators; a single instance of each character must be a thousands separator
1045 // followed by a decimal separator; etc.
1046 //
1047 // Only when presented with an ambiguous value do we fall back on the current locale.
1048
1049 value->Replace( wxS( " " ), wxEmptyString );
1050
1051 wxChar ambiguousSeparator = '?';
1052 wxChar thousandsSeparator = '?';
1053 bool thousandsSeparatorFound = false;
1054 wxChar decimalSeparator = '?';
1055 bool decimalSeparatorFound = false;
1056 int digits = 0;
1057
1058 for( int ii = (int) value->length() - 1; ii >= 0; --ii )
1059 {
1060 wxChar c = value->GetChar( ii );
1061
1062 if( c >= '0' && c <= '9' )
1063 {
1064 digits += 1;
1065 }
1066 else if( c == '.' || c == ',' )
1067 {
1068 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1069 {
1070 // We've previously found a non-ambiguous separator...
1071
1072 if( c == decimalSeparator )
1073 {
1074 if( thousandsSeparatorFound )
1075 return false; // decimal before thousands
1076 else if( decimalSeparatorFound )
1077 return false; // more than one decimal
1078 else
1079 decimalSeparatorFound = true;
1080 }
1081 else if( c == thousandsSeparator )
1082 {
1083 if( digits != 3 )
1084 return false; // thousands not followed by 3 digits
1085 else
1086 thousandsSeparatorFound = true;
1087 }
1088 }
1089 else if( ambiguousSeparator != '?' )
1090 {
1091 // We've previously found a separator, but we don't know for sure which...
1092
1093 if( c == ambiguousSeparator )
1094 {
1095 // They both must be thousands separators
1096 thousandsSeparator = ambiguousSeparator;
1097 thousandsSeparatorFound = true;
1098 decimalSeparator = c == '.' ? ',' : '.';
1099 }
1100 else
1101 {
1102 // The first must have been a decimal, and this must be a thousands.
1103 decimalSeparator = ambiguousSeparator;
1104 decimalSeparatorFound = true;
1105 thousandsSeparator = c;
1106 thousandsSeparatorFound = true;
1107 }
1108 }
1109 else
1110 {
1111 // This is the first separator...
1112
1113 // If it's preceded by a '0' (only), or if it's followed by some number of
1114 // digits not equal to 3, then it -must- be a decimal separator.
1115 //
1116 // In all other cases we don't really know what it is yet.
1117
1118 if( ( ii == 1 && value->GetChar( 0 ) == '0' ) || digits != 3 )
1119 {
1120 decimalSeparator = c;
1121 decimalSeparatorFound = true;
1122 thousandsSeparator = c == '.' ? ',' : '.';
1123 }
1124 else
1125 {
1126 ambiguousSeparator = c;
1127 }
1128 }
1129
1130 digits = 0;
1131 }
1132 else
1133 {
1134 digits = 0;
1135 }
1136 }
1137
1138 // If we found nothing definitive then we have to look at the current locale
1139 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1140 {
1141 const struct lconv* lc = localeconv();
1142
1143 decimalSeparator = lc->decimal_point[0];
1144 thousandsSeparator = decimalSeparator == '.' ? ',' : '.';
1145 }
1146
1147 // Convert to C-locale
1148 value->Replace( thousandsSeparator, wxEmptyString );
1149 value->Replace( decimalSeparator, '.' );
1150
1151 return true;
1152}
1153
1154
1155int ValueStringCompare( const wxString& strFWord, const wxString& strSWord )
1156{
1157 // Compare unescaped text
1158 wxString fWord = UnescapeString( strFWord );
1159 wxString sWord = UnescapeString( strSWord );
1160
1161 // The different sections of the two strings
1162 wxString strFWordBeg, strFWordMid, strFWordEnd;
1163 wxString strSWordBeg, strSWordMid, strSWordEnd;
1164
1165 // Split the two strings into separate parts
1166 SplitString( fWord, &strFWordBeg, &strFWordMid, &strFWordEnd );
1167 SplitString( sWord, &strSWordBeg, &strSWordMid, &strSWordEnd );
1168
1169 // Compare the Beginning section of the strings
1170 int isEqual = strFWordBeg.CmpNoCase( strSWordBeg );
1171
1172 if( isEqual > 0 )
1173 {
1174 return 1;
1175 }
1176 else if( isEqual < 0 )
1177 {
1178 return -1;
1179 }
1180 else
1181 {
1182 // If the first sections are equal compare their digits
1183 double lFirstNumber = 0;
1184 double lSecondNumber = 0;
1185 bool endingIsModifier = false;
1186
1187 convertSeparators( &strFWordMid );
1188 convertSeparators( &strSWordMid );
1189
1190 strFWordMid.ToCDouble( &lFirstNumber );
1191 strSWordMid.ToCDouble( &lSecondNumber );
1192
1193 endingIsModifier |= ApplyModifier( lFirstNumber, strFWordEnd );
1194 endingIsModifier |= ApplyModifier( lSecondNumber, strSWordEnd );
1195
1196 if( lFirstNumber > lSecondNumber )
1197 return 1;
1198 else if( lFirstNumber < lSecondNumber )
1199 return -1;
1200 // If the first two sections are equal and the endings are modifiers then compare them
1201 else if( !endingIsModifier )
1202 return strFWordEnd.CmpNoCase( strSWordEnd );
1203 // Ran out of things to compare; they must match
1204 else
1205 return 0;
1206 }
1207}
1208
1209
1210int SplitString( const wxString& strToSplit,
1211 wxString* strBeginning,
1212 wxString* strDigits,
1213 wxString* strEnd )
1214{
1215 static const wxString separators( wxT( ".," ) );
1216 wxUniChar infix = 0;
1217
1218 // Clear all the return strings
1219 strBeginning->Empty();
1220 strDigits->Empty();
1221 strEnd->Empty();
1222
1223 // There no need to do anything if the string is empty
1224 if( strToSplit.length() == 0 )
1225 return 0;
1226
1227 // Starting at the end of the string look for the first digit
1228 int ii;
1229
1230 for( ii = (strToSplit.length() - 1); ii >= 0; ii-- )
1231 {
1232 if( wxIsdigit( strToSplit[ii] ) )
1233 break;
1234 }
1235
1236 // If there were no digits then just set the single string
1237 if( ii < 0 )
1238 {
1239 *strBeginning = strToSplit;
1240 }
1241 else
1242 {
1243 // Since there is at least one digit this is the trailing string
1244 *strEnd = strToSplit.substr( ii + 1 );
1245
1246 // Go to the end of the digits
1247 int position = ii + 1;
1248
1249 for( ; ii >= 0; ii-- )
1250 {
1251 double scale;
1252 wxUniChar c = strToSplit[ii];
1253
1254 if( wxIsdigit( c ) )
1255 {
1256 continue;
1257 }
1258 if( infix == 0 && NUMERIC_EVALUATOR::IsOldSchoolDecimalSeparator( c, &scale ) )
1259 {
1260 infix = c;
1261 continue;
1262 }
1263 else if( separators.Find( strToSplit[ii] ) >= 0 )
1264 {
1265 continue;
1266 }
1267 else
1268 {
1269 break;
1270 }
1271 }
1272
1273 // If all that was left was digits, then just set the digits string
1274 if( ii < 0 )
1275 {
1276 *strDigits = strToSplit.substr( 0, position );
1277 }
1278 // Otherwise everything else is part of the preamble
1279 else
1280 {
1281 *strDigits = strToSplit.substr( ii + 1, position - ii - 1 );
1282 *strBeginning = strToSplit.substr( 0, ii + 1 );
1283 }
1284
1285 if( infix > 0 )
1286 {
1287 strDigits->Replace( infix, '.' );
1288 *strEnd = infix + *strEnd;
1289 }
1290 }
1291
1292 return 0;
1293}
1294
1295
1296int GetTrailingInt( const wxString& aStr )
1297{
1298 int number = 0;
1299 int base = 1;
1300
1301 // Trim and extract the trailing numeric part
1302 int index = aStr.Len() - 1;
1303
1304 while( index >= 0 )
1305 {
1306 const char chr = aStr.GetChar( index );
1307
1308 if( chr < '0' || chr > '9' )
1309 break;
1310
1311 number += ( chr - '0' ) * base;
1312 base *= 10;
1313 index--;
1314 }
1315
1316 return number;
1317}
1318
1319
1321{
1322 return wxString::FromUTF8( illegalFileNameChars.data(), illegalFileNameChars.length() );
1323}
1324
1325
1326bool ReplaceIllegalFileNameChars( std::string& aName, int aReplaceChar )
1327{
1328 size_t first_illegal_pos = aName.find_first_of( illegalFileNameChars );
1329
1330 if( first_illegal_pos == std::string::npos )
1331 {
1332 return false;
1333 }
1334
1335 std::string result;
1336 // result will be at least equal to original, add 16 in case of hex replacements
1337 result.reserve( aName.length() + 16 );
1338 // append the valid part
1339 result.append( aName, 0, first_illegal_pos );
1340
1341 for( size_t i = first_illegal_pos; i < aName.length(); ++i )
1342 {
1343 char c = aName[i];
1344
1345 // Check if this specific char is illegal
1346 if( illegalFileNameChars.find( c ) != std::string_view::npos )
1347 {
1348 if( aReplaceChar )
1349 {
1350 result.push_back( aReplaceChar );
1351 }
1352 else
1353 {
1354 fmt::format_to( std::back_inserter( result ), "%{:02x}", static_cast<unsigned char>( c ) );
1355 }
1356 }
1357 else
1358 {
1359 result.push_back( c );
1360 }
1361 }
1362
1363 aName = std::move( result );
1364 return true;
1365}
1366
1367
1368bool ReplaceIllegalFileNameChars( wxString& aName, int aReplaceChar )
1369{
1370 bool changed = false;
1371 wxString result;
1372 result.reserve( aName.Length() );
1373 wxString illWChars = GetIllegalFileNameWxChars();
1374
1375 for( wxString::iterator it = aName.begin(); it != aName.end(); ++it )
1376 {
1377 if( illWChars.Find( *it ) != wxNOT_FOUND )
1378 {
1379 if( aReplaceChar )
1380 result += aReplaceChar;
1381 else
1382 result += wxString::Format( "%%%02x", *it );
1383
1384 changed = true;
1385 }
1386 else
1387 {
1388 result += *it;
1389 }
1390 }
1391
1392 if( changed )
1393 aName = std::move( result );
1394
1395 return changed;
1396}
1397
1398
1399void wxStringSplit( const wxString& aText, wxArrayString& aStrings, wxChar aSplitter )
1400{
1401 wxString tmp;
1402
1403 for( unsigned ii = 0; ii < aText.Length(); ii++ )
1404 {
1405 if( aText[ii] == aSplitter )
1406 {
1407 aStrings.Add( tmp );
1408 tmp.Clear();
1409 }
1410 else
1411 {
1412 tmp << aText[ii];
1413 }
1414 }
1415
1416 if( !tmp.IsEmpty() )
1417 aStrings.Add( tmp );
1418}
1419
1420
1421void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed )
1422{
1423 struct lconv* lc = localeconv();
1424 char sep = lc->decimal_point[0];
1425 unsigned sep_pos = aStringValue.Find( sep );
1426
1427 if( sep_pos > 0 )
1428 {
1429 // We want to keep at least aTrailingZeroAllowed digits after the separator
1430 unsigned min_len = sep_pos + aTrailingZeroAllowed + 1;
1431
1432 while( aStringValue.Len() > min_len )
1433 {
1434 if( aStringValue.Last() == '0' )
1435 aStringValue.RemoveLast();
1436 else
1437 break;
1438 }
1439 }
1440}
1441
1442
1443std::string FormatDouble2Str( double aValue )
1444{
1445 std::string buf;
1446
1447 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1448 {
1449 buf = fmt::format( "{:.16f}", aValue );
1450
1451 // remove trailing zeros (and the decimal marker if needed)
1452 while( !buf.empty() && buf[buf.size() - 1] == '0' )
1453 {
1454 buf.pop_back();
1455 }
1456
1457 // if the value was really small
1458 // we may have just stripped all the zeros after the decimal
1459 if( buf[buf.size() - 1] == '.' )
1460 {
1461 buf.pop_back();
1462 }
1463 }
1464 else
1465 {
1466 buf = fmt::format( "{:.10g}", aValue );
1467 }
1468
1469 return buf;
1470}
1471
1472
1473std::string UIDouble2Str( double aValue )
1474{
1475 char buf[50];
1476 int len;
1477
1478 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1479 {
1480 // For these small values, %f works fine,
1481 // and %g gives an exponent
1482 len = snprintf( buf, sizeof( buf ), "%.16f", aValue );
1483
1484 while( --len > 0 && buf[len] == '0' )
1485 buf[len] = '\0';
1486
1487 if( buf[len] == '.' || buf[len] == ',' )
1488 buf[len] = '\0';
1489 else
1490 ++len;
1491 }
1492 else
1493 {
1494 // For these values, %g works fine, and sometimes %f
1495 // gives a bad value (try aValue = 1.222222222222, with %.16f format!)
1496 len = snprintf( buf, sizeof( buf ), "%.10g", aValue );
1497 }
1498
1499 return std::string( buf, len );
1500}
1501
1502
1503wxString From_UTF8( const char* cstring )
1504{
1505 // Convert an expected UTF8 encoded C string to a wxString
1506 wxString line = wxString::FromUTF8( cstring );
1507
1508 if( line.IsEmpty() ) // happens when cstring is not a valid UTF8 sequence
1509 {
1510 line = wxConvCurrent->cMB2WC( cstring ); // try to use locale conversion
1511
1512 if( line.IsEmpty() )
1513 line = wxString::From8BitData( cstring ); // try to use native string
1514 }
1515
1516 return line;
1517}
1518
1519
1520wxString From_UTF8( const std::string& aString )
1521{
1522 // Convert an expected UTF8 encoded std::string to a wxString
1523 wxString line = wxString::FromUTF8( aString );
1524
1525 if( line.IsEmpty() ) // happens when aString is not a valid UTF8 sequence
1526 {
1527 line = wxConvCurrent->cMB2WC( aString.c_str() ); // try to use locale conversion
1528
1529 if( line.IsEmpty() )
1530 line = wxString::From8BitData( aString.c_str() ); // try to use native string
1531 }
1532
1533 return line;
1534}
1535
1536
1537wxString NormalizeFileUri( const wxString& aFileUri )
1538{
1539 wxString uriPathAndFileName;
1540
1541 wxCHECK( aFileUri.StartsWith( wxS( "file://" ), &uriPathAndFileName ), aFileUri );
1542
1543 wxString tmp = uriPathAndFileName;
1544 wxString retv = wxS( "file://" );
1545
1546 tmp.Replace( wxS( "\\" ), wxS( "/" ) );
1547 tmp.Replace( wxS( ":" ), wxS( "" ) );
1548
1549 if( !tmp.IsEmpty() && tmp[0] != '/' )
1550 tmp = wxS( "/" ) + tmp;
1551
1552 retv += tmp;
1553
1554 return retv;
1555}
1556
1557
1558namespace
1559{
1560 // Extract (prefix, numericValue) where numericValue = -1 if no numeric suffix
1561 std::pair<wxString, long> ParseAlphaNumericPin( const wxString& pinNum )
1562 {
1563 wxString prefix;
1564 long numValue = -1;
1565
1566 size_t numStart = pinNum.length();
1567 for( int i = static_cast<int>( pinNum.length() ) - 1; i >= 0; --i )
1568 {
1569 if( !wxIsdigit( pinNum[i] ) )
1570 {
1571 numStart = i + 1;
1572 break;
1573 }
1574 if( i == 0 )
1575 numStart = 0; // all digits
1576 }
1577
1578 if( numStart < pinNum.length() )
1579 {
1580 prefix = pinNum.Left( numStart );
1581 wxString numericPart = pinNum.Mid( numStart );
1582 numericPart.ToLong( &numValue );
1583 }
1584
1585 return { prefix, numValue };
1586 }
1587}
1588
1589std::vector<wxString> ExpandStackedPinNotation( const wxString& aPinName, bool* aValid )
1590{
1591 if( aValid )
1592 *aValid = true;
1593
1594 std::vector<wxString> expanded;
1595
1596 const bool hasOpenBracket = aPinName.Contains( wxT( "[" ) );
1597 const bool hasCloseBracket = aPinName.Contains( wxT( "]" ) );
1598
1599 if( hasOpenBracket || hasCloseBracket )
1600 {
1601 if( !aPinName.StartsWith( wxT( "[" ) ) || !aPinName.EndsWith( wxT( "]" ) ) )
1602 {
1603 if( aValid )
1604 *aValid = false;
1605 expanded.push_back( aPinName );
1606 return expanded;
1607 }
1608 }
1609
1610 if( !aPinName.StartsWith( wxT( "[" ) ) || !aPinName.EndsWith( wxT( "]" ) ) )
1611 {
1612 expanded.push_back( aPinName );
1613 return expanded;
1614 }
1615
1616 const wxString inner = aPinName.Mid( 1, aPinName.Length() - 2 );
1617
1618 size_t start = 0;
1619 while( start < inner.length() )
1620 {
1621 size_t comma = inner.find( ',', start );
1622 wxString part = ( comma == wxString::npos ) ? inner.Mid( start ) : inner.Mid( start, comma - start );
1623 part.Trim( true ).Trim( false );
1624 if( part.empty() )
1625 {
1626 start = ( comma == wxString::npos ) ? inner.length() : comma + 1;
1627 continue;
1628 }
1629
1630 int dashPos = part.Find( '-' );
1631 if( dashPos != wxNOT_FOUND )
1632 {
1633 wxString startTxt = part.Left( dashPos );
1634 wxString endTxt = part.Mid( dashPos + 1 );
1635 startTxt.Trim( true ).Trim( false );
1636 endTxt.Trim( true ).Trim( false );
1637
1638 auto [startPrefix, startVal] = ParseAlphaNumericPin( startTxt );
1639 auto [endPrefix, endVal] = ParseAlphaNumericPin( endTxt );
1640
1641 if( startPrefix != endPrefix || startVal == -1 || endVal == -1 || startVal > endVal )
1642 {
1643 if( aValid )
1644 *aValid = false;
1645 expanded.clear();
1646 expanded.push_back( aPinName );
1647 return expanded;
1648 }
1649
1650 for( long ii = startVal; ii <= endVal; ++ii )
1651 {
1652 if( startPrefix.IsEmpty() )
1653 expanded.emplace_back( wxString::Format( wxT( "%ld" ), ii ) );
1654 else
1655 expanded.emplace_back( wxString::Format( wxT( "%s%ld" ), startPrefix, ii ) );
1656 }
1657 }
1658 else
1659 {
1660 expanded.push_back( part );
1661 }
1662
1663 if( comma == wxString::npos )
1664 break;
1665 start = comma + 1;
1666 }
1667
1668 if( expanded.empty() )
1669 {
1670 expanded.push_back( aPinName );
1671 if( aValid )
1672 *aValid = false;
1673 }
1674
1675 return expanded;
1676}
1677
1678
1679int CountStackedPinNotation( const wxString& aPinName, bool* aValid )
1680{
1681 size_t len = aPinName.length();
1682
1683 if( !aValid )
1684 {
1685 // Fastest path when we're not interested in validity
1686 if( len < 3 )
1687 return 1;
1688 }
1689 else
1690 {
1691 *aValid = true;
1692
1693 // Fast path: if no brackets, it's a single pin
1694 const bool hasOpenBracket = aPinName.Contains( wxT( "[" ) );
1695 const bool hasCloseBracket = aPinName.Contains( wxT( "]" ) );
1696
1697 if( hasOpenBracket || hasCloseBracket )
1698 {
1699 if( aPinName[0] != '[' || aPinName[len - 1] != ']' )
1700 {
1701 *aValid = false;
1702 return 1;
1703 }
1704 }
1705 }
1706
1707 if( aPinName[0] != '[' || aPinName[len - 1] != ']' )
1708 return 1;
1709
1710 const wxString inner = aPinName.Mid( 1, aPinName.Length() - 2 );
1711
1712 int count = 0;
1713 size_t start = 0;
1714
1715 while( start < inner.length() )
1716 {
1717 size_t comma = inner.find( ',', start );
1718 wxString part = ( comma == wxString::npos ) ? inner.Mid( start ) : inner.Mid( start, comma - start );
1719 part.Trim( true ).Trim( false );
1720
1721 if( part.empty() )
1722 {
1723 start = ( comma == wxString::npos ) ? inner.length() : comma + 1;
1724 continue;
1725 }
1726
1727 int dashPos = part.Find( '-' );
1728 if( dashPos != wxNOT_FOUND )
1729 {
1730 wxString startTxt = part.Left( dashPos );
1731 wxString endTxt = part.Mid( dashPos + 1 );
1732 startTxt.Trim( true ).Trim( false );
1733 endTxt.Trim( true ).Trim( false );
1734
1735 auto [startPrefix, startVal] = ParseAlphaNumericPin( startTxt );
1736 auto [endPrefix, endVal] = ParseAlphaNumericPin( endTxt );
1737
1738 if( startPrefix != endPrefix || startVal == -1 || endVal == -1 || startVal > endVal )
1739 {
1740 if( aValid )
1741 *aValid = false;
1742
1743 return 1;
1744 }
1745
1746 // Count pins in the range
1747 count += static_cast<int>( endVal - startVal + 1 );
1748 }
1749 else
1750 {
1751 // Single pin
1752 ++count;
1753 }
1754
1755 if( comma == wxString::npos )
1756 break;
1757
1758 start = comma + 1;
1759 }
1760
1761 if( count == 0 )
1762 {
1763 if( aValid )
1764 *aValid = false;
1765
1766 return 1;
1767 }
1768
1769 return count;
1770}
1771
1772
1774{
1775 return wxString( defaultVariantName );
1776}
1777
1778
1779int SortVariantNames( const wxString& aLhs, const wxString& aRhs )
1780{
1781 if( ( aLhs == defaultVariantName ) && ( aRhs != defaultVariantName ) )
1782 return -1;
1783
1784 if( ( aLhs != defaultVariantName ) && ( aRhs == defaultVariantName ) )
1785 return 1;
1786
1787 return StrNumCmp( aLhs, aRhs );
1788}
1789
1790
1791std::vector<LOAD_MESSAGE> ExtractLibraryLoadErrors( const wxString& aErrorString, int aSeverity )
1792{
1793 std::vector<LOAD_MESSAGE> messages;
1794
1795 if( aErrorString.IsEmpty() )
1796 return messages;
1797
1798 // Errors are separated by newlines. We want to keep:
1799 // - Lines starting with "Library '" (library-level errors)
1800 // - Lines containing "Expecting" (file error location)
1801 // And strip:
1802 // - Lines starting with "from " (internal code location info)
1803 wxStringTokenizer tokenizer( aErrorString, wxS( "\n" ), wxTOKEN_STRTOK );
1804
1805 while( tokenizer.HasMoreTokens() )
1806 {
1807 wxString line = tokenizer.GetNextToken();
1808
1809 // Skip internal code location lines (e.g., "from pcb_io_kicad_sexpr_parser.cpp : ...")
1810 if( line.StartsWith( wxS( "from " ) ) )
1811 continue;
1812
1813 if( line.StartsWith( wxS( "Library '" ) ) || line.Contains( wxS( "Expecting" ) ) )
1814 messages.push_back( { line, static_cast<SEVERITY>( aSeverity ) } );
1815 }
1816
1817 return messages;
1818}
1819
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.