KiCad PCB EDA Suite
Loading...
Searching...
No Matches
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-2023 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>
36#include <wx/aui/framemanager.h>
37#include <wx/config.h>
38#include <wx/debug.h>
39#include <wx/fileconf.h>
40#include <wx/filename.h>
41#include <wx/gdicmn.h>
42#include <wx/log.h>
43#include <wx/stdstream.h>
44#include <wx/wfstream.h>
45
46
47nlohmann::json::json_pointer JSON_SETTINGS_INTERNALS::PointerFromString( std::string aPath )
48{
49 std::replace( aPath.begin(), aPath.end(), '.', '/' );
50 aPath.insert( 0, "/" );
51
52 nlohmann::json::json_pointer p;
53
54 try
55 {
56 p = nlohmann::json::json_pointer( aPath );
57 }
58 catch( ... )
59 {
60 wxASSERT_MSG( false, wxT( "Invalid pointer path in PointerFromString!" ) );
61 }
62
63 return p;
64}
65
66
67JSON_SETTINGS::JSON_SETTINGS( const wxString& aFilename, SETTINGS_LOC aLocation,
68 int aSchemaVersion, bool aCreateIfMissing, bool aCreateIfDefault,
69 bool aWriteFile ) :
70 m_filename( aFilename ),
71 m_legacy_filename( "" ),
72 m_location( aLocation ),
73 m_createIfMissing( aCreateIfMissing ),
74 m_createIfDefault( aCreateIfDefault ),
75 m_writeFile( aWriteFile ),
76 m_deleteLegacyAfterMigration( true ),
77 m_resetParamsIfMissing( true ),
78 m_schemaVersion( aSchemaVersion ),
79 m_manager( nullptr )
80{
81 m_internals = std::make_unique<JSON_SETTINGS_INTERNALS>();
82
83 try
84 {
85 m_internals->SetFromString( "meta.filename", GetFullFilename() );
86 }
87 catch( ... )
88 {
89 wxLogTrace( traceSettings, wxT( "Error: Could not create filename field for %s" ),
91 }
92
93
94 m_params.emplace_back(
95 new PARAM<int>( "meta.version", &m_schemaVersion, m_schemaVersion, true ) );
96}
97
98
100{
101 for( PARAM_BASE* param: m_params )
102 delete param;
103
104 m_params.clear();
105}
106
107
109{
110 if( m_filename.BeforeLast( '.' ) == getFileExt() )
111 return m_filename;
112
113 return wxString( m_filename + "." + getFileExt() );
114}
115
116
117nlohmann::json& JSON_SETTINGS::At( const std::string& aPath )
118{
119 return m_internals->At( aPath );
120}
121
122
123bool JSON_SETTINGS::Contains( const std::string& aPath ) const
124{
125 return m_internals->contains( JSON_SETTINGS_INTERNALS::PointerFromString( aPath ) );
126}
127
128
130{
131 return m_internals.get();
132}
133
134
136{
137 for( PARAM_BASE* param : m_params )
138 {
139 try
140 {
141 param->Load( this, m_resetParamsIfMissing );
142 }
143 catch( ... )
144 {
145 // Skip unreadable parameters in file
146 wxLogTrace( traceSettings, wxT( "param '%s' load err" ), param->GetJsonPath().c_str() );
147 }
148 }
149}
150
151
152bool JSON_SETTINGS::LoadFromFile( const wxString& aDirectory )
153{
154 // First, load all params to default values
155 m_internals->clear();
156 Load();
157
158 bool success = true;
159 bool migrated = false;
160 bool legacy_migrated = false;
161
162 LOCALE_IO locale;
163
164 auto migrateFromLegacy =
165 [&] ( wxFileName& aPath )
166 {
167 // Backup and restore during migration so that the original can be mutated if
168 // convenient
169 bool backed_up = false;
170 wxFileName temp;
171
172 if( aPath.IsDirWritable() )
173 {
174 temp.AssignTempFileName( aPath.GetFullPath() );
175
176 if( !wxCopyFile( aPath.GetFullPath(), temp.GetFullPath() ) )
177 {
178 wxLogTrace( traceSettings,
179 wxT( "%s: could not create temp file for migration" ),
180 GetFullFilename() );
181 }
182 else
183 {
184 backed_up = true;
185 }
186 }
187
188 // Silence popups if legacy file is read-only
189 wxLogNull doNotLog;
190
191 wxConfigBase::DontCreateOnDemand();
192 auto cfg = std::make_unique<wxFileConfig>( wxT( "" ), wxT( "" ),
193 aPath.GetFullPath() );
194
195 // If migrate fails or is not implemented, fall back to built-in defaults that
196 // were already loaded above
197 if( !MigrateFromLegacy( cfg.get() ) )
198 {
199 success = false;
200 wxLogTrace( traceSettings,
201 wxT( "%s: migrated; not all settings were found in legacy file" ),
202 GetFullFilename() );
203 }
204 else
205 {
206 success = true;
207 wxLogTrace( traceSettings, wxT( "%s: migrated from legacy format" ),
208 GetFullFilename() );
209 }
210
211 if( backed_up )
212 {
213 cfg.reset();
214
215 if( !wxCopyFile( temp.GetFullPath(), aPath.GetFullPath() ) )
216 {
217 wxLogTrace( traceSettings,
218 wxT( "migrate; copy temp file %s to %s failed" ),
219 temp.GetFullPath(),
220 aPath.GetFullPath() );
221 }
222
223 if( !wxRemoveFile( temp.GetFullPath() ) )
224 {
225 wxLogTrace( traceSettings,
226 wxT( "migrate; failed to remove temp file %s" ),
227 temp.GetFullPath() );
228 }
229 }
230
231 // Either way, we want to clean up the old file afterwards
232 legacy_migrated = true;
233 };
234
235 wxFileName path;
236
237 if( aDirectory.empty() )
238 {
239 path.Assign( m_filename );
240 path.SetExt( getFileExt() );
241 }
242 else
243 {
244 wxString dir( aDirectory );
245 path.Assign( dir, m_filename, getFileExt() );
246 }
247
248 if( !path.Exists() )
249 {
250 // Case 1: legacy migration, no .json extension yet
251 path.SetExt( getLegacyFileExt() );
252
253 if( path.Exists() )
254 {
255 migrateFromLegacy( path );
256 }
257 // Case 2: legacy filename is different from new one
258 else if( !m_legacy_filename.empty() )
259 {
260 path.SetName( m_legacy_filename );
261
262 if( path.Exists() )
263 migrateFromLegacy( path );
264 }
265 else
266 {
267 success = false;
268 }
269 }
270 else
271 {
272 if( !path.IsFileWritable() )
273 m_writeFile = false;
274
275 try
276 {
277 wxFFileInputStream fp( path.GetFullPath(), wxT( "rt" ) );
278 wxStdInputStream fstream( fp );
279
280 if( fp.IsOk() )
281 {
282 *static_cast<nlohmann::json*>( m_internals.get() ) =
283 nlohmann::json::parse( fstream, nullptr,
284 /* allow_exceptions = */ true,
285 /* ignore_comments = */ true );
286
287 // Save whatever we loaded, before doing any migration etc
288 m_internals->m_original = *static_cast<nlohmann::json*>( m_internals.get() );
289
290 // If parse succeeds, check if schema migration is required
291 int filever = -1;
292
293 try
294 {
295 filever = m_internals->Get<int>( "meta.version" );
296 }
297 catch( ... )
298 {
299 wxLogTrace( traceSettings, wxT( "%s: file version could not be read!" ),
300 GetFullFilename() );
301 success = false;
302 }
303
304 if( filever >= 0 && filever < m_schemaVersion )
305 {
306 wxLogTrace( traceSettings, wxT( "%s: attempting migration from version "
307 "%d to %d" ),
308 GetFullFilename(), filever, m_schemaVersion );
309
310 if( Migrate() )
311 {
312 migrated = true;
313 }
314 else
315 {
316 wxLogTrace( traceSettings, wxT( "%s: migration failed!" ),
317 GetFullFilename() );
318 }
319 }
320 else if( filever > m_schemaVersion )
321 {
322 wxLogTrace( traceSettings,
323 wxT( "%s: warning: file version %d is newer than latest (%d)" ),
324 GetFullFilename(), filever, m_schemaVersion );
325 }
326 }
327 else
328 {
329 wxLogTrace( traceSettings, wxT( "%s exists but can't be opened for read" ),
330 GetFullFilename() );
331 }
332 }
333 catch( nlohmann::json::parse_error& error )
334 {
335 success = false;
336 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ),
337 path.GetFullPath(), error.what() );
338 wxLogTrace( traceSettings, wxT( "Attempting migration in case file is in legacy "
339 "format" ) );
340 migrateFromLegacy( path );
341 }
342 }
343
344 // Now that we have new data in the JSON structure, load the params again
345 Load();
346
347 // And finally load any nested settings
348 for( NESTED_SETTINGS* settings : m_nested_settings )
349 settings->LoadFromFile();
350
351 wxLogTrace( traceSettings, wxT( "Loaded <%s> with schema %d" ), GetFullFilename(),
353
354 // If we migrated, clean up the legacy file (with no extension)
355 if( m_writeFile && ( legacy_migrated || migrated ) )
356 {
357 if( legacy_migrated && m_deleteLegacyAfterMigration && !wxRemoveFile( path.GetFullPath() ) )
358 {
359 wxLogTrace( traceSettings, wxT( "Warning: could not remove legacy file %s" ),
360 path.GetFullPath() );
361 }
362
363 // And write-out immediately so that we don't lose data if the program later crashes.
365 SaveToFile( aDirectory, true );
366 }
367
368 return success;
369}
370
371
373{
374 bool modified = false;
375
376 for( PARAM_BASE* param : m_params )
377 {
378 modified |= !param->MatchesFile( this );
379 param->Store( this );
380 }
381
382 return modified;
383}
384
385
387{
388 for( PARAM_BASE* param : m_params )
389 param->SetDefault();
390}
391
392
393bool JSON_SETTINGS::SaveToFile( const wxString& aDirectory, bool aForce )
394{
395 if( !m_writeFile )
396 return false;
397
398 // Default PROJECT won't have a filename set
399 if( m_filename.IsEmpty() )
400 return false;
401
402 wxFileName path;
403
404 if( aDirectory.empty() )
405 {
406 path.Assign( m_filename );
407 path.SetExt( getFileExt() );
408 }
409 else
410 {
411 wxString dir( aDirectory );
412 path.Assign( dir, m_filename, getFileExt() );
413 }
414
415 if( !m_createIfMissing && !path.FileExists() )
416 {
417 wxLogTrace( traceSettings,
418 wxT( "File for %s doesn't exist and m_createIfMissing == false; not saving" ),
419 GetFullFilename() );
420 return false;
421 }
422
423 // Ensure the path exists, and create it if not.
424 if( !path.DirExists() && !path.Mkdir() )
425 {
426 wxLogTrace( traceSettings, wxT( "Warning: could not create path %s, can't save %s" ),
427 path.GetPath(), GetFullFilename() );
428 return false;
429 }
430
431 if( ( path.FileExists() && !path.IsFileWritable() ) ||
432 ( !path.FileExists() && !path.IsDirWritable() ) )
433 {
434 wxLogTrace( traceSettings, wxT( "File for %s is read-only; not saving" ),
435 GetFullFilename() );
436 return false;
437 }
438
439 bool modified = false;
440
441 for( NESTED_SETTINGS* settings : m_nested_settings )
442 modified |= settings->SaveToFile();
443
444 modified |= Store();
445
446 if( !modified && !aForce && path.FileExists() )
447 {
448 wxLogTrace( traceSettings, wxT( "%s contents not modified, skipping save" ),
449 GetFullFilename() );
450 return false;
451 }
452 else if( !modified && !aForce && !m_createIfDefault )
453 {
454 wxLogTrace( traceSettings,
455 wxT( "%s contents still default and m_createIfDefault == false; not saving" ),
456 GetFullFilename() );
457 return false;
458 }
459
460 wxLogTrace( traceSettings, wxT( "Saving %s" ), GetFullFilename() );
461
463 bool success = true;
464
465 nlohmann::json toSave = m_internals->m_original;
466
467
468 for( PARAM_BASE* param : m_params )
469 {
470 if( PARAM_WXSTRING_MAP* stringMap = dynamic_cast<PARAM_WXSTRING_MAP*>( param ) )
471 {
472 if( stringMap->ClearUnknownKeys() )
473 toSave[ stringMap->GetJsonPath() ] = nlohmann::json( {} );
474 }
475 }
476
477 toSave.update( m_internals->begin(), m_internals->end(), /* merge_objects = */ true );
478
479 try
480 {
481 std::stringstream buffer;
482 buffer << std::setw( 2 ) << toSave << std::endl;
483
484 wxFFileOutputStream fileStream( path.GetFullPath(), "wb" );
485
486 if( !fileStream.IsOk()
487 || !fileStream.WriteAll( buffer.str().c_str(), buffer.str().size() ) )
488 {
489 wxLogTrace( traceSettings, wxT( "Warning: could not save %s" ), GetFullFilename() );
490 success = false;
491 }
492 }
493 catch( nlohmann::json::exception& error )
494 {
495 wxLogTrace( traceSettings, wxT( "Catch error: could not save %s. Json error %s" ),
496 GetFullFilename(), error.what() );
497 success = false;
498 }
499 catch( ... )
500 {
501 wxLogTrace( traceSettings, wxT( "Error: could not save %s." ) );
502 success = false;
503 }
504
505 return success;
506}
507
508
510{
511 Store();
512
514
515 std::stringstream buffer;
516 buffer << std::setw( 2 ) << *m_internals << std::endl;
517
518 return buffer.str();
519}
520
521
522bool JSON_SETTINGS::LoadFromRawFile( const wxString& aPath )
523{
524 try
525 {
526 wxFFileInputStream fp( aPath, wxT( "rt" ) );
527 wxStdInputStream fstream( fp );
528
529 if( fp.IsOk() )
530 {
531 *static_cast<nlohmann::json*>( m_internals.get() ) =
532 nlohmann::json::parse( fstream, nullptr,
533 /* allow_exceptions = */ true,
534 /* ignore_comments = */ true );
535 }
536 else
537 {
538 return false;
539 }
540 }
541 catch( nlohmann::json::parse_error& error )
542 {
543 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ), aPath, error.what() );
544
545 return false;
546 }
547
548 // Now that we have new data in the JSON structure, load the params again
549 Load();
550 return true;
551}
552
553
554std::optional<nlohmann::json> JSON_SETTINGS::GetJson( const std::string& aPath ) const
555{
556 nlohmann::json::json_pointer ptr = m_internals->PointerFromString( aPath );
557
558 if( m_internals->contains( ptr ) )
559 {
560 try
561 {
562 return std::optional<nlohmann::json>{ m_internals->at( ptr ) };
563 }
564 catch( ... )
565 {
566 }
567 }
568
569 return std::optional<nlohmann::json>{};
570}
571
572
573template<typename ValueType>
574std::optional<ValueType> JSON_SETTINGS::Get( const std::string& aPath ) const
575{
576 if( std::optional<nlohmann::json> ret = GetJson( aPath ) )
577 {
578 try
579 {
580 return ret->get<ValueType>();
581 }
582 catch( ... )
583 {
584 }
585 }
586
587 return std::nullopt;
588}
589
590
591// Instantiate all required templates here to allow reducing scope of json.hpp
592template KICOMMON_API std::optional<bool> JSON_SETTINGS::Get<bool>( const std::string& aPath ) const;
593template KICOMMON_API std::optional<double>
594 JSON_SETTINGS::Get<double>( const std::string& aPath ) const;
595template KICOMMON_API std::optional<float>
596 JSON_SETTINGS::Get<float>( const std::string& aPath ) const;
597template KICOMMON_API std::optional<int> JSON_SETTINGS::Get<int>( const std::string& aPath ) const;
598template KICOMMON_API std::optional<unsigned int>
599 JSON_SETTINGS::Get<unsigned int>( const std::string& aPath ) const;
600template KICOMMON_API std::optional<unsigned long long>
601 JSON_SETTINGS::Get<unsigned long long>( const std::string& aPath ) const;
602template KICOMMON_API std::optional<std::string>
603 JSON_SETTINGS::Get<std::string>( const std::string& aPath ) const;
604template KICOMMON_API std::optional<nlohmann::json>
605 JSON_SETTINGS::Get<nlohmann::json>( const std::string& aPath ) const;
606template KICOMMON_API std::optional<KIGFX::COLOR4D>
607 JSON_SETTINGS::Get<KIGFX::COLOR4D>( const std::string& aPath ) const;
608template KICOMMON_API std::optional<BOM_FIELD>
609 JSON_SETTINGS::Get<BOM_FIELD>( const std::string& aPath ) const;
610template KICOMMON_API std::optional<BOM_PRESET>
611 JSON_SETTINGS::Get<BOM_PRESET>( const std::string& aPath ) const;
612template KICOMMON_API std::optional<BOM_FMT_PRESET>
613 JSON_SETTINGS::Get<BOM_FMT_PRESET>( const std::string& aPath ) const;
614template KICOMMON_API std::optional<GRID> JSON_SETTINGS::Get<GRID>( const std::string& aPath ) const;
615template KICOMMON_API std::optional<wxPoint>
616 JSON_SETTINGS::Get<wxPoint>( const std::string& aPath ) const;
617template KICOMMON_API std::optional<wxSize>
618 JSON_SETTINGS::Get<wxSize>( const std::string& aPath ) const;
619template KICOMMON_API std::optional<wxRect>
620 JSON_SETTINGS::Get<wxRect>( const std::string& aPath ) const;
621template KICOMMON_API std::optional<wxAuiPaneInfo>
622 JSON_SETTINGS::Get<wxAuiPaneInfo>( const std::string& aPath ) const;
623
624template<typename ValueType>
625void JSON_SETTINGS::Set( const std::string& aPath, ValueType aVal )
626{
627 m_internals->SetFromString( aPath, std::move( aVal ) );
628}
629
630
631// Instantiate all required templates here to allow reducing scope of json.hpp
632template KICOMMON_API void JSON_SETTINGS::Set<bool>( const std::string& aPath, bool aValue );
633template KICOMMON_API void JSON_SETTINGS::Set<double>( const std::string& aPath, double aValue );
634template KICOMMON_API void JSON_SETTINGS::Set<float>( const std::string& aPath, float aValue );
635template KICOMMON_API void JSON_SETTINGS::Set<int>( const std::string& aPath, int aValue );
636template KICOMMON_API void JSON_SETTINGS::Set<unsigned int>( const std::string& aPath,
637 unsigned int aValue );
638template KICOMMON_API void JSON_SETTINGS::Set<unsigned long long>( const std::string& aPath,
639 unsigned long long aValue );
640template KICOMMON_API void JSON_SETTINGS::Set<const char*>( const std::string& aPath,
641 const char* aValue );
642template KICOMMON_API void JSON_SETTINGS::Set<std::string>( const std::string& aPath,
643 std::string aValue );
644template KICOMMON_API void JSON_SETTINGS::Set<nlohmann::json>( const std::string& aPath,
645 nlohmann::json aValue );
646template KICOMMON_API void JSON_SETTINGS::Set<KIGFX::COLOR4D>( const std::string& aPath,
647 KIGFX::COLOR4D aValue );
648template KICOMMON_API void JSON_SETTINGS::Set<BOM_FIELD>( const std::string& aPath,
649 BOM_FIELD aValue );
650template KICOMMON_API void JSON_SETTINGS::Set<BOM_PRESET>( const std::string& aPath,
651 BOM_PRESET aValue );
652template KICOMMON_API void JSON_SETTINGS::Set<BOM_FMT_PRESET>( const std::string& aPath,
653 BOM_FMT_PRESET aValue );
654template KICOMMON_API void JSON_SETTINGS::Set<GRID>( const std::string& aPath, GRID aValue );
655template KICOMMON_API void JSON_SETTINGS::Set<wxPoint>( const std::string& aPath, wxPoint aValue );
656template KICOMMON_API void JSON_SETTINGS::Set<wxSize>( const std::string& aPath, wxSize aValue );
657template KICOMMON_API void JSON_SETTINGS::Set<wxRect>( const std::string& aPath, wxRect aValue );
658template KICOMMON_API void JSON_SETTINGS::Set<wxAuiPaneInfo>( const std::string& aPath,
659 wxAuiPaneInfo aValue );
660
661
662void JSON_SETTINGS::registerMigration( int aOldSchemaVersion, int aNewSchemaVersion,
663 std::function<bool()> aMigrator )
664{
665 wxASSERT( aNewSchemaVersion > aOldSchemaVersion );
666 wxASSERT( aNewSchemaVersion <= m_schemaVersion );
667 m_migrators[aOldSchemaVersion] = std::make_pair( aNewSchemaVersion, aMigrator );
668}
669
670
672{
673 int filever = m_internals->Get<int>( "meta.version" );
674
675 while( filever < m_schemaVersion )
676 {
677 if( !m_migrators.count( filever ) )
678 {
679 wxLogTrace( traceSettings, wxT( "Migrator missing for %s version %d!" ),
680 typeid( *this ).name(), filever );
681 return false;
682 }
683
684 std::pair<int, std::function<bool()>> pair = m_migrators.at( filever );
685
686 if( pair.second() )
687 {
688 wxLogTrace( traceSettings, wxT( "Migrated %s from %d to %d" ), typeid( *this ).name(),
689 filever, pair.first );
690 filever = pair.first;
691 m_internals->At( "meta.version" ) = filever;
692 }
693 else
694 {
695 wxLogTrace( traceSettings, wxT( "Migration failed for %s from %d to %d" ),
696 typeid( *this ).name(), filever, pair.first );
697 return false;
698 }
699 }
700
701 return true;
702}
703
704
705bool JSON_SETTINGS::MigrateFromLegacy( wxConfigBase* aLegacyConfig )
706{
707 wxLogTrace( traceSettings,
708 wxT( "MigrateFromLegacy() not implemented for %s" ), typeid( *this ).name() );
709 return false;
710}
711
712
713bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
714 wxString& aTarget )
715{
716 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
717
718 if( aObj.contains( ptr ) && aObj.at( ptr ).is_string() )
719 {
720 aTarget = aObj.at( ptr ).get<wxString>();
721 return true;
722 }
723
724 return false;
725}
726
727
728bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
729 bool& aTarget )
730{
731 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
732
733 if( aObj.contains( ptr ) && aObj.at( ptr ).is_boolean() )
734 {
735 aTarget = aObj.at( ptr ).get<bool>();
736 return true;
737 }
738
739 return false;
740}
741
742
743bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
744 int& aTarget )
745{
746 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
747
748 if( aObj.contains( ptr ) && aObj.at( ptr ).is_number_integer() )
749 {
750 aTarget = aObj.at( ptr ).get<int>();
751 return true;
752 }
753
754 return false;
755}
756
757
758bool JSON_SETTINGS::SetIfPresent( const nlohmann::json& aObj, const std::string& aPath,
759 unsigned int& aTarget )
760{
761 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( aPath );
762
763 if( aObj.contains( ptr ) && aObj.at( ptr ).is_number_unsigned() )
764 {
765 aTarget = aObj.at( ptr ).get<unsigned int>();
766 return true;
767 }
768
769 return false;
770}
771
772
773template<typename ValueType>
774bool JSON_SETTINGS::fromLegacy( wxConfigBase* aConfig, const std::string& aKey,
775 const std::string& aDest )
776{
777 ValueType val;
778
779 if( aConfig->Read( aKey, &val ) )
780 {
781 try
782 {
783 ( *m_internals )[aDest] = val;
784 }
785 catch( ... )
786 {
787 wxASSERT_MSG( false, wxT( "Could not write value in fromLegacy!" ) );
788 return false;
789 }
790
791 return true;
792 }
793
794 return false;
795}
796
797
798// Explicitly declare these because we only support a few types anyway, and it means we can keep
799// wxConfig detail out of the header file
800template KICOMMON_API bool JSON_SETTINGS::fromLegacy<int>( wxConfigBase*, const std::string&,
801 const std::string& );
802
803template KICOMMON_API bool JSON_SETTINGS::fromLegacy<double>( wxConfigBase*, const std::string&,
804 const std::string& );
805
806template KICOMMON_API bool JSON_SETTINGS::fromLegacy<bool>( wxConfigBase*, const std::string&,
807 const std::string& );
808
809
810bool JSON_SETTINGS::fromLegacyString( wxConfigBase* aConfig, const std::string& aKey,
811 const std::string& aDest )
812{
813 wxString str;
814
815 if( aConfig->Read( aKey, &str ) )
816 {
817 try
818 {
819 ( *m_internals )[aDest] = str.ToUTF8();
820 }
821 catch( ... )
822 {
823 wxASSERT_MSG( false, wxT( "Could not write value in fromLegacyString!" ) );
824 return false;
825 }
826
827 return true;
828 }
829
830 return false;
831}
832
833
834bool JSON_SETTINGS::fromLegacyColor( wxConfigBase* aConfig, const std::string& aKey,
835 const std::string& aDest )
836{
837 wxString str;
838
839 if( aConfig->Read( aKey, &str ) )
840 {
842 color.SetFromWxString( str );
843
844 try
845 {
846 nlohmann::json js = nlohmann::json::array( { color.r, color.g, color.b, color.a } );
847 ( *m_internals )[aDest] = std::move( js );
848 }
849 catch( ... )
850 {
851 wxASSERT_MSG( false, wxT( "Could not write value in fromLegacyColor!" ) );
852 return false;
853 }
854
855 return true;
856 }
857
858 return false;
859}
860
861
863{
864 wxLogTrace( traceSettings, wxT( "AddNestedSettings %s" ), aSettings->GetFilename() );
865 m_nested_settings.push_back( aSettings );
866}
867
868
870{
871 if( !aSettings || !m_manager )
872 return;
873
874 auto it = std::find_if( m_nested_settings.begin(), m_nested_settings.end(),
875 [&aSettings]( const JSON_SETTINGS* aPtr )
876 {
877 return aPtr == aSettings;
878 } );
879
880 if( it != m_nested_settings.end() )
881 {
882 wxLogTrace( traceSettings, wxT( "Flush and release %s" ), ( *it )->GetFilename() );
883 ( *it )->SaveToFile();
884 m_nested_settings.erase( it );
885 }
886
887 aSettings->SetParent( nullptr );
888}
889
890
891// Specializations to allow conversion between wxString and std::string via JSON_SETTINGS API
892template<> std::optional<wxString> JSON_SETTINGS::Get( const std::string& aPath ) const
893{
894 if( std::optional<nlohmann::json> opt_json = GetJson( aPath ) )
895 return wxString( opt_json->get<std::string>().c_str(), wxConvUTF8 );
896
897 return std::nullopt;
898}
899
900
901template<> void JSON_SETTINGS::Set<wxString>( const std::string& aPath, wxString aVal )
902{
903 ( *m_internals )[aPath] = aVal.ToUTF8();
904}
905
906
907template<typename ResultType>
908ResultType JSON_SETTINGS::fetchOrDefault( const nlohmann::json& aJson, const std::string& aKey,
909 ResultType aDefault )
910{
911 ResultType ret = std::move( aDefault );
912
913 try
914 {
915 if( aJson.contains( aKey ) )
916 ret = aJson.at( aKey ).get<ResultType>();
917 }
918 catch( ... )
919 {
920 }
921
922 return ret;
923}
924
925
926template KICOMMON_API std::string JSON_SETTINGS::fetchOrDefault( const nlohmann::json& aJson,
927 const std::string& aKey, std::string aDefault );
928
929
930template KICOMMON_API bool JSON_SETTINGS::fetchOrDefault( const nlohmann::json& aJson,
931 const std::string& aKey,
932 bool aDefault );
int color
Definition: DXF_plotter.cpp:58
static nlohmann::json::json_pointer PointerFromString(std::string aPath)
Builds a JSON pointer based on a given string.
bool fromLegacyString(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig string value to a given JSON pointer value.
bool fromLegacy(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig value to a given JSON pointer value.
virtual wxString getFileExt() 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...
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....
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::optional< ValueType > Get(const std::string &aPath) const
Fetches a value from within the JSON document.
std::vector< PARAM_BASE * > m_params
The list of parameters (owned by this object)
virtual bool MigrateFromLegacy(wxConfigBase *aLegacyConfig)
Migrates from wxConfig to JSON-based configuration.
const std::string FormatAsString()
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()
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.
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:71
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)
Calls Store() and then writes the contents of the JSON document to a file.
virtual wxString getLegacyFileExt() const
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)
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:80
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:49
NESTED_SETTINGS is a JSON_SETTINGS that lives inside a JSON_SETTINGS.
void SetParent(JSON_SETTINGS *aParent, bool aLoadFromFile=true)
A helper for <wxString, wxString> maps.
Definition: parameters.h:810
SETTINGS_LOC
Definition: json_settings.h:54
#define traceSettings
Definition: json_settings.h:52
#define KICOMMON_API
Definition: kicommon.h:28
std::vector< FAB_LAYER_COLOR > dummy
Common grid settings, available to every frame.
Definition: grid_settings.h:34