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