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