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