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