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
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
410wxString InitialCaps( const wxString& aString )
411{
412 wxArrayString words;
413 wxString result;
414
415 wxStringSplit( aString, words, ' ' );
416
417 result.reserve( aString.length() );
418
419 for( const wxString& word : words )
420 {
421 if( result.IsEmpty() )
422 result += word.Capitalize();
423 else
424 result += wxT( " " ) + word.Lower();
425 }
426
427 return result;
428}
429
430
431int ReadDelimitedText( wxString* aDest, const char* aSource )
432{
433 std::string utf8; // utf8 but without escapes and quotes.
434 bool inside = false;
435 const char* start = aSource;
436 char cc;
437
438 while( (cc = *aSource++) != 0 )
439 {
440 if( cc == '"' )
441 {
442 if( inside )
443 break; // 2nd double quote is end of delimited text
444
445 inside = true; // first delimiter found, make note, do not copy
446 }
447
448 else if( inside )
449 {
450 if( cc == '\\' )
451 {
452 cc = *aSource++;
453
454 if( !cc )
455 break;
456
457 // do no copy the escape byte if it is followed by \ or "
458 if( cc != '"' && cc != '\\' )
459 utf8 += '\\';
460
461 utf8 += cc;
462 }
463 else
464 {
465 utf8 += cc;
466 }
467 }
468 }
469
470 *aDest = From_UTF8( utf8.c_str() );
471
472 return aSource - start;
473}
474
475
476int ReadDelimitedText( char* aDest, const char* aSource, int aDestSize )
477{
478 if( aDestSize <= 0 )
479 return 0;
480
481 bool inside = false;
482 const char* start = aSource;
483 char* limit = aDest + aDestSize - 1;
484 char cc;
485
486 while( ( cc = *aSource++ ) != 0 && aDest < limit )
487 {
488 if( cc == '"' )
489 {
490 if( inside )
491 break; // 2nd double quote is end of delimited text
492
493 inside = true; // first delimiter found, make note, do not copy
494 }
495 else if( inside )
496 {
497 if( cc == '\\' )
498 {
499 cc = *aSource++;
500
501 if( !cc )
502 break;
503
504 // do no copy the escape byte if it is followed by \ or "
505 if( cc != '"' && cc != '\\' )
506 *aDest++ = '\\';
507
508 if( aDest < limit )
509 *aDest++ = cc;
510 }
511 else
512 {
513 *aDest++ = cc;
514 }
515 }
516 }
517
518 *aDest = 0;
519
520 return aSource - start;
521}
522
523
524std::string EscapedUTF8( const wxString& aString )
525{
526 wxString str = aString;
527
528 // No new-lines allowed in quoted strings
529 str.Replace( wxT( "\r\n" ), wxT( "\r" ) );
530 str.Replace( wxT( "\n" ), wxT( "\r" ) );
531
532 std::string utf8 = TO_UTF8( aString );
533
534 std::string ret;
535
536 ret.reserve( utf8.length() + 2 );
537
538 ret += '"';
539
540 for( std::string::const_iterator it = utf8.begin(); it!=utf8.end(); ++it )
541 {
542 // this escaping strategy is designed to be compatible with ReadDelimitedText():
543 if( *it == '"' )
544 {
545 ret += '\\';
546 ret += '"';
547 }
548 else if( *it == '\\' )
549 {
550 ret += '\\'; // double it up
551 ret += '\\';
552 }
553 else
554 {
555 ret += *it;
556 }
557 }
558
559 ret += '"';
560
561 return ret;
562}
563
564
565wxString EscapeHTML( const wxString& aString )
566{
567 wxString converted;
568
569 converted.reserve( aString.length() );
570
571 for( wxUniChar c : aString )
572 {
573 if( c == '\"' )
574 converted += wxT( "&quot;" );
575 else if( c == '\'' )
576 converted += wxT( "&apos;" );
577 else if( c == '&' )
578 converted += wxT( "&amp;" );
579 else if( c == '<' )
580 converted += wxT( "&lt;" );
581 else if( c == '>' )
582 converted += wxT( "&gt;" );
583 else
584 converted += c;
585 }
586
587 return converted;
588}
589
590
591wxString UnescapeHTML( const wxString& aString )
592{
593 // clang-format off
594 static const std::map<wxString, wxString> c_replacements = {
595 { wxS( "quot" ), wxS( "\"" ) },
596 { wxS( "apos" ), wxS( "'" ) },
597 { wxS( "amp" ), wxS( "&" ) },
598 { wxS( "lt" ), wxS( "<" ) },
599 { wxS( "gt" ), wxS( ">" ) }
600 };
601 // clang-format on
602
603 // Construct regex
604 wxString regexStr = "&(#(\\d*)|#x([a-zA-Z0-9]{4})";
605
606 for( auto& [key, value] : c_replacements )
607 regexStr << '|' << key;
608
609 regexStr << ");";
610
611 wxRegEx regex( regexStr );
612
613 // Process matches
614 size_t start = 0;
615 size_t len = 0;
616
617 wxString result;
618 wxString str = aString;
619
620 while( regex.Matches( str ) )
621 {
622 std::vector<wxString> matches;
623 regex.GetMatch( &start, &len );
624
625 result << str.Left( start );
626
627 wxString code = regex.GetMatch( str, 1 );
628 wxString codeDec = regex.GetMatch( str, 2 );
629 wxString codeHex = regex.GetMatch( str, 3 );
630
631 if( !codeDec.IsEmpty() || !codeHex.IsEmpty() )
632 {
633 unsigned long codeVal = 0;
634
635 if( !codeDec.IsEmpty() )
636 codeDec.ToCULong( &codeVal );
637 else if( !codeHex.IsEmpty() )
638 codeHex.ToCULong( &codeVal, 16 );
639
640 if( codeVal != 0 )
641 result << wxUniChar( codeVal );
642 }
643 else if( auto val = get_opt( c_replacements, code ) )
644 {
645 result << *val;
646 }
647
648 str = str.Mid( start + len );
649 }
650
651 result << str;
652
653 return result;
654}
655
656
657wxString RemoveHTMLTags( const wxString& aInput )
658{
659 wxString str = aInput;
660 wxRegEx( wxS( "<[^>]*>" ) ).ReplaceAll( &str, wxEmptyString );
661
662 return str;
663}
664
665
666wxString LinkifyHTML( wxString aStr )
667{
668 static wxRegEx regex( wxS( "\\b(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\(\\)\\s\u00b6])" ),
669 wxRE_ICASE );
670
671 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
672
673 return aStr;
674}
675
676
677bool IsURL( wxString aStr )
678{
679 static wxRegEx regex( wxS( "(https?|ftp|file)://([-\\w+&@#/%?=~|!:,.;]*[^.,:;<>\\s\u00b6])" ),
680 wxRE_ICASE );
681
682 regex.ReplaceAll( &aStr, "<a href=\"\\0\">\\0</a>" );
683
684 return regex.Matches( aStr );
685}
686
687
688bool NoPrintableChars( const wxString& aString )
689{
690 wxString tmp = aString;
691
692 return tmp.Trim( true ).Trim( false ).IsEmpty();
693}
694
695
696int PrintableCharCount( const wxString& aString )
697{
698 int char_count = 0;
699 int overbarDepth = -1;
700 int superSubDepth = -1;
701 int braceNesting = 0;
702
703 for( auto chIt = aString.begin(), end = aString.end(); chIt < end; ++chIt )
704 {
705 if( *chIt == '\t' )
706 {
707 // We don't format tabs in bitmap text (where this is currently used), so just
708 // drop them from the count.
709 continue;
710 }
711 else if( *chIt == '^' && superSubDepth == -1 )
712 {
713 auto lookahead = chIt;
714
715 if( ++lookahead != end && *lookahead == '{' )
716 {
717 chIt = lookahead;
718 superSubDepth = braceNesting;
719 braceNesting++;
720 continue;
721 }
722 }
723 else if( *chIt == '_' && superSubDepth == -1 )
724 {
725 auto lookahead = chIt;
726
727 if( ++lookahead != end && *lookahead == '{' )
728 {
729 chIt = lookahead;
730 superSubDepth = braceNesting;
731 braceNesting++;
732 continue;
733 }
734 }
735 else if( *chIt == '~' && overbarDepth == -1 )
736 {
737 auto lookahead = chIt;
738
739 if( ++lookahead != end && *lookahead == '{' )
740 {
741 chIt = lookahead;
742 overbarDepth = braceNesting;
743 braceNesting++;
744 continue;
745 }
746 }
747 else if( *chIt == '{' )
748 {
749 braceNesting++;
750 }
751 else if( *chIt == '}' )
752 {
753 if( braceNesting > 0 )
754 braceNesting--;
755
756 if( braceNesting == superSubDepth )
757 {
758 superSubDepth = -1;
759 continue;
760 }
761
762 if( braceNesting == overbarDepth )
763 {
764 overbarDepth = -1;
765 continue;
766 }
767 }
768
769 char_count++;
770 }
771
772 return char_count;
773}
774
775
776char* StrPurge( char* text )
777{
778 static const char whitespace[] = " \t\n\r\f\v";
779
780 if( text )
781 {
782 while( *text && strchr( whitespace, *text ) )
783 ++text;
784
785 char* cp = text + strlen( text ) - 1;
786
787 while( cp >= text && strchr( whitespace, *cp ) )
788 *cp-- = '\0';
789 }
790
791 return text;
792}
793
794
795char* GetLine( FILE* File, char* Line, int* LineNum, int SizeLine )
796{
797 do {
798 if( fgets( Line, SizeLine, File ) == nullptr )
799 return nullptr;
800
801 if( LineNum )
802 *LineNum += 1;
803
804 } while( Line[0] == '#' || Line[0] == '\n' || Line[0] == '\r' || Line[0] == 0 );
805
806 strtok( Line, "\n\r" );
807 return Line;
808}
809
810
812{
813 // on msys2 variant mingw64, in fmt::format the %z format
814 // (offset from UTC in the ISO 8601 format, e.g. -0430) does not work,
815 // and is in fact %Z (locale-dependent time zone name or abbreviation) and breaks our date.
816 // However, on msys2 variant ucrt64, it works (this is not the same code in fmt::format)
817#if defined(__MINGW32__) && !defined(_UCRT)
818 return fmt::format( "{:%FT%T}", fmt::localtime( std::time( nullptr ) ) );
819#else
820 return fmt::format( "{:%FT%T%z}", fmt::localtime( std::time( nullptr ) ) );
821#endif
822}
823
824
825int StrNumCmp( const wxString& aString1, const wxString& aString2, bool aIgnoreCase )
826{
827 int nb1 = 0, nb2 = 0;
828
829 auto str1 = aString1.begin();
830 auto str2 = aString2.begin();
831
832 while( str1 != aString1.end() && str2 != aString2.end() )
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 != aString1.end() && wxIsdigit( *str1 ) );
848
849 do
850 {
851 c2 = *str2;
852 nb2 = nb2 * 10 + (int) c2 - '0';
853 ++str2;
854 } while( str2 != aString2.end() && wxIsdigit( *str2 ) );
855
856 if( nb1 < nb2 )
857 return -1;
858
859 if( nb1 > nb2 )
860 return 1;
861
862 c1 = ( str1 != aString1.end() ) ? *str1 : wxUniChar( 0 );
863 c2 = ( str2 != aString2.end() ) ? *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 != aString1.end() )
888 ++str1;
889
890 if( str2 != aString2.end() )
891 ++str2;
892 }
893
894 if( str1 == aString1.end() && str2 != aString2.end() )
895 {
896 return -1; // Identical to here but aString1 is longer.
897 }
898 else if( str1 != aString1.end() && str2 == aString2.end() )
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( "pnuµμmkKM" ) );
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 if( modifier == 'p' )
1005 value *= 1.0e-12;
1006 if( modifier == 'n' )
1007 value *= 1.0e-9;
1008 else if( modifier == 'u' || modifier == wxS( "µ" )[0] || modifier == wxS( "μ" )[0] )
1009 value *= 1.0e-6;
1010 else if( modifier == 'm' )
1011 value *= 1.0e-3;
1012 else if( modifier == 'k' || modifier == 'K' )
1013 value *= 1.0e3;
1014 else if( modifier == 'M' )
1015 value *= 1.0e6;
1016 else if( modifier == 'G' )
1017 value *= 1.0e9;
1018
1019 return true;
1020}
1021
1022
1023bool convertSeparators( wxString* value )
1024{
1025 // Note: fetching the decimal separator from the current locale isn't a silver bullet because
1026 // it assumes the current computer's locale is the same as the locale the schematic was
1027 // authored in -- something that isn't true, for instance, when sharing designs through
1028 // DIYAudio.com.
1029 //
1030 // Some values are self-describing: multiple instances of a single separator character must be
1031 // thousands separators; a single instance of each character must be a thousands separator
1032 // followed by a decimal separator; etc.
1033 //
1034 // Only when presented with an ambiguous value do we fall back on the current locale.
1035
1036 value->Replace( wxS( " " ), wxEmptyString );
1037
1038 wxChar ambiguousSeparator = '?';
1039 wxChar thousandsSeparator = '?';
1040 bool thousandsSeparatorFound = false;
1041 wxChar decimalSeparator = '?';
1042 bool decimalSeparatorFound = false;
1043 int digits = 0;
1044
1045 for( int ii = (int) value->length() - 1; ii >= 0; --ii )
1046 {
1047 wxChar c = value->GetChar( ii );
1048
1049 if( c >= '0' && c <= '9' )
1050 {
1051 digits += 1;
1052 }
1053 else if( c == '.' || c == ',' )
1054 {
1055 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1056 {
1057 // We've previously found a non-ambiguous separator...
1058
1059 if( c == decimalSeparator )
1060 {
1061 if( thousandsSeparatorFound )
1062 return false; // decimal before thousands
1063 else if( decimalSeparatorFound )
1064 return false; // more than one decimal
1065 else
1066 decimalSeparatorFound = true;
1067 }
1068 else if( c == thousandsSeparator )
1069 {
1070 if( digits != 3 )
1071 return false; // thousands not followed by 3 digits
1072 else
1073 thousandsSeparatorFound = true;
1074 }
1075 }
1076 else if( ambiguousSeparator != '?' )
1077 {
1078 // We've previously found a separator, but we don't know for sure which...
1079
1080 if( c == ambiguousSeparator )
1081 {
1082 // They both must be thousands separators
1083 thousandsSeparator = ambiguousSeparator;
1084 thousandsSeparatorFound = true;
1085 decimalSeparator = c == '.' ? ',' : '.';
1086 }
1087 else
1088 {
1089 // The first must have been a decimal, and this must be a thousands.
1090 decimalSeparator = ambiguousSeparator;
1091 decimalSeparatorFound = true;
1092 thousandsSeparator = c;
1093 thousandsSeparatorFound = true;
1094 }
1095 }
1096 else
1097 {
1098 // This is the first separator...
1099
1100 // If it's preceded by a '0' (only), or if it's followed by some number of
1101 // digits not equal to 3, then it -must- be a decimal separator.
1102 //
1103 // In all other cases we don't really know what it is yet.
1104
1105 if( ( ii == 1 && value->GetChar( 0 ) == '0' ) || digits != 3 )
1106 {
1107 decimalSeparator = c;
1108 decimalSeparatorFound = true;
1109 thousandsSeparator = c == '.' ? ',' : '.';
1110 }
1111 else
1112 {
1113 ambiguousSeparator = c;
1114 }
1115 }
1116
1117 digits = 0;
1118 }
1119 else
1120 {
1121 digits = 0;
1122 }
1123 }
1124
1125 // If we found nothing definitive then we have to look at the current locale
1126 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1127 {
1128 const struct lconv* lc = localeconv();
1129
1130 decimalSeparator = lc->decimal_point[0];
1131 thousandsSeparator = decimalSeparator == '.' ? ',' : '.';
1132 }
1133
1134 // Convert to C-locale
1135 value->Replace( thousandsSeparator, wxEmptyString );
1136 value->Replace( decimalSeparator, '.' );
1137
1138 return true;
1139}
1140
1141
1142int ValueStringCompare( const wxString& strFWord, const wxString& strSWord )
1143{
1144 // Compare unescaped text
1145 wxString fWord = UnescapeString( strFWord );
1146 wxString sWord = UnescapeString( strSWord );
1147
1148 // The different sections of the two strings
1149 wxString strFWordBeg, strFWordMid, strFWordEnd;
1150 wxString strSWordBeg, strSWordMid, strSWordEnd;
1151
1152 // Split the two strings into separate parts
1153 SplitString( fWord, &strFWordBeg, &strFWordMid, &strFWordEnd );
1154 SplitString( sWord, &strSWordBeg, &strSWordMid, &strSWordEnd );
1155
1156 // Compare the Beginning section of the strings
1157 int isEqual = strFWordBeg.CmpNoCase( strSWordBeg );
1158
1159 if( isEqual > 0 )
1160 {
1161 return 1;
1162 }
1163 else if( isEqual < 0 )
1164 {
1165 return -1;
1166 }
1167 else
1168 {
1169 // If the first sections are equal compare their digits
1170 double lFirstNumber = 0;
1171 double lSecondNumber = 0;
1172 bool endingIsModifier = false;
1173
1174 convertSeparators( &strFWordMid );
1175 convertSeparators( &strSWordMid );
1176
1177 strFWordMid.ToCDouble( &lFirstNumber );
1178 strSWordMid.ToCDouble( &lSecondNumber );
1179
1180 endingIsModifier |= ApplyModifier( lFirstNumber, strFWordEnd );
1181 endingIsModifier |= ApplyModifier( lSecondNumber, strSWordEnd );
1182
1183 if( lFirstNumber > lSecondNumber )
1184 return 1;
1185 else if( lFirstNumber < lSecondNumber )
1186 return -1;
1187 // If the first two sections are equal and the endings are modifiers then compare them
1188 else if( !endingIsModifier )
1189 return strFWordEnd.CmpNoCase( strSWordEnd );
1190 // Ran out of things to compare; they must match
1191 else
1192 return 0;
1193 }
1194}
1195
1196
1197int SplitString( const wxString& strToSplit,
1198 wxString* strBeginning,
1199 wxString* strDigits,
1200 wxString* strEnd )
1201{
1202 static const wxString separators( wxT( ".," ) );
1203
1204 // Clear all the return strings
1205 strBeginning->Empty();
1206 strDigits->Empty();
1207 strEnd->Empty();
1208
1209 // There no need to do anything if the string is empty
1210 if( strToSplit.length() == 0 )
1211 return 0;
1212
1213 // Starting at the end of the string look for the first digit
1214 int ii;
1215
1216 for( ii = (strToSplit.length() - 1); ii >= 0; ii-- )
1217 {
1218 if( wxIsdigit( strToSplit[ii] ) )
1219 break;
1220 }
1221
1222 // If there were no digits then just set the single string
1223 if( ii < 0 )
1224 {
1225 *strBeginning = strToSplit;
1226 }
1227 else
1228 {
1229 // Since there is at least one digit this is the trailing string
1230 *strEnd = strToSplit.substr( ii + 1 );
1231
1232 // Go to the end of the digits
1233 int position = ii + 1;
1234
1235 for( ; ii >= 0; ii-- )
1236 {
1237 if( !wxIsdigit( strToSplit[ii] ) && separators.Find( strToSplit[ii] ) < 0 )
1238 break;
1239 }
1240
1241 // If all that was left was digits, then just set the digits string
1242 if( ii < 0 )
1243 *strDigits = strToSplit.substr( 0, position );
1244
1245 /* We were only looking for the last set of digits everything else is
1246 * part of the preamble */
1247 else
1248 {
1249 *strDigits = strToSplit.substr( ii + 1, position - ii - 1 );
1250 *strBeginning = strToSplit.substr( 0, ii + 1 );
1251 }
1252 }
1253
1254 return 0;
1255}
1256
1257
1258int GetTrailingInt( const wxString& aStr )
1259{
1260 int number = 0;
1261 int base = 1;
1262
1263 // Trim and extract the trailing numeric part
1264 int index = aStr.Len() - 1;
1265
1266 while( index >= 0 )
1267 {
1268 const char chr = aStr.GetChar( index );
1269
1270 if( chr < '0' || chr > '9' )
1271 break;
1272
1273 number += ( chr - '0' ) * base;
1274 base *= 10;
1275 index--;
1276 }
1277
1278 return number;
1279}
1280
1281
1283{
1285}
1286
1287
1288bool ReplaceIllegalFileNameChars( std::string* aName, int aReplaceChar )
1289{
1290 bool changed = false;
1291 std::string result;
1292 result.reserve( aName->length() );
1293
1294 for( std::string::iterator it = aName->begin(); it != aName->end(); ++it )
1295 {
1296 if( strchr( illegalFileNameChars, *it ) )
1297 {
1298 if( aReplaceChar )
1299 StrPrintf( &result, "%c", aReplaceChar );
1300 else
1301 StrPrintf( &result, "%%%02x", *it );
1302
1303 changed = true;
1304 }
1305 else
1306 {
1307 result += *it;
1308 }
1309 }
1310
1311 if( changed )
1312 *aName = std::move( result );
1313
1314 return changed;
1315}
1316
1317
1318bool ReplaceIllegalFileNameChars( wxString& aName, int aReplaceChar )
1319{
1320 bool changed = false;
1321 wxString result;
1322 result.reserve( aName.Length() );
1323 wxString illWChars = GetIllegalFileNameWxChars();
1324
1325 for( wxString::iterator it = aName.begin(); it != aName.end(); ++it )
1326 {
1327 if( illWChars.Find( *it ) != wxNOT_FOUND )
1328 {
1329 if( aReplaceChar )
1330 result += aReplaceChar;
1331 else
1332 result += wxString::Format( "%%%02x", *it );
1333
1334 changed = true;
1335 }
1336 else
1337 {
1338 result += *it;
1339 }
1340 }
1341
1342 if( changed )
1343 aName = std::move( result );
1344
1345 return changed;
1346}
1347
1348
1349void wxStringSplit( const wxString& aText, wxArrayString& aStrings, wxChar aSplitter )
1350{
1351 wxString tmp;
1352
1353 for( unsigned ii = 0; ii < aText.Length(); ii++ )
1354 {
1355 if( aText[ii] == aSplitter )
1356 {
1357 aStrings.Add( tmp );
1358 tmp.Clear();
1359 }
1360 else
1361 {
1362 tmp << aText[ii];
1363 }
1364 }
1365
1366 if( !tmp.IsEmpty() )
1367 aStrings.Add( tmp );
1368}
1369
1370
1371void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed )
1372{
1373 struct lconv* lc = localeconv();
1374 char sep = lc->decimal_point[0];
1375 unsigned sep_pos = aStringValue.Find( sep );
1376
1377 if( sep_pos > 0 )
1378 {
1379 // We want to keep at least aTrailingZeroAllowed digits after the separator
1380 unsigned min_len = sep_pos + aTrailingZeroAllowed + 1;
1381
1382 while( aStringValue.Len() > min_len )
1383 {
1384 if( aStringValue.Last() == '0' )
1385 aStringValue.RemoveLast();
1386 else
1387 break;
1388 }
1389 }
1390}
1391
1392
1393std::string FormatDouble2Str( double aValue )
1394{
1395 std::string buf;
1396
1397 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1398 {
1399 buf = fmt::format( "{:.16f}", aValue );
1400
1401 // remove trailing zeros (and the decimal marker if needed)
1402 while( !buf.empty() && buf[buf.size() - 1] == '0' )
1403 {
1404 buf.pop_back();
1405 }
1406
1407 // if the value was really small
1408 // we may have just stripped all the zeros after the decimal
1409 if( buf[buf.size() - 1] == '.' )
1410 {
1411 buf.pop_back();
1412 }
1413 }
1414 else
1415 {
1416 buf = fmt::format( "{:.10g}", aValue );
1417 }
1418
1419 return buf;
1420}
1421
1422
1423std::string UIDouble2Str( double aValue )
1424{
1425 char buf[50];
1426 int len;
1427
1428 if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 )
1429 {
1430 // For these small values, %f works fine,
1431 // and %g gives an exponent
1432 len = snprintf( buf, sizeof( buf ), "%.16f", aValue );
1433
1434 while( --len > 0 && buf[len] == '0' )
1435 buf[len] = '\0';
1436
1437 if( buf[len] == '.' || buf[len] == ',' )
1438 buf[len] = '\0';
1439 else
1440 ++len;
1441 }
1442 else
1443 {
1444 // For these values, %g works fine, and sometimes %f
1445 // gives a bad value (try aValue = 1.222222222222, with %.16f format!)
1446 len = snprintf( buf, sizeof( buf ), "%.10g", aValue );
1447 }
1448
1449 return std::string( buf, len );
1450}
1451
1452
1453wxString From_UTF8( const char* cstring )
1454{
1455 // Convert an expected UTF8 encoded C string to a wxString
1456 wxString line = wxString::FromUTF8( cstring );
1457
1458 if( line.IsEmpty() ) // happens when cstring is not a valid UTF8 sequence
1459 {
1460 line = wxConvCurrent->cMB2WC( cstring ); // try to use locale conversion
1461
1462 if( line.IsEmpty() )
1463 line = wxString::From8BitData( cstring ); // try to use native string
1464 }
1465
1466 return line;
1467}
1468
1469
1470wxString From_UTF8( const std::string& aString )
1471{
1472 // Convert an expected UTF8 encoded std::string to a wxString
1473 wxString line = wxString::FromUTF8( aString );
1474
1475 if( line.IsEmpty() ) // happens when aString is not a valid UTF8 sequence
1476 {
1477 line = wxConvCurrent->cMB2WC( aString.c_str() ); // try to use locale conversion
1478
1479 if( line.IsEmpty() )
1480 line = wxString::From8BitData( aString.c_str() ); // try to use native string
1481 }
1482
1483 return line;
1484}
1485
1486
1487wxString NormalizeFileUri( const wxString& aFileUri )
1488{
1489 wxString uriPathAndFileName;
1490
1491 wxCHECK( aFileUri.StartsWith( wxS( "file://" ), &uriPathAndFileName ), aFileUri );
1492
1493 wxString tmp = uriPathAndFileName;
1494 wxString retv = wxS( "file://" );
1495
1496 tmp.Replace( wxS( "\\" ), wxS( "/" ) );
1497 tmp.Replace( wxS( ":" ), wxS( "" ) );
1498
1499 if( !tmp.IsEmpty() && tmp[0] != '/' )
1500 tmp = wxS( "/" ) + tmp;
1501
1502 retv += tmp;
1503
1504 return retv;
1505}
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:71
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 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.
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.
Definition: string_utils.h:429
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
VECTOR2I end