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 (C) 2004-2023, 2024 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
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 <richio.h> // StrPrintf
36#include <string_utils.h>
37#include <wx_filename.h>
38#include <fmt/chrono.h>
39#include <wx/log.h>
40#include <wx/regex.h>
41#include "locale_io.h"
42
43
49static const char illegalFileNameChars[] = "\\/:\"<>|*?";
50
51
52// Checks if a full filename is valid, i.e. does not contains illegal chars
53bool IsFullFileNameValid( const wxString& aFullFilename )
54{
55
56 // Test for forbidden chars in aFullFilename.
57 // '\'and '/' are allowed here because aFullFilename can be a full path, and
58 // ':' is allowed on Windows as second char in string.
59 // So remove allowed separators from string to test
60 wxString filtered_fullpath = aFullFilename;
61
62#ifdef __WINDOWS__
63 // On MSW, the list returned by wxFileName::GetForbiddenChars() contains separators
64 // '\'and '/'
65 filtered_fullpath.Replace( "/", "_" );
66 filtered_fullpath.Replace( "\\", "_" );
67
68 // A disk identifier is allowed, and therefore remove its separator
69 if( filtered_fullpath.Length() > 1 && filtered_fullpath[1] == ':' )
70 filtered_fullpath[1] = ' ';
71#endif
72
73 if( wxString::npos != filtered_fullpath.find_first_of( wxFileName::GetForbiddenChars() ) )
74 return false;
75
76 return true;
77}
78
79
80wxString ConvertToNewOverbarNotation( const wxString& aOldStr )
81{
82 wxString newStr;
83 bool inOverbar = false;
84
85 // Don't get tripped up by the legacy empty-string token.
86 if( aOldStr == wxT( "~" ) )
87 return aOldStr;
88
89 newStr.reserve( aOldStr.length() );
90
91 for( wxString::const_iterator chIt = aOldStr.begin(); chIt != aOldStr.end(); ++chIt )
92 {
93 if( *chIt == '~' )
94 {
95 wxString::const_iterator lookahead = chIt + 1;
96
97 if( lookahead != aOldStr.end() && *lookahead == '~' )
98 {
99 if( ++lookahead != aOldStr.end() && *lookahead == '{' )
100 {
101 // This way the subsequent opening curly brace will not start an
102 // overbar.
103 newStr << wxT( "~~{}" );
104 continue;
105 }
106
107 // Two subsequent tildes mean a tilde.
108 newStr << wxT( "~" );
109 ++chIt;
110 continue;
111 }
112 else if( lookahead != aOldStr.end() && *lookahead == '{' )
113 {
114 // Could mean the user wants "{" with an overbar, but more likely this
115 // is a case of double notation conversion. Bail out.
116 return aOldStr;
117 }
118 else
119 {
120 if( inOverbar )
121 {
122 newStr << wxT( "}" );
123 inOverbar = false;
124 }
125 else
126 {
127 newStr << wxT( "~{" );
128 inOverbar = true;
129 }
130
131 continue;
132 }
133 }
134 else if( ( *chIt == ' ' || *chIt == '}' || *chIt == ')' ) && inOverbar )
135 {
136 // Spaces were used to terminate overbar as well
137 newStr << wxT( "}" );
138 inOverbar = false;
139 }
140
141 newStr << *chIt;
142 }
143
144 // Explicitly end the overbar even if there was no terminating '~' in the aOldStr.
145 if( inOverbar )
146 newStr << wxT( "}" );
147
148 return newStr;
149}
150
151
152bool ConvertSmartQuotesAndDashes( wxString* aString )
153{
154 bool retVal = false;
155
156 for( wxString::iterator ii = aString->begin(); ii != aString->end(); ++ii )
157 {
158 if( *ii == L'\u00B4' || *ii == L'\u2018' || *ii == L'\u2019' )
159 {
160 *ii = '\'';
161 retVal = true;
162 }
163 if( *ii == L'\u201C' || *ii == L'\u201D' )
164 {
165 *ii = '"';
166 retVal = true;
167 }
168 if( *ii == L'\u2013' || *ii == L'\u2014' )
169 {
170 *ii = '-';
171 retVal = true;
172 }
173 }
174
175 return retVal;
176}
177
178
179wxString EscapeString( const wxString& aSource, ESCAPE_CONTEXT aContext )
180{
181 wxString converted;
182 std::vector<bool> braceStack; // true == formatting construct
183
184 converted.reserve( aSource.length() );
185
186 for( wxUniChar c: aSource )
187 {
188 if( aContext == CTX_NETNAME )
189 {
190 if( c == '/' )
191 converted += wxT( "{slash}" );
192 else if( c == '\n' || c == '\r' )
193 converted += wxEmptyString; // drop
194 else
195 converted += c;
196 }
197 else if( aContext == CTX_LIBID || aContext == CTX_LEGACY_LIBID )
198 {
199 // We no longer escape '/' in LIB_IDs, but we used to
200 if( c == '/' && aContext == CTX_LEGACY_LIBID )
201 converted += wxT( "{slash}" );
202 else if( c == '\\' )
203 converted += wxT( "{backslash}" );
204 else if( c == '<' )
205 converted += wxT( "{lt}" );
206 else if( c == '>' )
207 converted += wxT( "{gt}" );
208 else if( c == ':' )
209 converted += wxT( "{colon}" );
210 else if( c == '\"' )
211 converted += wxT( "{dblquote}" );
212 else if( c == '\n' || c == '\r' )
213 converted += wxEmptyString; // drop
214 else
215 converted += c;
216 }
217 else if( aContext == CTX_IPC )
218 {
219 if( c == '/' )
220 converted += wxT( "{slash}" );
221 else if( c == ',' )
222 converted += wxT( "{comma}" );
223 else if( c == '\"' )
224 converted += wxT( "{dblquote}" );
225 else
226 converted += c;
227 }
228 else if( aContext == CTX_QUOTED_STR )
229 {
230 if( c == '\"' )
231 converted += wxT( "{dblquote}" );
232 else
233 converted += c;
234 }
235 else if( aContext == CTX_JS_STR )
236 {
237 if( c >= 0x7F || c == '\'' || c == '\\' || c == '(' || c == ')' )
238 {
239 unsigned int code = c;
240 char buffer[16];
241 snprintf( buffer, sizeof(buffer), "\\u%4.4X", code );
242 converted += buffer;
243 }
244 else
245 {
246 converted += c;
247 }
248 }
249 else if( aContext == CTX_LINE )
250 {
251 if( c == '\n' || c == '\r' )
252 converted += wxT( "{return}" );
253 else
254 converted += c;
255 }
256 else if( aContext == CTX_FILENAME )
257 {
258 if( c == '/' )
259 converted += wxT( "{slash}" );
260 else if( c == '\\' )
261 converted += wxT( "{backslash}" );
262 else if( c == '\"' )
263 converted += wxT( "{dblquote}" );
264 else if( c == '<' )
265 converted += wxT( "{lt}" );
266 else if( c == '>' )
267 converted += wxT( "{gt}" );
268 else if( c == '|' )
269 converted += wxT( "{bar}" );
270 else if( c == ':' )
271 converted += wxT( "{colon}" );
272 else if( c == '\t' )
273 converted += wxT( "{tab}" );
274 else if( c == '\n' || c == '\r' )
275 converted += wxT( "{return}" );
276 else
277 converted += c;
278 }
279 else if( aContext == CTX_NO_SPACE )
280 {
281 if( c == ' ' )
282 converted += wxT( "{space}" );
283 else
284 converted += c;
285 }
286 else if( aContext == CTX_CSV )
287 {
288 if( c == ',' )
289 converted += wxT( "{comma}" );
290 else if( c == '\n' || c == '\r' )
291 converted += wxT( "{return}" );
292 else
293 converted += c;
294 }
295 else
296 {
297 converted += c;
298 }
299 }
300
301 return converted;
302}
303
304
305wxString UnescapeString( const wxString& aSource )
306{
307 size_t sourceLen = aSource.length();
308
309 // smallest escape string is three characters, shortcut everything else
310 if( sourceLen <= 2 )
311 {
312 return aSource;
313 }
314
315 wxString newbuf;
316 newbuf.reserve( sourceLen );
317
318 wxUniChar prev = 0;
319 wxUniChar ch = 0;
320
321 for( size_t i = 0; i < sourceLen; ++i )
322 {
323 prev = ch;
324 ch = aSource[i];
325
326 if( ch == '{' )
327 {
328 wxString token;
329 int depth = 1;
330 bool terminated = false;
331
332 for( i = i + 1; i < sourceLen; ++i )
333 {
334 ch = aSource[i];
335
336 if( ch == '{' )
337 depth++;
338 else if( ch == '}' )
339 depth--;
340
341 if( depth <= 0 )
342 {
343 terminated = true;
344 break;
345 }
346 else
347 {
348 token << ch;
349 }
350 }
351
352 if( !terminated )
353 {
354 newbuf << wxT( "{" ) << UnescapeString( token );
355 }
356 else if( prev == '$' || prev == '~' || prev == '^' || prev == '_' )
357 {
358 newbuf << wxT( "{" ) << UnescapeString( token ) << wxT( "}" );
359 }
360 else if( token == wxT( "dblquote" ) ) newbuf << wxT( "\"" );
361 else if( token == wxT( "quote" ) ) newbuf << wxT( "'" );
362 else if( token == wxT( "lt" ) ) newbuf << wxT( "<" );
363 else if( token == wxT( "gt" ) ) newbuf << wxT( ">" );
364 else if( token == wxT( "backslash" ) ) newbuf << wxT( "\\" );
365 else if( token == wxT( "slash" ) ) newbuf << wxT( "/" );
366 else if( token == wxT( "bar" ) ) newbuf << wxT( "|" );
367 else if( token == wxT( "comma" ) ) newbuf << wxT( "," );
368 else if( token == wxT( "colon" ) ) newbuf << wxT( ":" );
369 else if( token == wxT( "space" ) ) newbuf << wxT( " " );
370 else if( token == wxT( "dollar" ) ) newbuf << wxT( "$" );
371 else if( token == wxT( "tab" ) ) newbuf << wxT( "\t" );
372 else if( token == wxT( "return" ) ) newbuf << wxT( "\n" );
373 else if( token == wxT( "brace" ) ) newbuf << wxT( "{" );
374 else
375 {
376 newbuf << wxT( "{" ) << UnescapeString( token ) << wxT( "}" );
377 }
378 }
379 else
380 {
381 newbuf << ch;
382 }
383 }
384
385 return newbuf;
386}
387
388
389wxString TitleCaps( const wxString& aString )
390{
391 wxArrayString words;
392 wxString result;
393
394 wxStringSplit( aString, words, ' ' );
395
396 result.reserve( aString.length() );
397
398 for( const wxString& word : words )
399 {
400 if( !result.IsEmpty() )
401 result += wxT( " " );
402
403 result += word.Capitalize();
404 }
405
406 return result;
407}
408
409
410int ReadDelimitedText( wxString* aDest, const char* aSource )
411{
412 std::string utf8; // utf8 but without escapes and quotes.
413 bool inside = false;
414 const char* start = aSource;
415 char cc;
416
417 while( (cc = *aSource++) != 0 )
418 {
419 if( cc == '"' )
420 {
421 if( inside )
422 break; // 2nd double quote is end of delimited text
423
424 inside = true; // first delimiter found, make note, do not copy
425 }
426
427 else if( inside )
428 {
429 if( cc == '\\' )
430 {
431 cc = *aSource++;
432
433 if( !cc )
434 break;
435
436 // do no copy the escape byte if it is followed by \ or "
437 if( cc != '"' && cc != '\\' )
438 utf8 += '\\';
439
440 utf8 += cc;
441 }
442 else
443 {
444 utf8 += cc;
445 }
446 }
447 }
448
449 *aDest = From_UTF8( utf8.c_str() );
450
451 return aSource - start;
452}
453
454
455int ReadDelimitedText( char* aDest, const char* aSource, int aDestSize )
456{
457 if( aDestSize <= 0 )
458 return 0;
459
460 bool inside = false;
461 const char* start = aSource;
462 char* limit = aDest + aDestSize - 1;
463 char cc;
464
465 while( (cc = *aSource++) != 0 && aDest < limit )
466 {
467 if( cc == '"' )
468 {
469 if( inside )
470 break; // 2nd double quote is end of delimited text
471
472 inside = true; // first delimiter found, make note, do not copy
473 }
474
475 else if( inside )
476 {
477 if( cc == '\\' )
478 {
479 cc = *aSource++;
480
481 if( !cc )
482 break;
483
484 // do no copy the escape byte if it is followed by \ or "
485 if( cc != '"' && cc != '\\' )
486 *aDest++ = '\\';
487
488 if( aDest < limit )
489 *aDest++ = cc;
490 }
491 else
492 {
493 *aDest++ = cc;
494 }
495 }
496 }
497
498 *aDest = 0;
499
500 return aSource - start;
501}
502
503
504std::string EscapedUTF8( const wxString& aString )
505{
506 wxString str = aString;
507
508 // No new-lines allowed in quoted strings
509 str.Replace( wxT( "\r\n" ), wxT( "\r" ) );
510 str.Replace( wxT( "\n" ), wxT( "\r" ) );
511
512 std::string utf8 = TO_UTF8( aString );
513
514 std::string ret;
515
516 ret.reserve( utf8.length() + 2 );
517
518 ret += '"';
519
520 for( std::string::const_iterator it = utf8.begin(); it!=utf8.end(); ++it )
521 {
522 // this escaping strategy is designed to be compatible with ReadDelimitedText():
523 if( *it == '"' )
524 {
525 ret += '\\';
526 ret += '"';
527 }
528 else if( *it == '\\' )
529 {
530 ret += '\\'; // double it up
531 ret += '\\';
532 }
533 else
534 {
535 ret += *it;
536 }
537 }
538
539 ret += '"';
540
541 return ret;
542}
543
544
545wxString EscapeHTML( const wxString& aString )
546{
547 wxString converted;
548
549 converted.reserve( aString.length() );
550
551 for( wxUniChar c : aString )
552 {
553 if( c == '\"' )
554 converted += wxT( "&quot;" );
555 else if( c == '\'' )
556 converted += wxT( "&apos;" );
557 else if( c == '&' )
558 converted += wxT( "&amp;" );
559 else if( c == '<' )
560 converted += wxT( "&lt;" );
561 else if( c == '>' )
562 converted += wxT( "&gt;" );
563 else
564 converted += c;
565 }
566
567 return converted;
568}
569
570
571wxString UnescapeHTML( const wxString& aString )
572{
573 wxString converted = aString;
574
575 // clang-format off
576 static const std::map<wxString, wxString> c_replacements = {
577 { wxS( "quot" ), wxS( "\"" ) },
578 { wxS( "apos" ), wxS( "'" ) },
579 { wxS( "amp" ), wxS( "&" ) },
580 { wxS( "lt" ), wxS( "<" ) },
581 { wxS( "gt" ), wxS( ">" ) }
582 };
583 // clang-format on
584
585 // Construct regex
586 wxString regexStr = "&(#(\\d*)|#x([a-zA-Z0-9]{4})";
587
588 for( auto& [key, value] : c_replacements )
589 regexStr << '|' << key;
590
591 regexStr << ");";
592
593 wxRegEx regex( regexStr );
594
595 // Process matches
596 size_t start = 0;
597 size_t len = 0;
598
599 wxString result;
600 wxString str = converted;
601
602 while( regex.Matches( str ) )
603 {
604 std::vector<wxString> matches;
605 regex.GetMatch( &start, &len );
606
607 result << str.Left( start );
608
609 wxString code = regex.GetMatch( str, 1 );
610 wxString codeDec = regex.GetMatch( str, 2 );
611 wxString codeHex = regex.GetMatch( str, 3 );
612
613 if( !codeDec.IsEmpty() || !codeHex.IsEmpty() )
614 {
615 unsigned long codeVal = 0;
616
617 if( !codeDec.IsEmpty() )
618 codeDec.ToCULong( &codeVal );
619 else if( !codeHex.IsEmpty() )
620 codeHex.ToCULong( &codeVal, 16 );
621
622 if( codeVal != 0 )
623 result << wxUniChar( codeVal );
624 }
625 else if( auto val = get_opt( c_replacements, code ) )
626 {
627 result << *val;
628 }
629
630 str = str.Mid( start + len );
631 }
632
633 result << str;
634
635 return result;
636}
637
638
639wxString RemoveHTMLTags( const wxString& aInput )
640{
641 wxString str = aInput;
642 wxRegEx( wxS( "<[^>]*>" ) ).ReplaceAll( &str, wxEmptyString );
643
644 return str;
645}
646
647
648wxString LinkifyHTML( wxString aStr )
649{
650 wxRegEx regex( wxS( "\\b(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\s\u00b6])" ),
651 wxRE_ICASE );
652
653 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
654
655 return aStr;
656}
657
658
659bool NoPrintableChars( const wxString& aString )
660{
661 wxString tmp = aString;
662
663 return tmp.Trim( true ).Trim( false ).IsEmpty();
664}
665
666
671int PrintableCharCount( const wxString& aString )
672{
673 int char_count = 0;
674 int overbarDepth = -1;
675 int superSubDepth = -1;
676 int braceNesting = 0;
677
678 for( auto chIt = aString.begin(), end = aString.end(); chIt < end; ++chIt )
679 {
680 if( *chIt == '\t' )
681 {
682 // We don't format tabs in bitmap text (where this is currently used), so just
683 // drop them from the count.
684 continue;
685 }
686 else if( *chIt == '^' && superSubDepth == -1 )
687 {
688 auto lookahead = chIt;
689
690 if( ++lookahead != end && *lookahead == '{' )
691 {
692 chIt = lookahead;
693 superSubDepth = braceNesting;
694 braceNesting++;
695 continue;
696 }
697 }
698 else if( *chIt == '_' && superSubDepth == -1 )
699 {
700 auto lookahead = chIt;
701
702 if( ++lookahead != end && *lookahead == '{' )
703 {
704 chIt = lookahead;
705 superSubDepth = braceNesting;
706 braceNesting++;
707 continue;
708 }
709 }
710 else if( *chIt == '~' && overbarDepth == -1 )
711 {
712 auto lookahead = chIt;
713
714 if( ++lookahead != end && *lookahead == '{' )
715 {
716 chIt = lookahead;
717 overbarDepth = braceNesting;
718 braceNesting++;
719 continue;
720 }
721 }
722 else if( *chIt == '{' )
723 {
724 braceNesting++;
725 }
726 else if( *chIt == '}' )
727 {
728 if( braceNesting > 0 )
729 braceNesting--;
730
731 if( braceNesting == superSubDepth )
732 {
733 superSubDepth = -1;
734 continue;
735 }
736
737 if( braceNesting == overbarDepth )
738 {
739 overbarDepth = -1;
740 continue;
741 }
742 }
743
744 char_count++;
745 }
746
747 return char_count;
748}
749
750
751char* StrPurge( char* text )
752{
753 static const char whitespace[] = " \t\n\r\f\v";
754
755 if( text )
756 {
757 while( *text && strchr( whitespace, *text ) )
758 ++text;
759
760 char* cp = text + strlen( text ) - 1;
761
762 while( cp >= text && strchr( whitespace, *cp ) )
763 *cp-- = '\0';
764 }
765
766 return text;
767}
768
769
770char* GetLine( FILE* File, char* Line, int* LineNum, int SizeLine )
771{
772 do {
773 if( fgets( Line, SizeLine, File ) == nullptr )
774 return nullptr;
775
776 if( LineNum )
777 *LineNum += 1;
778
779 } while( Line[0] == '#' || Line[0] == '\n' || Line[0] == '\r' || Line[0] == 0 );
780
781 strtok( Line, "\n\r" );
782 return Line;
783}
784
785
787{
788 // on msys2 variant mingw64, in fmt::format the %z format
789 // (offset from UTC in the ISO 8601 format, e.g. -0430) does not work,
790 // and is in fact %Z (locale-dependent time zone name or abbreviation) and breaks our date.
791 // However, on msys2 variant ucrt64, it works (this is not the same code in fmt::format)
792#if defined(__MINGW32__) && !defined(_UCRT)
793 return fmt::format( "{:%FT%T}", fmt::localtime( std::time( nullptr ) ) );
794#else
795 return fmt::format( "{:%FT%T%z}", fmt::localtime( std::time( nullptr ) ) );
796#endif
797}
798
799
800int StrNumCmp( const wxString& aString1, const wxString& aString2, bool aIgnoreCase )
801{
802 int nb1 = 0, nb2 = 0;
803
804 auto str1 = aString1.begin();
805 auto str2 = aString2.begin();
806
807 while( str1 != aString1.end() && str2 != aString2.end() )
808 {
809 wxUniChar c1 = *str1;
810 wxUniChar c2 = *str2;
811
812 if( wxIsdigit( c1 ) && wxIsdigit( c2 ) ) // Both characters are digits, do numeric compare.
813 {
814 nb1 = 0;
815 nb2 = 0;
816
817 do
818 {
819 c1 = *str1;
820 nb1 = nb1 * 10 + (int) c1 - '0';
821 ++str1;
822 } while( str1 != aString1.end() && wxIsdigit( *str1 ) );
823
824 do
825 {
826 c2 = *str2;
827 nb2 = nb2 * 10 + (int) c2 - '0';
828 ++str2;
829 } while( str2 != aString2.end() && wxIsdigit( *str2 ) );
830
831 if( nb1 < nb2 )
832 return -1;
833
834 if( nb1 > nb2 )
835 return 1;
836
837 c1 = ( str1 != aString1.end() ) ? *str1 : wxUniChar( 0 );
838 c2 = ( str2 != aString2.end() ) ? *str2 : wxUniChar( 0 );
839 }
840
841 // Any numerical comparisons to here are identical.
842 if( aIgnoreCase )
843 {
844 if( c1 != c2 )
845 {
846 wxUniChar uc1 = wxToupper( c1 );
847 wxUniChar uc2 = wxToupper( c2 );
848
849 if( uc1 != uc2 )
850 return uc1 < uc2 ? -1 : 1;
851 }
852 }
853 else
854 {
855 if( c1 < c2 )
856 return -1;
857
858 if( c1 > c2 )
859 return 1;
860 }
861
862 if( str1 != aString1.end() )
863 ++str1;
864
865 if( str2 != aString2.end() )
866 ++str2;
867 }
868
869 if( str1 == aString1.end() && str2 != aString2.end() )
870 {
871 return -1; // Identical to here but aString1 is longer.
872 }
873 else if( str1 != aString1.end() && str2 == aString2.end() )
874 {
875 return 1; // Identical to here but aString2 is longer.
876 }
877
878 return 0;
879}
880
881
882bool WildCompareString( const wxString& pattern, const wxString& string_to_tst,
883 bool case_sensitive )
884{
885 const wxChar* cp = nullptr;
886 const wxChar* mp = nullptr;
887 const wxChar* wild = nullptr;
888 const wxChar* str = nullptr;
889 wxString _pattern, _string_to_tst;
890
891 if( case_sensitive )
892 {
893 wild = pattern.GetData();
894 str = string_to_tst.GetData();
895 }
896 else
897 {
898 _pattern = pattern;
899 _pattern.MakeUpper();
900 _string_to_tst = string_to_tst;
901 _string_to_tst.MakeUpper();
902 wild = _pattern.GetData();
903 str = _string_to_tst.GetData();
904 }
905
906 while( ( *str ) && ( *wild != '*' ) )
907 {
908 if( ( *wild != *str ) && ( *wild != '?' ) )
909 return false;
910
911 wild++;
912 str++;
913 }
914
915 while( *str )
916 {
917 if( *wild == '*' )
918 {
919 if( !*++wild )
920 return true;
921
922 mp = wild;
923 cp = str + 1;
924 }
925 else if( ( *wild == *str ) || ( *wild == '?' ) )
926 {
927 wild++;
928 str++;
929 }
930 else
931 {
932 wild = mp;
933 str = cp++;
934 }
935 }
936
937 while( *wild == '*' )
938 {
939 wild++;
940 }
941
942 return !*wild;
943}
944
945
946bool ApplyModifier( double& value, const wxString& aString )
947{
949 static const wxString modifiers( wxT( "pnuµμmkKM" ) );
950
951 if( !aString.length() )
952 return false;
953
954 wxChar modifier;
955 wxString units;
956
957 if( modifiers.Find( aString[ 0 ] ) >= 0 )
958 {
959 modifier = aString[ 0 ];
960 units = aString.Mid( 1 ).Trim();
961 }
962 else
963 {
964 modifier = ' ';
965 units = aString.Mid( 0 ).Trim();
966 }
967
968 if( units.length()
969 && !units.IsSameAs( wxT( "F" ), false )
970 && !units.IsSameAs( wxT( "hz" ), false )
971 && !units.IsSameAs( wxT( "W" ), false )
972 && !units.IsSameAs( wxT( "V" ), false )
973 && !units.IsSameAs( wxT( "A" ), false )
974 && !units.IsSameAs( wxT( "H" ), false ) )
975 {
976 return false;
977 }
978
979 if( modifier == 'p' )
980 value *= 1.0e-12;
981 if( modifier == 'n' )
982 value *= 1.0e-9;
983 else if( modifier == 'u' || modifier == wxS( "µ" )[0] || modifier == wxS( "μ" )[0] )
984 value *= 1.0e-6;
985 else if( modifier == 'm' )
986 value *= 1.0e-3;
987 else if( modifier == 'k' || modifier == 'K' )
988 value *= 1.0e3;
989 else if( modifier == 'M' )
990 value *= 1.0e6;
991 else if( modifier == 'G' )
992 value *= 1.0e9;
993
994 return true;
995}
996
997
998bool convertSeparators( wxString* value )
999{
1000 // Note: fetching the decimal separtor from the current locale isn't a silver bullet because
1001 // it assumes the current computer's locale is the same as the locale the schematic was
1002 // authored in -- something that isn't true, for instance, when sharing designs through
1003 // DIYAudio.com.
1004 //
1005 // Some values are self-describing: multiple instances of a single separator character must be
1006 // thousands separators; a single instance of each character must be a thousands separator
1007 // followed by a decimal separator; etc.
1008 //
1009 // Only when presented with an ambiguous value do we fall back on the current locale.
1010
1011 value->Replace( wxS( " " ), wxEmptyString );
1012
1013 wxChar ambiguousSeparator = '?';
1014 wxChar thousandsSeparator = '?';
1015 bool thousandsSeparatorFound = false;
1016 wxChar decimalSeparator = '?';
1017 bool decimalSeparatorFound = false;
1018 int digits = 0;
1019
1020 for( int ii = (int) value->length() - 1; ii >= 0; --ii )
1021 {
1022 wxChar c = value->GetChar( ii );
1023
1024 if( c >= '0' && c <= '9' )
1025 {
1026 digits += 1;
1027 }
1028 else if( c == '.' || c == ',' )
1029 {
1030 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1031 {
1032 // We've previously found a non-ambiguous separator...
1033
1034 if( c == decimalSeparator )
1035 {
1036 if( thousandsSeparatorFound )
1037 return false; // decimal before thousands
1038 else if( decimalSeparatorFound )
1039 return false; // more than one decimal
1040 else
1041 decimalSeparatorFound = true;
1042 }
1043 else if( c == thousandsSeparator )
1044 {
1045 if( digits != 3 )
1046 return false; // thousands not followed by 3 digits
1047 else
1048 thousandsSeparatorFound = true;
1049 }
1050 }
1051 else if( ambiguousSeparator != '?' )
1052 {
1053 // We've previously found a separator, but we don't know for sure which...
1054
1055 if( c == ambiguousSeparator )
1056 {
1057 // They both must be thousands separators
1058 thousandsSeparator = ambiguousSeparator;
1059 thousandsSeparatorFound = true;
1060 decimalSeparator = c == '.' ? ',' : '.';
1061 }
1062 else
1063 {
1064 // The first must have been a decimal, and this must be a thousands.
1065 decimalSeparator = ambiguousSeparator;
1066 decimalSeparatorFound = true;
1067 thousandsSeparator = c;
1068 thousandsSeparatorFound = true;
1069 }
1070 }
1071 else
1072 {
1073 // This is the first separator...
1074
1075 // If it's preceeded by a '0' (only), or if it's followed by some number of
1076 // digits not equal to 3, then it -must- be a decimal separator.
1077 //
1078 // In all other cases we don't really know what it is yet.
1079
1080 if( ( ii == 1 && value->GetChar( 0 ) == '0' ) || digits != 3 )
1081 {
1082 decimalSeparator = c;
1083 decimalSeparatorFound = true;
1084 thousandsSeparator = c == '.' ? ',' : '.';
1085 }
1086 else
1087 {
1088 ambiguousSeparator = c;
1089 }
1090 }
1091
1092 digits = 0;
1093 }
1094 else
1095 {
1096 digits = 0;
1097 }
1098 }
1099
1100 // If we found nothing difinitive then we have to look at the current locale
1101 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1102 {
1103 const struct lconv* lc = localeconv();
1104
1105 decimalSeparator = lc->decimal_point[0];
1106 thousandsSeparator = decimalSeparator == '.' ? ',' : '.';
1107 }
1108
1109 // Convert to C-locale
1110 value->Replace( thousandsSeparator, wxEmptyString );
1111 value->Replace( decimalSeparator, '.' );
1112
1113 return true;
1114}
1115
1116
1117int ValueStringCompare( const wxString& strFWord, const wxString& strSWord )
1118{
1119 // Compare unescaped text
1120 wxString fWord = UnescapeString( strFWord );
1121 wxString sWord = UnescapeString( strSWord );
1122
1123 // The different sections of the two strings
1124 wxString strFWordBeg, strFWordMid, strFWordEnd;
1125 wxString strSWordBeg, strSWordMid, strSWordEnd;
1126
1127 // Split the two strings into separate parts
1128 SplitString( fWord, &strFWordBeg, &strFWordMid, &strFWordEnd );
1129 SplitString( sWord, &strSWordBeg, &strSWordMid, &strSWordEnd );
1130
1131 // Compare the Beginning section of the strings
1132 int isEqual = strFWordBeg.CmpNoCase( strSWordBeg );
1133
1134 if( isEqual > 0 )
1135 {
1136 return 1;
1137 }
1138 else if( isEqual < 0 )
1139 {
1140 return -1;
1141 }
1142 else
1143 {
1144 // If the first sections are equal compare their digits
1145 double lFirstNumber = 0;
1146 double lSecondNumber = 0;
1147 bool endingIsModifier = false;
1148
1149 convertSeparators( &strFWordMid );
1150 convertSeparators( &strSWordMid );
1151
1152 LOCALE_IO toggle; // toggles on, then off, the C locale.
1153
1154 strFWordMid.ToDouble( &lFirstNumber );
1155 strSWordMid.ToDouble( &lSecondNumber );
1156
1157 endingIsModifier |= ApplyModifier( lFirstNumber, strFWordEnd );
1158 endingIsModifier |= ApplyModifier( lSecondNumber, strSWordEnd );
1159
1160 if( lFirstNumber > lSecondNumber )
1161 return 1;
1162 else if( lFirstNumber < lSecondNumber )
1163 return -1;
1164 // If the first two sections are equal and the endings are modifiers then compare them
1165 else if( !endingIsModifier )
1166 return strFWordEnd.CmpNoCase( strSWordEnd );
1167 // Ran out of things to compare; they must match
1168 else
1169 return 0;
1170 }
1171}
1172
1173
1174int SplitString( const wxString& strToSplit,
1175 wxString* strBeginning,
1176 wxString* strDigits,
1177 wxString* strEnd )
1178{
1179 static const wxString separators( wxT( ".," ) );
1180
1181 // Clear all the return strings
1182 strBeginning->Empty();
1183 strDigits->Empty();
1184 strEnd->Empty();
1185
1186 // There no need to do anything if the string is empty
1187 if( strToSplit.length() == 0 )
1188 return 0;
1189
1190 // Starting at the end of the string look for the first digit
1191 int ii;
1192
1193 for( ii = (strToSplit.length() - 1); ii >= 0; ii-- )
1194 {
1195 if( wxIsdigit( strToSplit[ii] ) )
1196 break;
1197 }
1198
1199 // If there were no digits then just set the single string
1200 if( ii < 0 )
1201 {
1202 *strBeginning = strToSplit;
1203 }
1204 else
1205 {
1206 // Since there is at least one digit this is the trailing string
1207 *strEnd = strToSplit.substr( ii + 1 );
1208
1209 // Go to the end of the digits
1210 int position = ii + 1;
1211
1212 for( ; ii >= 0; ii-- )
1213 {
1214 if( !wxIsdigit( strToSplit[ii] ) && separators.Find( strToSplit[ii] ) < 0 )
1215 break;
1216 }
1217
1218 // If all that was left was digits, then just set the digits string
1219 if( ii < 0 )
1220 *strDigits = strToSplit.substr( 0, position );
1221
1222 /* We were only looking for the last set of digits everything else is
1223 * part of the preamble */
1224 else
1225 {
1226 *strDigits = strToSplit.substr( ii + 1, position - ii - 1 );
1227 *strBeginning = strToSplit.substr( 0, ii + 1 );
1228 }
1229 }
1230
1231 return 0;
1232}
1233
1234
1235int GetTrailingInt( const wxString& aStr )
1236{
1237 int number = 0;
1238 int base = 1;
1239
1240 // Trim and extract the trailing numeric part
1241 int index = aStr.Len() - 1;
1242
1243 while( index >= 0 )
1244 {
1245 const char chr = aStr.GetChar( index );
1246
1247 if( chr < '0' || chr > '9' )
1248 break;
1249
1250 number += ( chr - '0' ) * base;
1251 base *= 10;
1252 index--;
1253 }
1254
1255 return number;
1256}
1257
1258
1260{
1262}
1263
1264
1265bool ReplaceIllegalFileNameChars( std::string* aName, int aReplaceChar )
1266{
1267 bool changed = false;
1268 std::string result;
1269 result.reserve( aName->length() );
1270
1271 for( std::string::iterator it = aName->begin(); it != aName->end(); ++it )
1272 {
1273 if( strchr( illegalFileNameChars, *it ) )
1274 {
1275 if( aReplaceChar )
1276 StrPrintf( &result, "%c", aReplaceChar );
1277 else
1278 StrPrintf( &result, "%%%02x", *it );
1279
1280 changed = true;
1281 }
1282 else
1283 {
1284 result += *it;
1285 }
1286 }
1287
1288 if( changed )
1289 *aName = result;
1290
1291 return changed;
1292}
1293
1294
1295bool ReplaceIllegalFileNameChars( wxString& aName, int aReplaceChar )
1296{
1297 bool changed = false;
1298 wxString result;
1299 result.reserve( aName.Length() );
1300 wxString illWChars = GetIllegalFileNameWxChars();
1301
1302 for( wxString::iterator it = aName.begin(); it != aName.end(); ++it )
1303 {
1304 if( illWChars.Find( *it ) != wxNOT_FOUND )
1305 {
1306 if( aReplaceChar )
1307 result += aReplaceChar;
1308 else
1309 result += wxString::Format( "%%%02x", *it );
1310
1311 changed = true;
1312 }
1313 else
1314 {
1315 result += *it;
1316 }
1317 }
1318
1319 if( changed )
1320 aName = result;
1321
1322 return changed;
1323}
1324
1325
1326void wxStringSplit( const wxString& aText, wxArrayString& aStrings, wxChar aSplitter )
1327{
1328 wxString tmp;
1329
1330 for( unsigned ii = 0; ii < aText.Length(); ii++ )
1331 {
1332 if( aText[ii] == aSplitter )
1333 {
1334 aStrings.Add( tmp );
1335 tmp.Clear();
1336 }
1337 else
1338 {
1339 tmp << aText[ii];
1340 }
1341 }
1342
1343 if( !tmp.IsEmpty() )
1344 aStrings.Add( tmp );
1345}
1346
1347
1348void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed )
1349{
1350 struct lconv* lc = localeconv();
1351 char sep = lc->decimal_point[0];
1352 unsigned sep_pos = aStringValue.Find( sep );
1353
1354 if( sep_pos > 0 )
1355 {
1356 // We want to keep at least aTrailingZeroAllowed digits after the separator
1357 unsigned min_len = sep_pos + aTrailingZeroAllowed + 1;
1358
1359 while( aStringValue.Len() > min_len )
1360 {
1361 if( aStringValue.Last() == '0' )
1362 aStringValue.RemoveLast();
1363 else
1364 break;
1365 }
1366 }
1367}
1368
1369
1370std::string FormatDouble2Str( double aValue )
1371{
1372 std::string buf;
1373
1374 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1375 {
1376 buf = fmt::format( "{:.16f}", aValue );
1377
1378 // remove trailing zeros (and the decimal marker if needed)
1379 while( !buf.empty() && buf[buf.size() - 1] == '0' )
1380 {
1381 buf.pop_back();
1382 }
1383
1384 // if the value was really small
1385 // we may have just stripped all the zeros after the decimal
1386 if( buf[buf.size() - 1] == '.' )
1387 {
1388 buf.pop_back();
1389 }
1390 }
1391 else
1392 {
1393 buf = fmt::format( "{:.10g}", aValue );
1394 }
1395
1396 return buf;
1397}
1398
1399
1400std::string UIDouble2Str( double aValue )
1401{
1402 char buf[50];
1403 int len;
1404
1405 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1406 {
1407 // For these small values, %f works fine,
1408 // and %g gives an exponent
1409 len = snprintf( buf, sizeof(buf), "%.16f", aValue );
1410
1411 while( --len > 0 && buf[len] == '0' )
1412 buf[len] = '\0';
1413
1414 if( buf[len] == '.' || buf[len] == ',' )
1415 buf[len] = '\0';
1416 else
1417 ++len;
1418 }
1419 else
1420 {
1421 // For these values, %g works fine, and sometimes %f
1422 // gives a bad value (try aValue = 1.222222222222, with %.16f format!)
1423 len = snprintf( buf, sizeof(buf), "%.10g", aValue );
1424 }
1425
1426 return std::string( buf, len );
1427}
1428
1429
1430wxString From_UTF8( const char* cstring )
1431{
1432 // Convert an expected UTF8 encoded C string to a wxString
1433 wxString line = wxString::FromUTF8( cstring );
1434
1435 if( line.IsEmpty() ) // happens when cstring is not a valid UTF8 sequence
1436 {
1437 line = wxConvCurrent->cMB2WC( cstring ); // try to use locale conversion
1438
1439 if( line.IsEmpty() )
1440 line = wxString::From8BitData( cstring ); // try to use native string
1441 }
1442
1443 return line;
1444}
1445
1446
1447wxString From_UTF8( const std::string& aString )
1448{
1449 // Convert an expected UTF8 encoded std::string to a wxString
1450 wxString line = wxString::FromUTF8( aString );
1451
1452 if( line.IsEmpty() ) // happens when aString is not a valid UTF8 sequence
1453 {
1454 line = wxConvCurrent->cMB2WC( aString.c_str() ); // try to use locale conversion
1455
1456 if( line.IsEmpty() )
1457 line = wxString::From8BitData( aString.c_str() ); // try to use native string
1458 }
1459
1460 return line;
1461}
1462
1463
1464wxString NormalizeFileUri( const wxString& aFileUri )
1465{
1466 wxString uriPathAndFileName;
1467
1468 wxCHECK( aFileUri.StartsWith( wxS( "file://" ), &uriPathAndFileName ), aFileUri );
1469
1470 wxString tmp = uriPathAndFileName;
1471 wxString retv = wxS( "file://" );
1472
1473 tmp.Replace( wxS( "\\" ), wxS( "/" ) );
1474 tmp.Replace( wxS( ":" ), wxS( "" ) );
1475
1476 if( !tmp.IsEmpty() && tmp[0] != '/' )
1477 tmp = wxS( "/" ) + tmp;
1478
1479 retv += tmp;
1480
1481 return retv;
1482}
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:49
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
int StrPrintf(std::string *result, const char *format,...)
This is like sprintf() but the output is appended to a std::string instead of to a character array.
Definition: richio.cpp:68
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 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)
static const char illegalFileNameChars[]
Illegal file name characters used to ensure file names will be valid on all supported platforms.
wxString LinkifyHTML(wxString aStr)
Wraps links in HTML tags.
bool convertSeparators(wxString *value)
wxString GetIllegalFileNameWxChars()
wxString From_UTF8(const char *cstring)
bool ConvertSmartQuotesAndDashes(wxString *aString)
Convert curly quotes and em/en dashes to straight quotes and dashes.
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.
bool ReplaceIllegalFileNameChars(std::string *aName, int aReplaceChar)
Checks aName for illegal file name characters.
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 ...
std::string FormatDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 This function is intended in...
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 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.
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.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: string_utils.h:398
ESCAPE_CONTEXT
Escape/Unescape routines to safely encode reserved-characters in various contexts.
Definition: string_utils.h:52
@ CTX_FILENAME
Definition: string_utils.h:61
@ CTX_QUOTED_STR
Definition: string_utils.h:57
@ CTX_LINE
Definition: string_utils.h:59
@ CTX_NO_SPACE
Definition: string_utils.h:62
@ CTX_LIBID
Definition: string_utils.h:54
@ CTX_NETNAME
Definition: string_utils.h:53
@ CTX_CSV
Definition: string_utils.h:60
@ CTX_IPC
Definition: string_utils.h:56
@ CTX_LEGACY_LIBID
Definition: string_utils.h:55
@ CTX_JS_STR
Definition: string_utils.h:58