KiCad PCB EDA Suite
json_settings.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) 2020 Jon Evans <[email protected]>
5 * Copyright (C) 2020-2022 KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21#include <algorithm>
22#include <fstream>
23#include <iomanip>
24#include <utility>
25#include <sstream>
26
27#include <locale_io.h>
28#include <gal/color4d.h>
32#include <settings/parameters.h>
33#include <wx/config.h>
34#include <wx/debug.h>
35#include <wx/fileconf.h>
36#include <wx/filename.h>
37#include <wx/log.h>
38#include <wx/stdstream.h>
39#include <wx/wfstream.h>
40
41const wxChar* const traceSettings = wxT( "KICAD_SETTINGS" );
42
43
44nlohmann::json::json_pointer JSON_SETTINGS_INTERNALS::PointerFromString( std::string aPath )
45{
46 std::replace( aPath.begin(), aPath.end(), '.', '/' );
47 aPath.insert( 0, "/" );
48
49 nlohmann::json::json_pointer p;
50
51 try
52 {
53 p = nlohmann::json::json_pointer( aPath );
54 }
55 catch( ... )
56 {
57 wxASSERT_MSG( false, wxT( "Invalid pointer path in PointerFromString!" ) );
58 }
59
60 return p;
61}
62
63
64JSON_SETTINGS::JSON_SETTINGS( const wxString& aFilename, SETTINGS_LOC aLocation,
65 int aSchemaVersion, bool aCreateIfMissing, bool aCreateIfDefault,
66 bool aWriteFile ) :
67 m_filename( aFilename ),
68 m_legacy_filename( "" ),
69 m_location( aLocation ),
70 m_createIfMissing( aCreateIfMissing ),
71 m_createIfDefault( aCreateIfDefault ),
72 m_writeFile( aWriteFile ),
73 m_deleteLegacyAfterMigration( true ),
74 m_resetParamsIfMissing( true ),
75 m_schemaVersion( aSchemaVersion ),
76 m_manager( nullptr )
77{
78 m_internals = std::make_unique<JSON_SETTINGS_INTERNALS>();
79
80 try
81 {
82 m_internals->SetFromString( "meta.filename", GetFullFilename() );
83 }
84 catch( ... )
85 {
86 wxLogTrace( traceSettings, wxT( "Error: Could not create filename field for %s" ),
88 }
89
90
91 m_params.emplace_back(
92 new PARAM<int>( "meta.version", &m_schemaVersion, m_schemaVersion, true ) );
93}
94
95
97{
98 for( auto param: m_params )
99 delete param;
100
101 m_params.clear();
102}
103
104
106{
107 return wxString( m_filename + "." + getFileExt() );
108}
109
110
111nlohmann::json& JSON_SETTINGS::At( const std::string& aPath )
112{
113 return m_internals->At( aPath );
114}
115
116
117bool JSON_SETTINGS::Contains( const std::string& aPath ) const
118{
119 return m_internals->contains( JSON_SETTINGS_INTERNALS::PointerFromString( aPath ) );
120}
121
122
124{
125 return m_internals.get();
126}
127
128
130{
131 for( auto param : m_params )
132 {
133 try
134 {
135 param->Load( this, m_resetParamsIfMissing );
136 }
137 catch( ... )
138 {
139 // Skip unreadable parameters in file
140 wxLogTrace( traceSettings, wxT( "param '%s' load err" ), param->GetJsonPath().c_str() );
141 }
142 }
143}
144
145
146bool JSON_SETTINGS::LoadFromFile( const wxString& aDirectory )
147{
148 // First, load all params to default values
149 m_internals->clear();
150 Load();
151
152 bool success = true;
153 bool migrated = false;
154 bool legacy_migrated = false;
155
156 LOCALE_IO locale;
157
158 auto migrateFromLegacy = [&] ( wxFileName& aPath ) {
159 // Backup and restore during migration so that the original can be mutated if convenient
160 bool backed_up = false;
161 wxFileName temp;
162
163 if( aPath.IsDirWritable() )
164 {
165 temp.AssignTempFileName( aPath.GetFullPath() );
166
167 if( !wxCopyFile( aPath.GetFullPath(), temp.GetFullPath() ) )
168 {
169 wxLogTrace( traceSettings, wxT( "%s: could not create temp file for migration" ),
170 GetFullFilename() );
171 }
172 else
173 backed_up = true;
174 }
175
176 // Silence popups if legacy file is read-only
177 wxLogNull doNotLog;
178
179 wxConfigBase::DontCreateOnDemand();
180 auto cfg = std::make_unique<wxFileConfig>( wxT( "" ), wxT( "" ), aPath.GetFullPath() );
181
182 // If migrate fails or is not implemented, fall back to built-in defaults that were
183 // already loaded above
184 if( !MigrateFromLegacy( cfg.get() ) )
185 {
186 success = false;
187 wxLogTrace( traceSettings,
188 wxT( "%s: migrated; not all settings were found in legacy file" ),
189 GetFullFilename() );
190 }
191 else
192 {
193 success = true;
194 wxLogTrace( traceSettings, wxT( "%s: migrated from legacy format" ), GetFullFilename() );
195 }
196
197 if( backed_up )
198 {
199 cfg.reset();
200
201 if( !wxCopyFile( temp.GetFullPath(), aPath.GetFullPath() ) )
202 {
203 wxLogTrace( traceSettings,
204 wxT( "migrate; copy temp file %s to %s failed" ),
205 temp.GetFullPath(), aPath.GetFullPath() );
206 }
207
208 if( !wxRemoveFile( temp.GetFullPath() ) )
209 {
210 wxLogTrace( traceSettings,
211 wxT( "migrate; failed to remove temp file %s" ),
212 temp.GetFullPath() );
213 }
214 }
215
216 // Either way, we want to clean up the old file afterwards
217 legacy_migrated = true;
218 };
219
220 wxFileName path;
221
222 if( aDirectory.empty() )
223 {
224 path.Assign( m_filename );
225 path.SetExt( getFileExt() );
226 }
227 else
228 {
229 wxString dir( aDirectory );
230 path.Assign( dir, m_filename, getFileExt() );
231 }
232
233 if( !path.Exists() )
234 {
235 // Case 1: legacy migration, no .json extension yet
236 path.SetExt( getLegacyFileExt() );
237
238 if( path.Exists() )
239 {
240 migrateFromLegacy( path );
241 }
242 // Case 2: legacy filename is different from new one
243 else if( !m_legacy_filename.empty() )
244 {
245 path.SetName( m_legacy_filename );
246
247 if( path.Exists() )
248 migrateFromLegacy( path );
249 }
250 else
251 {
252 success = false;
253 }
254 }
255 else
256 {
257 if( !path.IsFileWritable() )
258 m_writeFile = false;
259
260 try
261 {
262 wxFFileInputStream fp( path.GetFullPath(), wxT( "rt" ) );
263 wxStdInputStream fstream( fp );
264
265 if( fp.IsOk() )
266 {
267 *static_cast<nlohmann::json*>( m_internals.get() ) =
268 nlohmann::json::parse( fstream, nullptr,
269 /* allow_exceptions = */ true,
270 /* ignore_comments = */ true );
271
272 // If parse succeeds, check if schema migration is required
273 int filever = -1;
274
275 try
276 {
277 filever = m_internals->Get<int>( "meta.version" );
278 }
279 catch( ... )
280 {
281 wxLogTrace( traceSettings, wxT( "%s: file version could not be read!" ),
282 GetFullFilename() );
283 success = false;
284 }
285
286 if( filever >= 0 && filever < m_schemaVersion )
287 {
288 wxLogTrace( traceSettings, wxT( "%s: attempting migration from version %d to %d" ),
289 GetFullFilename(), filever, m_schemaVersion );
290
291 if( Migrate() )
292 {
293 migrated = true;
294 }
295 else
296 {
297 wxLogTrace( traceSettings, wxT( "%s: migration failed!" ), GetFullFilename() );
298 }
299 }
300 else if( filever > m_schemaVersion )
301 {
302 wxLogTrace( traceSettings,
303 wxT( "%s: warning: file version %d is newer than latest (%d)" ),
304 GetFullFilename(), filever, m_schemaVersion );
305 }
306 }
307 else
308 {
309 wxLogTrace( traceSettings, wxT( "%s exists but can't be opened for read" ),
310 GetFullFilename() );
311 }
312 }
313 catch( nlohmann::json::parse_error& error )
314 {
315 success = false;
316 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ),
317 path.GetFullPath(), error.what() );
318 wxLogTrace( traceSettings, wxT( "Attempting migration in case file is in legacy format" ) );
319 migrateFromLegacy( path );
320 }
321 }
322
323 // Now that we have new data in the JSON structure, load the params again
324 Load();
325
326 // And finally load any nested settings
327 for( auto settings : m_nested_settings )
328 settings->LoadFromFile();
329
330 wxLogTrace( traceSettings, wxT( "Loaded <%s> with schema %d" ), GetFullFilename(), m_schemaVersion );
331
332 // If we migrated, clean up the legacy file (with no extension)
333 if( m_writeFile && ( legacy_migrated || migrated ) )
334 {
335 if( legacy_migrated && m_deleteLegacyAfterMigration && !wxRemoveFile( path.GetFullPath() ) )
336 {
337 wxLogTrace( traceSettings, wxT( "Warning: could not remove legacy file %s" ),
338 path.GetFullPath() );
339 }
340
341 // And write-out immediately so that we don't lose data if the program later crashes.
343 SaveToFile( aDirectory, true );
344 }
345
346 return success;
347}
348
349
351{
352 bool modified = false;
353
354 for( auto param : m_params )
355 {
356 modified |= !param->MatchesFile( this );
357 param->Store( this );
358 }
359
360 return modified;
361}
362
363
365{
366 for( auto param : m_params )
367 param->SetDefault();
368}
369
370
371bool JSON_SETTINGS::SaveToFile( const wxString& aDirectory, bool aForce )
372{
373 if( !m_writeFile )
374 return false;
375
376 // Default PROJECT won't have a filename set
377 if( m_filename.IsEmpty() )
378 return false;
379
380 wxFileName path;
381
382 if( aDirectory.empty() )
383 {
384 path.Assign( m_filename );
385 path.SetExt( getFileExt() );
386 }
387 else
388 {
389 wxString dir( aDirectory );
390 path.Assign( dir, m_filename, getFileExt() );
391 }
392
393 if( !m_createIfMissing && !path.FileExists() )
394 {
395 wxLogTrace( traceSettings,
396 wxT( "File for %s doesn't exist and m_createIfMissing == false; not saving" ),
397 GetFullFilename() );
398 return false;
399 }
400
401 // Ensure the path exists, and create it if not.
402 if( !path.DirExists() && !path.Mkdir() )
403 {
404 wxLogTrace( traceSettings, wxT( "Warning: could not create path %s, can't save %s" ),
405 path.GetPath(), GetFullFilename() );
406 return false;
407 }
408
409 if( ( path.FileExists() && !path.IsFileWritable() ) ||
410 ( !path.FileExists() && !path.IsDirWritable() ) )
411 {
412 wxLogTrace( traceSettings, wxT( "File for %s is read-only; not saving" ), GetFullFilename() );
413 return false;
414 }
415
416 bool modified = false;
417
418 for( auto settings : m_nested_settings )
419 modified |= settings->SaveToFile();
420
421 modified |= Store();
422
423 if( !modified && !aForce && path.FileExists() )
424 {
425 wxLogTrace( traceSettings, wxT( "%s contents not modified, skipping save" ), GetFullFilename() );
426 return false;
427 }
428 else if( !modified && !aForce && !m_createIfDefault )
429 {
430 wxLogTrace( traceSettings,
431 wxT( "%s contents still default and m_createIfDefault == false; not saving" ),
432 GetFullFilename() );
433 return false;
434 }
435
436 wxLogTrace( traceSettings, wxT( "Saving %s" ), GetFullFilename() );
437
439 bool success = true;
440
441 try
442 {
443 std::stringstream buffer;
444 buffer << std::setw( 2 ) << *m_internals << std::endl;
445
446 wxFFileOutputStream fileStream( path.GetFullPath(), "wb" );
447
448 if( !fileStream.IsOk()
449 || !fileStream.WriteAll( buffer.str().c_str(), buffer.str().size() ) )
450 {
451 wxLogTrace( traceSettings, wxT( "Warning: could not save %s" ), GetFullFilename() );
452 success = false;
453 }
454 }
455 catch( nlohmann::json::exception& error )
456 {
457 wxLogTrace( traceSettings, wxT( "Catch error: could not save %s. Json error %s" ),
458 GetFullFilename(), error.what() );
459 success = false;
460 }
461 catch( ... )
462 {
463 wxLogTrace( traceSettings, wxT( "Error: could not save %s." ) );
464 success = false;
465 }
466
467 return success;
468}
469
470
471const std::string JSON_SETTINGS::FormatAsString() const
472{
474
475 std::stringstream buffer;
476 buffer << std::setw( 2 ) << *m_internals << std::endl;
477
478 return buffer.str();
479}
480
481
482bool JSON_SETTINGS::LoadFromRawFile( const wxString& aPath )
483{
484 try
485 {
486 wxFFileInputStream fp( aPath, wxT( "rt" ) );
487 wxStdInputStream fstream( fp );
488
489 if( fp.IsOk() )
490 {
491 *static_cast<nlohmann::json*>( m_internals.get() ) =
492 nlohmann::json::parse( fstream, nullptr,
493 /* allow_exceptions = */ true,
494 /* ignore_comments = */ true );
495 }
496 else
497 {
498 return false;
499 }
500 }
501 catch( nlohmann::json::parse_error& error )
502 {
503 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ), aPath, error.what() );
504
505 return false;
506 }
507
508 // Now that we have new data in the JSON structure, load the params again
509 Load();
510 return true;
511}
512
513
514std::optional<nlohmann::json> JSON_SETTINGS::GetJson( const std::string& aPath ) const
515{
516 nlohmann::json::json_pointer ptr = m_internals->PointerFromString( aPath );
517
518 if( m_internals->contains( ptr ) )
519 {
520 try
521 {
522 return std::optional<nlohmann::json>{ m_internals->at( ptr ) };
523 }
524 catch( ... )
525 {
526 }
527 }
528
529 return std::optional<nlohmann::json>{};
530}
531
532
533template<typename ValueType>
534std::optional<ValueType> JSON_SETTINGS::Get( const std::string& aPath ) const
535{
536 if( std::optional<nlohmann::json> ret = GetJson( aPath ) )
537 {
538 try
539 {
540 return ret->get<ValueType>();
541 }
542 catch( ... )
543 {
544 }
545 }
546
547 return std::nullopt;
548}
549
550
551// Instantiate all required templates here to allow reducing scope of json.hpp
552template std::optional<bool> JSON_SETTINGS::Get<bool>( const std::string& aPath ) const;
553template std::optional<double> JSON_SETTINGS::Get<double>( const std::string& aPath ) const;
554template std::optional<float> JSON_SETTINGS::Get<float>( const std::string& aPath ) const;
555template std::optional<int> JSON_SETTINGS::Get<int>( const std::string& aPath ) const;
556template std::optional<unsigned int> JSON_SETTINGS::Get<unsigned int>( const std::string& aPath ) const;
557template std::optional<unsigned long long> JSON_SETTINGS::Get<unsigned long long>( const std::string& aPath ) const;
558template std::optional<std::string> JSON_SETTINGS::Get<std::string>( const std::string& aPath ) const;
559template std::optional<nlohmann::json> JSON_SETTINGS::Get<nlohmann::json>( const std::string& aPath ) const;
560template std::optional<KIGFX::COLOR4D> JSON_SETTINGS::Get<KIGFX::COLOR4D>( const std::string& aPath ) const;
561
562
563template<typename ValueType>
564void JSON_SETTINGS::Set( const std::string& aPath, ValueType aVal )
565{
566 m_internals->SetFromString( aPath, aVal );
567}
568
569
570// Instantiate all required templates here to allow reducing scope of json.hpp
571template void JSON_SETTINGS::Set<bool>( const std::string& aPath, bool aValue );
572template void JSON_SETTINGS::Set<double>( const std::string& aPath, double aValue );
573template void JSON_SETTINGS::Set<float>( const std::string& aPath, float aValue );
574template void JSON_SETTINGS::Set<int>( const std::string& aPath, int aValue );
575template void JSON_SETTINGS::Set<unsigned int>( const std::string& aPath, unsigned int aValue );
576template void JSON_SETTINGS::Set<unsigned long long>( const std::string& aPath, unsigned long long aValue );
577template void JSON_SETTINGS::Set<const char*>( const std::string& aPath, const char* aValue );
578template void JSON_SETTINGS::Set<std::string>( const std::string& aPath, std::string aValue );
579template void JSON_SETTINGS::Set<nlohmann::json>( const std::string& aPath, nlohmann::json aValue );
580template void JSON_SETTINGS::Set<KIGFX::COLOR4D>( const std::string& aPath, KIGFX::COLOR4D aValue );
581
582
583void JSON_SETTINGS::registerMigration( int aOldSchemaVersion, int aNewSchemaVersion,
584 std::function<bool()> aMigrator )
585{
586 wxASSERT( aNewSchemaVersion > aOldSchemaVersion );
587 wxASSERT( aNewSchemaVersion <= m_schemaVersion );
588 m_migrators[aOldSchemaVersion] = std::make_pair( aNewSchemaVersion, aMigrator );
589}
590
591
593{
594 int filever = m_internals->Get<int>( "meta.version" );
595
596 while( filever < m_schemaVersion )
597 {
598 if( !m_migrators.count( filever ) )
599 {
600 wxLogTrace( traceSettings, wxT( "Migrator missing for %s version %d!" ),
601 typeid( *this ).name(), filever );
602 return false;
603 }
604
605 std::pair<int, std::function<bool()>> pair = m_migrators.at( filever );
606
607 if( pair.second() )
608 {
609 wxLogTrace( traceSettings, wxT( "Migrated %s from %d to %d" ), typeid( *this ).name(),
610 filever, pair.first );
611 filever = pair.first;
612 m_internals->At( "meta.version" ) = filever;
613 }
614 else
615 {
616 wxLogTrace( traceSettings, wxT( "Migration failed for %s from %d to %d" ),
617 typeid( *this ).name(), filever, pair.first );
618 return false;
619 }
620 }
621
622 return true;
623}
624
625
626bool JSON_SETTINGS::MigrateFromLegacy( wxConfigBase* aLegacyConfig )
627{
628 wxLogTrace( traceSettings,
629 wxT( "MigrateFromLegacy() not implemented for %s" ), typeid( *this ).name() );
630 return false;
631}
632
633
634bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
635 wxString& aTarget )
636{
637 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
638
639 if( aObj.contains( ptr ) && aObj.at( ptr ).is_string() )
640 {
641 aTarget = aObj.at( ptr ).get<wxString>();
642 return true;
643 }
644
645 return false;
646}
647
648
649bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
650 bool& aTarget )
651{
652 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
653
654 if( aObj.contains( ptr ) && aObj.at( ptr ).is_boolean() )
655 {
656 aTarget = aObj.at( ptr ).get<bool>();
657 return true;
658 }
659
660 return false;
661}
662
663
664bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
665 int& aTarget )
666{
667 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
668
669 if( aObj.contains( ptr ) && aObj.at( ptr ).is_number_integer() )
670 {
671 aTarget = aObj.at( ptr ).get<int>();
672 return true;
673 }
674
675 return false;
676}
677
678
679bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
680 unsigned int& aTarget )
681{
682 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
683
684 if( aObj.contains( ptr ) && aObj.at( ptr ).is_number_unsigned() )
685 {
686 aTarget = aObj.at( ptr ).get<unsigned int>();
687 return true;
688 }
689
690 return false;
691}
692
693
694template<typename ValueType>
695bool JSON_SETTINGS::fromLegacy( wxConfigBase* aConfig, const std::string& aKey,
696 const std::string& aDest )
697{
698 ValueType val;
699
700 if( aConfig->Read( aKey, &val ) )
701 {
702 try
703 {
704 ( *m_internals )[aDest] = val;
705 }
706 catch( ... )
707 {
708 wxASSERT_MSG( false, wxT( "Could not write value in fromLegacy!" ) );
709 return false;
710 }
711
712 return true;
713 }
714
715 return false;
716}
717
718
719// Explicitly declare these because we only support a few types anyway, and it means we can keep
720// wxConfig detail out of the header file
721template bool JSON_SETTINGS::fromLegacy<int>( wxConfigBase*, const std::string&,
722 const std::string& );
723
724template bool JSON_SETTINGS::fromLegacy<double>( wxConfigBase*, const std::string&,
725 const std::string& );
726
727template bool JSON_SETTINGS::fromLegacy<bool>( wxConfigBase*, const std::string&,
728 const std::string& );
729
730
731bool JSON_SETTINGS::fromLegacyString( wxConfigBase* aConfig, const std::string& aKey,
732 const std::string& aDest )
733{
734 wxString str;
735
736 if( aConfig->Read( aKey, &str ) )
737 {
738 try
739 {
740 ( *m_internals )[aDest] = str.ToUTF8();
741 }
742 catch( ... )
743 {
744 wxASSERT_MSG( false, wxT( "Could not write value in fromLegacyString!" ) );
745 return false;
746 }
747
748 return true;
749 }
750
751 return false;
752}
753
754
755bool JSON_SETTINGS::fromLegacyColor( wxConfigBase* aConfig, const std::string& aKey,
756 const std::string& aDest )
757{
758 wxString str;
759
760 if( aConfig->Read( aKey, &str ) )
761 {
763 color.SetFromWxString( str );
764
765 try
766 {
767 nlohmann::json js = nlohmann::json::array( { color.r, color.g, color.b, color.a } );
768 ( *m_internals )[aDest] = js;
769 }
770 catch( ... )
771 {
772 wxASSERT_MSG( false, wxT( "Could not write value in fromLegacyColor!" ) );
773 return false;
774 }
775
776 return true;
777 }
778
779 return false;
780}
781
782
784{
785 wxLogTrace( traceSettings, wxT( "AddNestedSettings %s" ), aSettings->GetFilename() );
786 m_nested_settings.push_back( aSettings );
787}
788
789
791{
792 if( !aSettings || !m_manager )
793 return;
794
795 auto it = std::find_if( m_nested_settings.begin(), m_nested_settings.end(),
796 [&aSettings]( const JSON_SETTINGS* aPtr ) {
797 return aPtr == aSettings;
798 } );
799
800 if( it != m_nested_settings.end() )
801 {
802 wxLogTrace( traceSettings, wxT( "Flush and release %s" ), ( *it )->GetFilename() );
803 ( *it )->SaveToFile();
804 m_nested_settings.erase( it );
805 }
806
807 aSettings->SetParent( nullptr );
808}
809
810
811// Specializations to allow conversion between wxString and std::string via JSON_SETTINGS API
812
813template<> std::optional<wxString> JSON_SETTINGS::Get( const std::string& aPath ) const
814{
815 if( std::optional<nlohmann::json> opt_json = GetJson( aPath ) )
816 return wxString( opt_json->get<std::string>().c_str(), wxConvUTF8 );
817
818 return std::nullopt;
819}
820
821
822template<> void JSON_SETTINGS::Set<wxString>( const std::string& aPath, wxString aVal )
823{
824 ( *m_internals )[aPath] = aVal.ToUTF8();
825}
826
827// Specializations to allow directly reading/writing wxStrings from JSON
828
829void to_json( nlohmann::json& aJson, const wxString& aString )
830{
831 aJson = aString.ToUTF8();
832}
833
834
835void from_json( const nlohmann::json& aJson, wxString& aString )
836{
837 aString = wxString( aJson.get<std::string>().c_str(), wxConvUTF8 );
838}
839
840
841template<typename ResultType>
842ResultType JSON_SETTINGS::fetchOrDefault( const nlohmann::json& aJson, const std::string& aKey,
843 ResultType aDefault )
844{
845 ResultType ret = aDefault;
846
847 try
848 {
849 if( aJson.contains( aKey ) )
850 ret = aJson.at( aKey ).get<ResultType>();
851 }
852 catch( ... )
853 {
854 }
855
856 return ret;
857}
858
859
860template std::string JSON_SETTINGS::fetchOrDefault( const nlohmann::json& aJson,
861 const std::string& aKey, std::string aDefault );
862
863template bool JSON_SETTINGS::fetchOrDefault( const nlohmann::json& aJson, const std::string& aKey,
864 bool aDefault );
int color
Definition: DXF_plotter.cpp:57
static nlohmann::json::json_pointer PointerFromString(std::string aPath)
Builds a JSON pointer based on a given string.
const std::string FormatAsString() const
bool fromLegacyString(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig string value to a given JSON pointer value.
virtual wxString getFileExt() const
std::optional< nlohmann::json > GetJson(const std::string &aPath) const
Fetches a JSON object that is a subset of this JSON_SETTINGS object, using a path of the form "key1....
bool fromLegacy(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig value to a given JSON pointer value.
wxString m_filename
The filename (not including path) of this settings file (inicode)
SETTINGS_MANAGER * m_manager
A pointer to the settings manager managing this file (may be null)
bool Contains(const std::string &aPath) const
bool LoadFromRawFile(const wxString &aPath)
virtual ~JSON_SETTINGS()
std::vector< NESTED_SETTINGS * > m_nested_settings
Nested settings files that live inside this one, if any.
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
bool m_createIfDefault
Whether or not the backing store file should be created if all parameters are still at their default ...
bool m_writeFile
Whether or not the backing store file should be written.
static bool SetIfPresent(const nlohmann::json &aObj, const std::string &aPath, wxString &aTarget)
Sets the given string if the given key/path is present.
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.
void ResetToDefaults()
Resets all parameters to default values.
bool fromLegacyColor(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy COLOR4D stored in a wxConfig string to a given JSON pointer value.
wxString GetFullFilename() const
bool m_createIfMissing
Whether or not the backing store file should be created it if doesn't exist.
bool Migrate()
Migrates the schema of this settings from the version in the file to the latest version.
std::vector< PARAM_BASE * > m_params
The list of parameters (owned by this object)
static ResultType fetchOrDefault(const nlohmann::json &aJson, const std::string &aKey, ResultType aDefault=ResultType())
Helper to retrieve a value from a JSON object (dictionary) as a certain result type.
virtual bool MigrateFromLegacy(wxConfigBase *aLegacyConfig)
Migrates from wxConfig to JSON-based configuration.
void registerMigration(int aOldSchemaVersion, int aNewSchemaVersion, std::function< bool(void)> aMigrator)
Registers a migration from one schema version to another.
nlohmann::json & At(const std::string &aPath)
Wrappers for the underlying JSON API so that most consumers don't need json.hpp All of these function...
JSON_SETTINGS_INTERNALS * Internals()
void ReleaseNestedSettings(NESTED_SETTINGS *aSettings)
Saves and frees a nested settings object, if it exists within this one.
JSON_SETTINGS(const wxString &aFilename, SETTINGS_LOC aLocation, int aSchemaVersion)
Definition: json_settings.h:64
bool m_deleteLegacyAfterMigration
Whether or not to delete legacy file after migration.
std::unique_ptr< JSON_SETTINGS_INTERNALS > m_internals
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
virtual wxString getLegacyFileExt() const
void Set(const std::string &aPath, ValueType aVal)
Stores a value into the JSON document Will throw an exception if ValueType isn't something that the l...
bool m_resetParamsIfMissing
Whether or not to set parameters to their default value if missing from JSON on Load()
std::map< int, std::pair< int, std::function< bool()> > > m_migrators
A map of starting schema version to a pair of <ending version, migrator function>
int m_schemaVersion
Version of this settings schema.
wxString m_legacy_filename
The filename of the wxConfig legacy file (if different from m_filename)
std::optional< ValueType > Get(const std::string &aPath) const
Fetches a value from within the JSON document.
void AddNestedSettings(NESTED_SETTINGS *aSettings)
Transfers ownership of a given NESTED_SETTINGS to this object.
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
wxString GetFilename() const
Definition: json_settings.h:73
A color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:104
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:41
NESTED_SETTINGS is a JSON_SETTINGS that lives inside a JSON_SETTINGS.
void SetParent(JSON_SETTINGS *aParent, bool aLoadFromFile=true)
nlohmann::json json
Definition: gerbview.cpp:44
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
void from_json(const nlohmann::json &aJson, wxString &aString)
void to_json(nlohmann::json &aJson, const wxString &aString)
SETTINGS_LOC
Definition: json_settings.h:47
bool parse(std::istream &aStream, bool aVerbose)
Parse a PCB or footprint file from the given input stream.
std::vector< FAB_LAYER_COLOR > dummy