KiCad PCB EDA Suite
COMMON_SETTINGS Class Reference

#include <common_settings.h>

Inheritance diagram for COMMON_SETTINGS:
JSON_SETTINGS

Classes

struct  APPEARANCE
 
struct  AUTO_BACKUP
 
struct  DO_NOT_SHOW_AGAIN
 
struct  ENVIRONMENT
 
struct  GRAPHICS
 
struct  INPUT
 
struct  LEGACY_3D_SEARCH_PATH
 
struct  NETCLASS_PANEL
 
struct  PACKAGE_MANAGER
 
struct  SESSION
 
struct  SYSTEM
 

Public Member Functions

 COMMON_SETTINGS ()
 
virtual ~COMMON_SETTINGS ()
 
virtual bool MigrateFromLegacy (wxConfigBase *aLegacyConfig) override
 Migrates from wxConfig to JSON-based configuration. More...
 
void InitializeEnvironment ()
 Creates the built-in environment variables and sets their default values. More...
 
wxString GetFilename () const
 
wxString GetFullFilename () const
 
void SetFilename (const wxString &aFilename)
 
void SetLocation (SETTINGS_LOC aLocation)
 
SETTINGS_LOC GetLocation () const
 
void SetLegacyFilename (const wxString &aFilename)
 
bool IsReadOnly () const
 
void SetReadOnly (bool aReadOnly)
 
nlohmann::jsonAt (const std::string &aPath)
 Wrappers for the underlying JSON API so that most consumers don't need json.hpp All of these functions take a string that is passed to PointerFromString internally. More...
 
bool Contains (const std::string &aPath) const
 
JSON_SETTINGS_INTERNALSInternals ()
 
virtual void Load ()
 Updates the parameters of this object based on the current JSON document contents. More...
 
virtual bool Store ()
 Stores the current parameters into the JSON document represented by this object Note: this doesn't do any writing to disk; that's handled by SETTINGS_MANAGER. More...
 
virtual bool LoadFromFile (const wxString &aDirectory="")
 Loads the backing file from disk and then calls Load() More...
 
virtual bool SaveToFile (const wxString &aDirectory="", bool aForce=false)
 
void ResetToDefaults ()
 Resets all parameters to default values. More...
 
std::optional< nlohmann::jsonGetJson (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.key2.key3" to refer to nested objects. More...
 
template<typename ValueType >
std::optional< ValueType > Get (const std::string &aPath) const
 Fetches a value from within the JSON document. More...
 
template<>
std::optional< wxString > Get (const std::string &aPath) const
 
template<typename ValueType >
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 library can handle. More...
 
template<>
void Set (const std::string &aPath, wxString aVal)
 
template<>
void Set (const std::string &aPath, wxString aVal)
 
bool Migrate ()
 Migrates the schema of this settings from the version in the file to the latest version. More...
 
void AddNestedSettings (NESTED_SETTINGS *aSettings)
 Transfers ownership of a given NESTED_SETTINGS to this object. More...
 
void ReleaseNestedSettings (NESTED_SETTINGS *aSettings)
 Saves and frees a nested settings object, if it exists within this one. More...
 
void SetManager (SETTINGS_MANAGER *aManager)
 
const std::string FormatAsString () const
 
bool LoadFromRawFile (const wxString &aPath)
 

Static Public Member Functions

static bool SetIfPresent (const nlohmann::json &aObj, const std::string &aPath, wxString &aTarget)
 Sets the given string if the given key/path is present. More...
 
static bool SetIfPresent (const nlohmann::json &aObj, const std::string &aPath, bool &aTarget)
 Sets the given bool if the given key/path is present. More...
 
static bool SetIfPresent (const nlohmann::json &aObj, const std::string &aPath, int &aTarget)
 Sets the given int if the given key/path is present. More...
 
static bool SetIfPresent (const nlohmann::json &aObj, const std::string &aPath, unsigned int &aTarget)
 Sets the given unsigned int if the given key/path is present. More...
 

Public Attributes

APPEARANCE m_Appearance
 
AUTO_BACKUP m_Backup
 
ENVIRONMENT m_Env
 
INPUT m_Input
 
GRAPHICS m_Graphics
 
SESSION m_Session
 
SYSTEM m_System
 
DO_NOT_SHOW_AGAIN m_DoNotShowAgain
 
NETCLASS_PANEL m_NetclassPanel
 
PACKAGE_MANAGER m_PackageManager
 

Protected Member Functions

void registerMigration (int aOldSchemaVersion, int aNewSchemaVersion, std::function< bool(void)> aMigrator)
 Registers a migration from one schema version to another. More...
 
template<typename ValueType >
bool fromLegacy (wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
 Translates a legacy wxConfig value to a given JSON pointer value. More...
 
bool fromLegacyString (wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
 Translates a legacy wxConfig string value to a given JSON pointer value. More...
 
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. More...
 
virtual wxString getFileExt () const
 
virtual wxString getLegacyFileExt () const
 

Static Protected Member Functions

template<typename ResultType >
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. More...
 

Protected Attributes

wxString m_filename
 The filename (not including path) of this settings file (inicode) More...
 
wxString m_legacy_filename
 The filename of the wxConfig legacy file (if different from m_filename) More...
 
SETTINGS_LOC m_location
 The location of this settings file (. More...
 
std::vector< PARAM_BASE * > m_params
 The list of parameters (owned by this object) More...
 
std::vector< NESTED_SETTINGS * > m_nested_settings
 Nested settings files that live inside this one, if any. More...
 
bool m_createIfMissing
 Whether or not the backing store file should be created it if doesn't exist. More...
 
bool m_createIfDefault
 Whether or not the backing store file should be created if all parameters are still at their default values. More...
 
bool m_writeFile
 Whether or not the backing store file should be written. More...
 
bool m_deleteLegacyAfterMigration
 Whether or not to delete legacy file after migration. More...
 
bool m_resetParamsIfMissing
 Whether or not to set parameters to their default value if missing from JSON on Load() More...
 
int m_schemaVersion
 Version of this settings schema. More...
 
SETTINGS_MANAGERm_manager
 A pointer to the settings manager managing this file (may be null) More...
 
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> More...
 
std::unique_ptr< JSON_SETTINGS_INTERNALSm_internals
 

Private Member Functions

bool migrateSchema0to1 ()
 
bool migrateSchema1to2 ()
 
bool migrateSchema2to3 ()
 
bool readLegacy3DResolverCfg (const wxString &aPath, std::vector< LEGACY_3D_SEARCH_PATH > &aSearchPaths)
 

Static Private Member Functions

static bool getLegacy3DHollerith (const std::string &aString, size_t &aIndex, wxString &aResult)
 

Detailed Description

Definition at line 47 of file common_settings.h.

Constructor & Destructor Documentation

◆ COMMON_SETTINGS()

COMMON_SETTINGS::COMMON_SETTINGS ( )

Definition at line 51 of file common_settings.cpp.

51 :
54 m_Backup(),
55 m_Env(),
56 m_Input(),
57 m_Graphics(),
58 m_Session(),
59 m_System(),
63{
64 /*
65 * Automatic dark mode detection works fine on Mac.
66 */
67#if defined( __WXGTK__ ) || defined( __WXMSW__ )
68 m_params.emplace_back( new PARAM_ENUM<ICON_THEME>( "appearance.icon_theme",
70#else
72#endif
73
74 /*
75 * Automatic icon scaling works fine on Mac. It works mostly fine on MSW, but perhaps not
76 * uniformly enough to exclude the explicit controls there.
77 */
78#if defined( __WXGTK__ ) || defined( __WXMSW__ )
79 m_params.emplace_back( new PARAM<int>( "appearance.icon_scale",
81#else
83#endif
84
85 /*
86 * Automatic canvas scaling works fine on all supported platforms, so it's no longer exposed as
87 * a configuration option.
88 */
90
91 /*
92 * Menu icons are off by default on OSX and on for all other platforms.
93 */
94#ifdef __WXMAC__
95 m_params.emplace_back( new PARAM<bool>( "appearance.use_icons_in_menus",
97#else
98 m_params.emplace_back( new PARAM<bool>( "appearance.use_icons_in_menus",
100#endif
101
102 /*
103 * Font scaling hacks are only needed on GTK under wxWidgets 3.0.
104 */
105#if defined( __WXGTK__ ) && !wxCHECK_VERSION( 3, 1, 0 )
106 m_params.emplace_back( new PARAM<bool>( "appearance.apply_icon_scale_to_fonts",
108#else
110#endif
111
112 m_params.emplace_back( new PARAM<bool>( "appearance.show_scrollbars",
113 &m_Appearance.show_scrollbars, true ) );
114
115 m_params.emplace_back( new PARAM<double>( "appearance.hicontrast_dimming_factor",
117
118 m_params.emplace_back( new PARAM<int>( "appearance.text_editor_zoom",
120
121 m_params.emplace_back( new PARAM<bool>( "auto_backup.enabled", &m_Backup.enabled, true ) );
122
123 m_params.emplace_back( new PARAM<bool>( "auto_backup.backup_on_autosave",
124 &m_Backup.backup_on_autosave, false ) );
125
126 m_params.emplace_back( new PARAM<int>( "auto_backup.limit_total_files",
128
129 m_params.emplace_back( new PARAM<unsigned long long>( "auto_backup.limit_total_size",
130 &m_Backup.limit_total_size, 104857600 ) );
131
132 m_params.emplace_back( new PARAM<int>( "auto_backup.limit_daily_files",
134
135 m_params.emplace_back( new PARAM<int>( "auto_backup.min_interval",
136 &m_Backup.min_interval, 300 ) );
137
138 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "environment.vars",
139 [&]() -> nlohmann::json
140 {
141 nlohmann::json ret = {};
142
143 for( const std::pair<wxString, ENV_VAR_ITEM> entry : m_Env.vars )
144 {
145 const ENV_VAR_ITEM& var = entry.second;
146
147 wxASSERT( entry.first == var.GetKey() );
148
149 // Default values are never persisted
150 if( var.IsDefault() )
151 {
152 wxLogTrace( traceEnvVars,
153 wxS( "COMMON_SETTINGS: Env var %s skipping save (default)" ),
154 var.GetKey() );
155 continue;
156 }
157
158 wxString value = var.GetValue();
159
160 // Vars that existed in JSON are persisted, but if they were overridden
161 // externally, we persist the old value (i.e. the one that was loaded from JSON)
162 if( var.GetDefinedExternally() )
163 {
164 if( var.GetDefinedInSettings() )
165 {
166 wxLogTrace( traceEnvVars,
167 wxS( "COMMON_SETTINGS: Env var %s was overridden externally, " )
168 "saving previously-loaded value %s",
169 var.GetKey(), var.GetSettingsValue() );
170 value = var.GetSettingsValue();
171 }
172 else
173 {
174 wxLogTrace( traceEnvVars,
175 wxS( "COMMON_SETTINGS: Env var %s skipping save (external)" ),
176 var.GetKey() );
177 continue;
178 }
179 }
180
181 wxLogTrace( traceEnvVars,
182 wxS( "COMMON_SETTINGS: Saving env var %s = %s" ),
183 var.GetKey(), value);
184
185 std::string key( var.GetKey().ToUTF8() );
186 ret[key] = value;
187 }
188
189 return ret;
190 },
191 [&]( const nlohmann::json& aJson )
192 {
193 if( !aJson.is_object() )
194 return;
195
196 for( const auto& entry : aJson.items() )
197 {
198 wxString key = wxString( entry.key().c_str(), wxConvUTF8 );
199 wxString val = entry.value().get<wxString>();
200
201 if( m_Env.vars.count( key ) )
202 {
203 if( m_Env.vars[key].GetDefinedExternally() )
204 {
205 wxLogTrace( traceEnvVars, wxS( "COMMON_SETTINGS: %s is defined externally" ),
206 key );
207 m_Env.vars[key].SetDefinedInSettings();
208 m_Env.vars[key].SetSettingsValue( val );
209 continue;
210 }
211 else
212 {
213 wxLogTrace( traceEnvVars, wxS( "COMMON_SETTINGS: Updating %s: %s -> %s"),
214 key, m_Env.vars[key].GetValue(), val );
215 m_Env.vars[key].SetValue( val );
216 }
217 }
218 else
219 {
220 wxLogTrace( traceEnvVars, wxS( "COMMON_SETTINGS: Loaded new var: %s = %s" ),
221 key, val );
222 m_Env.vars[key] = ENV_VAR_ITEM( key, val );
223 }
224
225 m_Env.vars[key].SetDefinedInSettings();
226 m_Env.vars[key].SetSettingsValue( val );
227 }
228 },
229 {} ) );
230
231 m_params.emplace_back( new PARAM<bool>( "input.focus_follow_sch_pcb",
232 &m_Input.focus_follow_sch_pcb, false ) );
233
234 m_params.emplace_back( new PARAM<bool>( "input.auto_pan", &m_Input.auto_pan, false ) );
235
236 m_params.emplace_back( new PARAM<int>( "input.auto_pan_acceleration",
238
239 m_params.emplace_back( new PARAM<bool>( "input.center_on_zoom",
240 &m_Input.center_on_zoom, true ) );
241
242 m_params.emplace_back( new PARAM<bool>( "input.immediate_actions",
243 &m_Input.immediate_actions, true ) );
244
245 m_params.emplace_back( new PARAM<bool>( "input.warp_mouse_on_move",
246 &m_Input.warp_mouse_on_move, true ) );
247
248 m_params.emplace_back( new PARAM<bool>( "input.horizontal_pan",
249 &m_Input.horizontal_pan, false ) );
250
251 m_params.emplace_back( new PARAM<bool>( "input.zoom_acceleration",
252 &m_Input.zoom_acceleration, false ) );
253
254#ifdef __WXMAC__
255 int default_zoom_speed = 5;
256#else
257 int default_zoom_speed = 1;
258#endif
259
260 m_params.emplace_back( new PARAM<int>( "input.zoom_speed",
261 &m_Input.zoom_speed, default_zoom_speed ) );
262
263 m_params.emplace_back( new PARAM<bool>( "input.zoom_speed_auto",
264 &m_Input.zoom_speed_auto, true ) );
265
266 m_params.emplace_back( new PARAM<int>( "input.scroll_modifier_zoom",
268
269 m_params.emplace_back( new PARAM<int>( "input.scroll_modifier_pan_h",
270 &m_Input.scroll_modifier_pan_h, WXK_CONTROL ) );
271
272 m_params.emplace_back( new PARAM<int>( "input.scroll_modifier_pan_v",
273 &m_Input.scroll_modifier_pan_v, WXK_SHIFT ) );
274
275 m_params.emplace_back( new PARAM_ENUM<MOUSE_DRAG_ACTION>( "input.mouse_left",
278
279 m_params.emplace_back( new PARAM_ENUM<MOUSE_DRAG_ACTION>( "input.mouse_middle",
282
283 m_params.emplace_back( new PARAM_ENUM<MOUSE_DRAG_ACTION>( "input.mouse_right",
286
287 m_params.emplace_back( new PARAM<int>( "graphics.opengl_antialiasing_mode",
288 &m_Graphics.opengl_aa_mode, 1, 0, 2 ) );
289
290 m_params.emplace_back( new PARAM<int>( "graphics.cairo_antialiasing_mode",
291 &m_Graphics.cairo_aa_mode, 0, 0, 2 ) );
292
293 m_params.emplace_back( new PARAM<int>( "system.autosave_interval",
294 &m_System.autosave_interval, 600 ) );
295
296#ifdef __WXMAC__
297 m_params.emplace_back( new PARAM<wxString>( "system.text_editor",
298 &m_System.text_editor, wxS( "/usr/bin/open -e" ) ) );
299#else
300 m_params.emplace_back( new PARAM<wxString>( "system.text_editor",
301 &m_System.text_editor, wxS( "" ) ) );
302#endif
303
304 m_params.emplace_back( new PARAM<int>( "system.file_history_size",
306
307 m_params.emplace_back( new PARAM<wxString>( "system.language",
308 &m_System.language, wxS( "Default" ) ) );
309
310 m_params.emplace_back( new PARAM<wxString>( "system.pdf_viewer_name",
311 &m_System.pdf_viewer_name, wxS( "" ) ) );
312
313 m_params.emplace_back( new PARAM<bool>( "system.use_system_pdf_viewer",
315
316 m_params.emplace_back( new PARAM<wxString>( "system.working_dir",
317 &m_System.working_dir, wxS( "" ) ) );
318
319 m_params.emplace_back( new PARAM<int>( "system.clear_3d_cache_interval",
321
322 m_params.emplace_back( new PARAM<bool>( "do_not_show_again.zone_fill_warning",
324
325 m_params.emplace_back( new PARAM<bool>( "do_not_show_again.env_var_overwrite_warning",
327
328 m_params.emplace_back( new PARAM<bool>( "do_not_show_again.scaled_3d_models_warning",
330
331 m_params.emplace_back( new PARAM<bool>( "do_not_show_again.data_collection_prompt",
333
334 m_params.emplace_back( new PARAM<bool>( "session.remember_open_files",
335 &m_Session.remember_open_files, false ) );
336
337 m_params.emplace_back( new PARAM_LIST<wxString>( "session.pinned_symbol_libs",
339
340 m_params.emplace_back( new PARAM_LIST<wxString>( "session.pinned_fp_libs",
341 &m_Session.pinned_fp_libs, {} ) );
342
343 m_params.emplace_back( new PARAM<int>( "netclass_panel.sash_pos",
344 &m_NetclassPanel.sash_pos, 160 ) );
345
346 m_params.emplace_back( new PARAM<int>( "package_manager.sash_pos",
347 &m_PackageManager.sash_pos, 380 ) );
348
349 registerMigration( 0, 1, std::bind( &COMMON_SETTINGS::migrateSchema0to1, this ) );
350 registerMigration( 1, 2, std::bind( &COMMON_SETTINGS::migrateSchema1to2, this ) );
351 registerMigration( 2, 3, std::bind( &COMMON_SETTINGS::migrateSchema2to3, this ) );
352}
NETCLASS_PANEL m_NetclassPanel
APPEARANCE m_Appearance
PACKAGE_MANAGER m_PackageManager
AUTO_BACKUP m_Backup
DO_NOT_SHOW_AGAIN m_DoNotShowAgain
ENVIRONMENT m_Env
KiCad uses environment variables internally for determining the base paths for libraries,...
std::vector< PARAM_BASE * > m_params
The list of parameters (owned by this object)
void registerMigration(int aOldSchemaVersion, int aNewSchemaVersion, std::function< bool(void)> aMigrator)
Registers a migration from one schema version to another.
JSON_SETTINGS(const wxString &aFilename, SETTINGS_LOC aLocation, int aSchemaVersion)
Definition: json_settings.h:64
Stores an enum as an integer.
Definition: parameters.h:217
const int commonSchemaVersion
! Update the schema version whenever a migration is required
nlohmann::json json
Definition: gerbview.cpp:44
const wxChar *const traceEnvVars
Flag to enable debug output of environment variable operations.
@ USER
The main config directory (e.g. ~/.config/kicad/)
int min_interval
Minimum time, in seconds, between subsequent backups.
bool backup_on_autosave
Trigger a backup on autosave.
unsigned long long limit_total_size
Maximum total size of backups (bytes), 0 for unlimited.
int limit_total_files
Maximum number of backup archives to retain.
int limit_daily_files
Maximum files to keep per day, 0 for unlimited.
bool enabled
Automatically back up the project when files are saved.
MOUSE_DRAG_ACTION drag_right
MOUSE_DRAG_ACTION drag_middle
MOUSE_DRAG_ACTION drag_left
std::vector< wxString > pinned_fp_libs
std::vector< wxString > pinned_symbol_libs

References COMMON_SETTINGS::APPEARANCE::apply_icon_scale_to_fonts, AUTO, COMMON_SETTINGS::AUTO_BACKUP::backup_on_autosave, COMMON_SETTINGS::APPEARANCE::canvas_scale, COMMON_SETTINGS::AUTO_BACKUP::enabled, COMMON_SETTINGS::APPEARANCE::hicontrast_dimming_factor, COMMON_SETTINGS::APPEARANCE::icon_scale, COMMON_SETTINGS::APPEARANCE::icon_theme, LIGHT, COMMON_SETTINGS::AUTO_BACKUP::limit_daily_files, COMMON_SETTINGS::AUTO_BACKUP::limit_total_files, COMMON_SETTINGS::AUTO_BACKUP::limit_total_size, m_Appearance, m_Backup, m_Env, JSON_SETTINGS::m_params, COMMON_SETTINGS::AUTO_BACKUP::min_interval, COMMON_SETTINGS::APPEARANCE::show_scrollbars, COMMON_SETTINGS::APPEARANCE::text_editor_zoom, traceEnvVars, COMMON_SETTINGS::APPEARANCE::use_icons_in_menus, USER, and COMMON_SETTINGS::ENVIRONMENT::vars.

◆ ~COMMON_SETTINGS()

virtual COMMON_SETTINGS::~COMMON_SETTINGS ( )
inlinevirtual

Definition at line 147 of file common_settings.h.

147{}

Member Function Documentation

◆ AddNestedSettings()

void JSON_SETTINGS::AddNestedSettings ( NESTED_SETTINGS aSettings)
inherited

Transfers ownership of a given NESTED_SETTINGS to this object.

Can be used to construct a NESTED_SETTINGS without the parent object needing to know about the implementation of the nested object;

Parameters
aSettingsis the settings object to take ownership of
aTargetis a pointer to update to the passed in settings

Definition at line 783 of file json_settings.cpp.

784{
785 wxLogTrace( traceSettings, wxT( "AddNestedSettings %s" ), aSettings->GetFilename() );
786 m_nested_settings.push_back( aSettings );
787}
std::vector< NESTED_SETTINGS * > m_nested_settings
Nested settings files that live inside this one, if any.
wxString GetFilename() const
Definition: json_settings.h:73
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

References JSON_SETTINGS::GetFilename(), JSON_SETTINGS::m_nested_settings, and traceSettings.

Referenced by NESTED_SETTINGS::SetParent().

◆ At()

nlohmann::json & JSON_SETTINGS::At ( const std::string &  aPath)
inherited

Wrappers for the underlying JSON API so that most consumers don't need json.hpp All of these functions take a string that is passed to PointerFromString internally.

Definition at line 111 of file json_settings.cpp.

112{
113 return m_internals->At( aPath );
114}
std::unique_ptr< JSON_SETTINGS_INTERNALS > m_internals

References JSON_SETTINGS::m_internals.

Referenced by EESCHEMA_SETTINGS::migrateBomSettings(), GERBVIEW_SETTINGS::MigrateFromLegacy(), APP_SETTINGS_BASE::migrateLibTreeWidth(), BOARD_DESIGN_SETTINGS::migrateSchema0to1(), FOOTPRINT_EDITOR_SETTINGS::migrateSchema0to1(), COLOR_SETTINGS::migrateSchema0to1(), PCBNEW_SETTINGS::PCBNEW_SETTINGS(), and PROJECT_LOCAL_SETTINGS::PROJECT_LOCAL_SETTINGS().

◆ Contains()

bool JSON_SETTINGS::Contains ( const std::string &  aPath) const
inherited

◆ fetchOrDefault()

template<typename ResultType >
template bool JSON_SETTINGS::fetchOrDefault ( const nlohmann::json aJson,
const std::string &  aKey,
ResultType  aDefault = ResultType() 
)
staticprotectedinherited

Helper to retrieve a value from a JSON object (dictionary) as a certain result type.

Template Parameters
ResultTypeis the type of the retrieved value.
Parameters
aJsonis the object to act on .
aKeyis the object key to retrieve the value for.
Returns
the result, or aDefault if aKey is not found.

Definition at line 842 of file json_settings.cpp.

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}

◆ FormatAsString()

const std::string JSON_SETTINGS::FormatAsString ( ) const
inherited

Definition at line 471 of file json_settings.cpp.

472{
474
475 std::stringstream buffer;
476 buffer << std::setw( 2 ) << *m_internals << std::endl;
477
478 return buffer.str();
479}
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:41
std::vector< FAB_LAYER_COLOR > dummy

References dummy, and JSON_SETTINGS::m_internals.

Referenced by ROUTER_TOOL::saveRouterDebugLog().

◆ fromLegacy()

template<typename ValueType >
template bool JSON_SETTINGS::fromLegacy< bool > ( wxConfigBase *  aConfig,
const std::string &  aKey,
const std::string &  aDest 
)
protectedinherited

Translates a legacy wxConfig value to a given JSON pointer value.

Template Parameters
ValueTypeis the basic type of the value
Parameters
aConfigis the legacy config to read from
aKeyis the key (within the current path) to read
aDestis a string that will form a JSON pointer (key1.key2.key3) to write to

Definition at line 695 of file json_settings.cpp.

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}

◆ fromLegacyColor()

bool JSON_SETTINGS::fromLegacyColor ( wxConfigBase *  aConfig,
const std::string &  aKey,
const std::string &  aDest 
)
protectedinherited

Translates a legacy COLOR4D stored in a wxConfig string to a given JSON pointer value.

Parameters
aConfigis the legacy config to read from
aKeyis the key (within the current path) to read
aDestis a string that will form a JSON pointer (key1.key2.key3) to write to

Definition at line 755 of file json_settings.cpp.

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}
int color
Definition: DXF_plotter.cpp:57
A color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:104

References color.

Referenced by APP_SETTINGS_BASE::migrateWindowConfig().

◆ fromLegacyString()

bool JSON_SETTINGS::fromLegacyString ( wxConfigBase *  aConfig,
const std::string &  aKey,
const std::string &  aDest 
)
protectedinherited

Translates a legacy wxConfig string value to a given JSON pointer value.

Parameters
aConfigis the legacy config to read from
aKeyis the key (within the current path) to read
aDestis a string that will form a JSON pointer (key1.key2.key3) to write to

Definition at line 731 of file json_settings.cpp.

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}

Referenced by PROJECT_FILE::MigrateFromLegacy(), APP_SETTINGS_BASE::MigrateFromLegacy(), BITMAP2CMP_SETTINGS::MigrateFromLegacy(), EESCHEMA_SETTINGS::MigrateFromLegacy(), SYMBOL_EDITOR_SETTINGS::MigrateFromLegacy(), GERBVIEW_SETTINGS::MigrateFromLegacy(), FOOTPRINT_EDITOR_SETTINGS::MigrateFromLegacy(), MigrateFromLegacy(), PCB_CALCULATOR_SETTINGS::MigrateFromLegacy(), PCBNEW_SETTINGS::MigrateFromLegacy(), and APP_SETTINGS_BASE::migrateWindowConfig().

◆ Get() [1/2]

template<>
std::optional< wxString > JSON_SETTINGS::Get ( const std::string &  aPath) const
inherited

Definition at line 813 of file json_settings.cpp.

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}
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....

References JSON_SETTINGS::GetJson().

◆ Get() [2/2]

template<typename ValueType >
template std::optional< unsigned long long > JSON_SETTINGS::Get< unsigned long long > ( const std::string &  aPath) const
inherited

Fetches a value from within the JSON document.

Will return an empty optional if the value is not found or a mismatching type.

Template Parameters
ValueTypeis the type to cast to
Parameters
aPathis the path within the document to retrieve
Returns
a value from within this document

Definition at line 534 of file json_settings.cpp.

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}

References JSON_SETTINGS::GetJson().

Referenced by COLOR_MAP_PARAM::Load(), PARAM< ValueType >::Load(), PARAM_ENUM< EnumType >::Load(), PARAM_LAMBDA< ValueType >::Load(), PARAM_SCALED< ValueType >::Load(), COLOR_MAP_PARAM::MatchesFile(), PARAM< ValueType >::MatchesFile(), PARAM_PATH::MatchesFile(), PARAM_ENUM< EnumType >::MatchesFile(), PARAM_LAMBDA< ValueType >::MatchesFile(), and PARAM_SCALED< ValueType >::MatchesFile().

◆ getFileExt()

virtual wxString JSON_SETTINGS::getFileExt ( ) const
inlineprotectedvirtualinherited

Reimplemented in DATABASE_LIB_SETTINGS, PROJECT_FILE, and PROJECT_LOCAL_SETTINGS.

Definition at line 275 of file json_settings.h.

276 {
277 return wxT( "json" );
278 }

Referenced by JSON_SETTINGS::GetFullFilename(), JSON_SETTINGS::LoadFromFile(), and JSON_SETTINGS::SaveToFile().

◆ GetFilename()

◆ GetFullFilename()

wxString JSON_SETTINGS::GetFullFilename ( ) const
inherited

Definition at line 105 of file json_settings.cpp.

106{
107 return wxString( m_filename + "." + getFileExt() );
108}
virtual wxString getFileExt() const

References JSON_SETTINGS::getFileExt(), and JSON_SETTINGS::m_filename.

Referenced by JSON_SETTINGS::JSON_SETTINGS(), JSON_SETTINGS::LoadFromFile(), NESTED_SETTINGS::LoadFromFile(), and JSON_SETTINGS::SaveToFile().

◆ GetJson()

std::optional< nlohmann::json > JSON_SETTINGS::GetJson ( const std::string &  aPath) const
inherited

Fetches a JSON object that is a subset of this JSON_SETTINGS object, using a path of the form "key1.key2.key3" to refer to nested objects.

Parameters
aPathis a string containing one or more keys separated by '.'
Returns
a JSON object from within this one

Definition at line 514 of file json_settings.cpp.

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}

References JSON_SETTINGS::m_internals.

Referenced by JSON_SETTINGS::Get(), PARAM_LAMBDA< ValueType >::Load(), PARAM_LIST< Type >::Load(), PARAM_SET< Type >::Load(), PARAM_MAP< Value >::Load(), PARAM_LAMBDA< ValueType >::MatchesFile(), PARAM_LIST< Type >::MatchesFile(), PARAM_SET< Type >::MatchesFile(), PARAM_PATH_LIST::MatchesFile(), PARAM_MAP< Value >::MatchesFile(), PARAM_WXSTRING_MAP::MatchesFile(), SETTINGS_MANAGER::SaveColorSettings(), and NESTED_SETTINGS::SaveToFile().

◆ getLegacy3DHollerith()

bool COMMON_SETTINGS::getLegacy3DHollerith ( const std::string &  aString,
size_t &  aIndex,
wxString &  aResult 
)
staticprivate

Definition at line 693 of file common_settings.cpp.

695{
696 aResult.clear();
697
698 if( aIndex >= aString.size() )
699 {
700 std::ostringstream ostr;
701 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
702 wxString errmsg = wxS( "bad Hollerith string on line" );
703 ostr << " * " << errmsg.ToUTF8() << "\n'" << aString << "'";
704 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
705
706 return false;
707 }
708
709 size_t i2 = aString.find( '"', aIndex );
710
711 if( std::string::npos == i2 )
712 {
713 std::ostringstream ostr;
714 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
715 wxString errmsg = wxS( "missing opening quote mark in config file" );
716 ostr << " * " << errmsg.ToUTF8() << "\n'" << aString << "'";
717 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
718
719 return false;
720 }
721
722 ++i2;
723
724 if( i2 >= aString.size() )
725 {
726 std::ostringstream ostr;
727 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
728 wxString errmsg = wxS( "invalid entry (unexpected end of line)" );
729 ostr << " * " << errmsg.ToUTF8() << "\n'" << aString << "'";
730 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
731
732 return false;
733 }
734
735 std::string tnum;
736
737 while( aString[i2] >= '0' && aString[i2] <= '9' )
738 tnum.append( 1, aString[i2++] );
739
740 if( tnum.empty() || aString[i2++] != ':' )
741 {
742 std::ostringstream ostr;
743 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
744 wxString errmsg = wxS( "bad Hollerith string on line" );
745 ostr << " * " << errmsg.ToUTF8() << "\n'" << aString << "'";
746 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
747
748 return false;
749 }
750
751 std::istringstream istr;
752 istr.str( tnum );
753 size_t nchars;
754 istr >> nchars;
755
756 if( ( i2 + nchars ) >= aString.size() )
757 {
758 std::ostringstream ostr;
759 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
760 wxString errmsg = wxS( "invalid entry (unexpected end of line)" );
761 ostr << " * " << errmsg.ToUTF8() << "\n'" << aString << "'";
762 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
763
764 return false;
765 }
766
767 if( nchars > 0 )
768 {
769 aResult = wxString::FromUTF8( aString.substr( i2, nchars ).c_str() );
770 i2 += nchars;
771 }
772
773 if( i2 >= aString.size() || aString[i2] != '"' )
774 {
775 std::ostringstream ostr;
776 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
777 wxString errmsg = wxS( "missing closing quote mark in config file" );
778 ostr << " * " << errmsg.ToUTF8() << "\n'" << aString << "'";
779 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
780
781 return false;
782 }
783
784 aIndex = i2 + 1;
785 return true;
786}

References traceSettings.

Referenced by readLegacy3DResolverCfg().

◆ getLegacyFileExt()

virtual wxString JSON_SETTINGS::getLegacyFileExt ( ) const
inlineprotectedvirtualinherited

Reimplemented in PROJECT_FILE, and PROJECT_LOCAL_SETTINGS.

Definition at line 280 of file json_settings.h.

281 {
282 return wxEmptyString;
283 }

Referenced by JSON_SETTINGS::LoadFromFile().

◆ GetLocation()

SETTINGS_LOC JSON_SETTINGS::GetLocation ( ) const
inlineinherited

Definition at line 80 of file json_settings.h.

80{ return m_location; }
SETTINGS_LOC m_location
The location of this settings file (.

References JSON_SETTINGS::m_location.

Referenced by SETTINGS_MANAGER::GetPathForSettingsFile().

◆ InitializeEnvironment()

void COMMON_SETTINGS::InitializeEnvironment ( )

Creates the built-in environment variables and sets their default values.

Definition at line 549 of file common_settings.cpp.

550{
551 auto addVar =
552 [&]( const wxString& aKey, const wxString& aDefault )
553 {
554 m_Env.vars[aKey] = ENV_VAR_ITEM( aKey, aDefault, aDefault );
555
556 wxString envValue;
557
558 if( wxGetEnv( aKey, &envValue ) == true && !envValue.IsEmpty() )
559 {
560 m_Env.vars[aKey].SetValue( envValue );
561 m_Env.vars[aKey].SetDefinedExternally();
562 wxLogTrace( traceEnvVars,
563 wxS( "InitializeEnvironment: Entry %s defined externally as %s" ), aKey,
564 envValue );
565 }
566 else
567 {
568 wxLogTrace( traceEnvVars, wxS( "InitializeEnvironment: Setting entry %s to default %s" ),
569 aKey, aDefault );
570 }
571 };
572
573 wxFileName basePath( PATHS::GetStockEDALibraryPath(), wxEmptyString );
574
575 wxFileName path( basePath );
576 path.AppendDir( wxT( "footprints" ) );
577 addVar( wxT( "KICAD7_FOOTPRINT_DIR" ), path.GetFullPath() );
578
579 path = basePath;
580 path.AppendDir( wxT( "3dmodels" ) );
581 addVar( wxT( "KICAD7_3DMODEL_DIR" ), path.GetFullPath() );
582
583 addVar( wxT( "KICAD7_TEMPLATE_DIR" ), PATHS::GetStockTemplatesPath() );
584
585 addVar( wxT( "KICAD_USER_TEMPLATE_DIR" ), PATHS::GetUserTemplatesPath() );
586
587 addVar( wxT( "KICAD7_3RD_PARTY" ), PATHS::GetDefault3rdPartyPath() );
588
589 path = basePath;
590 path.AppendDir( wxT( "symbols" ) );
591 addVar( wxT( "KICAD7_SYMBOL_DIR" ), path.GetFullPath() );
592}
static wxString GetUserTemplatesPath()
Gets the user path for custom templates.
Definition: paths.cpp:86
static wxString GetStockEDALibraryPath()
Gets the stock (install) EDA library data path, which is the base path for templates,...
Definition: paths.cpp:186
static wxString GetDefault3rdPartyPath()
Gets the default path for PCM packages.
Definition: paths.cpp:129
static wxString GetStockTemplatesPath()
Gets the stock (install) templates path.
Definition: paths.cpp:242

References PATHS::GetDefault3rdPartyPath(), PATHS::GetStockEDALibraryPath(), PATHS::GetStockTemplatesPath(), PATHS::GetUserTemplatesPath(), m_Env, path, traceEnvVars, and COMMON_SETTINGS::ENVIRONMENT::vars.

Referenced by PGM_BASE::InitPgm().

◆ Internals()

JSON_SETTINGS_INTERNALS * JSON_SETTINGS::Internals ( )
inherited

Definition at line 123 of file json_settings.cpp.

124{
125 return m_internals.get();
126}

References JSON_SETTINGS::m_internals.

Referenced by COLOR_SETTINGS::migrateSchema0to1(), and SETTINGS_MANAGER::SaveColorSettings().

◆ IsReadOnly()

◆ Load()

void JSON_SETTINGS::Load ( )
virtualinherited

Updates the parameters of this object based on the current JSON document contents.

Definition at line 129 of file json_settings.cpp.

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}
bool m_resetParamsIfMissing
Whether or not to set parameters to their default value if missing from JSON on Load()

References JSON_SETTINGS::m_params, JSON_SETTINGS::m_resetParamsIfMissing, and traceSettings.

Referenced by COLOR_SETTINGS::CreateBuiltinColorSettings(), JSON_SETTINGS::LoadFromFile(), BOARD_DESIGN_SETTINGS::LoadFromFile(), NESTED_SETTINGS::LoadFromFile(), JSON_SETTINGS::LoadFromRawFile(), COLOR_SETTINGS::migrateSchema0to1(), PANEL_3D_DISPLAY_OPTIONS::ResetPanel(), PANEL_3D_OPENGL_OPTIONS::ResetPanel(), PANEL_3D_RAYTRACING_OPTIONS::ResetPanel(), PANEL_EESCHEMA_ANNOTATION_OPTIONS::ResetPanel(), PANEL_EESCHEMA_DISPLAY_OPTIONS::ResetPanel(), PANEL_EESCHEMA_EDITING_OPTIONS::ResetPanel(), PANEL_SYM_DISPLAY_OPTIONS::ResetPanel(), PANEL_SYM_EDITING_OPTIONS::ResetPanel(), PANEL_GERBVIEW_DISPLAY_OPTIONS::ResetPanel(), PANEL_PL_EDITOR_DISPLAY_OPTIONS::ResetPanel(), PANEL_DISPLAY_OPTIONS::ResetPanel(), PANEL_EDIT_OPTIONS::ResetPanel(), PANEL_FP_EDITOR_DEFAULTS::ResetPanel(), PANEL_PCBNEW_DISPLAY_ORIGIN::ResetPanel(), and SETTINGS_MANAGER::SaveColorSettings().

◆ LoadFromFile()

bool JSON_SETTINGS::LoadFromFile ( const wxString &  aDirectory = "")
virtualinherited

Loads the backing file from disk and then calls Load()

Parameters
aDirectoryis the path to the file
Returns
true if the file was found on disk and loaded or migrated

Reimplemented in BOARD_DESIGN_SETTINGS, and NESTED_SETTINGS.

Definition at line 146 of file json_settings.cpp.

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}
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.
wxString GetFullFilename() const
bool Migrate()
Migrates the schema of this settings from the version in the file to the latest version.
virtual bool MigrateFromLegacy(wxConfigBase *aLegacyConfig)
Migrates from wxConfig to JSON-based configuration.
bool m_deleteLegacyAfterMigration
Whether or not to delete legacy file after migration.
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
virtual wxString getLegacyFileExt() const
int m_schemaVersion
Version of this settings schema.
wxString m_legacy_filename
The filename of the wxConfig legacy file (if different from m_filename)
bool parse(std::istream &aStream, bool aVerbose)
Parse a PCB or footprint file from the given input stream.

References JSON_SETTINGS::getFileExt(), JSON_SETTINGS::GetFullFilename(), JSON_SETTINGS::getLegacyFileExt(), JSON_SETTINGS::Load(), JSON_SETTINGS::m_deleteLegacyAfterMigration, JSON_SETTINGS::m_filename, JSON_SETTINGS::m_internals, JSON_SETTINGS::m_legacy_filename, JSON_SETTINGS::m_nested_settings, JSON_SETTINGS::m_schemaVersion, JSON_SETTINGS::m_writeFile, JSON_SETTINGS::Migrate(), JSON_SETTINGS::MigrateFromLegacy(), parse(), path, JSON_SETTINGS::SaveToFile(), and traceSettings.

Referenced by SETTINGS_MANAGER::LoadProject(), SETTINGS_MANAGER::loadProjectFile(), SETTINGS_MANAGER::MigrateIfNeeded(), SAVE_AS_TRAVERSER::OnFile(), and SETTINGS_MANAGER::SaveColorSettings().

◆ LoadFromRawFile()

bool JSON_SETTINGS::LoadFromRawFile ( const wxString &  aPath)
inherited

Definition at line 482 of file json_settings.cpp.

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}

References JSON_SETTINGS::Load(), JSON_SETTINGS::m_internals, parse(), and traceSettings.

◆ Migrate()

bool JSON_SETTINGS::Migrate ( )
inherited

Migrates the schema of this settings from the version in the file to the latest version.

Schema migration doesn't need to be used every time a setting is added! This is intended to be more of an "escape hatch" in the event that we decide to move settings around or make other changes to a settings file format that can't simply be handled by loading a new default

Returns
true if migration was successful

Definition at line 592 of file json_settings.cpp.

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}
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>

References JSON_SETTINGS::m_internals, JSON_SETTINGS::m_migrators, JSON_SETTINGS::m_schemaVersion, and traceSettings.

Referenced by JSON_SETTINGS::LoadFromFile(), and NESTED_SETTINGS::LoadFromFile().

◆ MigrateFromLegacy()

bool COMMON_SETTINGS::MigrateFromLegacy ( wxConfigBase *  aLegacyConfig)
overridevirtual

Migrates from wxConfig to JSON-based configuration.

Should be implemented by any subclasses of JSON_SETTINGS that map to a legacy (wxConfig-based) config file.

Parameters
aLegacyConfigis a wxConfigBase holding a loaded configuration to migrate
Returns
true if migration was successful

Reimplemented from JSON_SETTINGS.

Definition at line 469 of file common_settings.cpp.

470{
471 bool ret = true;
472
473 ret &= fromLegacy<double>( aCfg, "CanvasScale", "appearance.canvas_scale" );
474 ret &= fromLegacy<int>( aCfg, "IconScale", "appearance.icon_scale" );
475 ret &= fromLegacy<bool>( aCfg, "UseIconsInMenus", "appearance.use_icons_in_menus" );
476 ret &= fromLegacy<bool>( aCfg, "ShowEnvVarWarningDialog", "environment.show_warning_dialog" );
477
478 auto load_env_vars =
479 [&]()
480 {
481 wxString key, value;
482 long index = 0;
483 nlohmann::json::json_pointer ptr = m_internals->PointerFromString( "environment.vars" );
484
485 aCfg->SetPath( "EnvironmentVariables" );
486 ( *m_internals )[ptr] = nlohmann::json( {} );
487
488 while( aCfg->GetNextEntry( key, index ) )
489 {
490 if( envVarBlacklist.count( key ) )
491 {
492 wxLogTrace( traceSettings, wxT( "Migrate Env: %s is blacklisted; skipping." ), key );
493 continue;
494 }
495
496 value = aCfg->Read( key, wxEmptyString );
497
498 if( !value.IsEmpty() )
499 {
500 ptr.push_back( key.ToStdString() );
501
502 wxLogTrace( traceSettings, wxT( "Migrate Env: %s=%s" ), ptr.to_string(), value );
503 ( *m_internals )[ptr] = value.ToUTF8();
504
505 ptr.pop_back();
506 }
507 }
508
509 aCfg->SetPath( ".." );
510 };
511
512 load_env_vars();
513
514 bool mousewheel_pan = false;
515
516 if( aCfg->Read( "MousewheelPAN", &mousewheel_pan ) && mousewheel_pan )
517 {
518 Set( "input.horizontal_pan", true );
519 Set( "input.scroll_modifier_pan_h", static_cast<int>( WXK_SHIFT ) );
520 Set( "input.scroll_modifier_pan_v", 0 );
521 Set( "input.scroll_modifier_zoom", static_cast<int>( WXK_CONTROL ) );
522 }
523
524 ret &= fromLegacy<bool>( aCfg, "AutoPAN", "input.auto_pan" );
525 ret &= fromLegacy<bool>( aCfg, "ImmediateActions", "input.immediate_actions" );
526 ret &= fromLegacy<bool>( aCfg, "PreferSelectionToDragging", "input.prefer_select_to_drag" );
527 ret &= fromLegacy<bool>( aCfg, "MoveWarpsCursor", "input.warp_mouse_on_move" );
528 ret &= fromLegacy<bool>( aCfg, "ZoomNoCenter", "input.center_on_zoom" );
529
530 // This was stored inverted in legacy config
531 if( std::optional<bool> value = Get<bool>( "input.center_on_zoom" ) )
532 Set( "input.center_on_zoom", !( *value ) );
533
534 ret &= fromLegacy<int>( aCfg, "OpenGLAntialiasingMode", "graphics.opengl_antialiasing_mode" );
535 ret &= fromLegacy<int>( aCfg, "CairoAntialiasingMode", "graphics.cairo_antialiasing_mode" );
536
537 ret &= fromLegacy<int>( aCfg, "AutoSaveInterval", "system.autosave_interval" );
538 ret &= fromLegacyString( aCfg, "Editor", "system.editor_name" );
539 ret &= fromLegacy<int>( aCfg, "FileHistorySize", "system.file_history_size" );
540 ret &= fromLegacyString( aCfg, "LanguageID", "system.language" );
541 ret &= fromLegacyString( aCfg, "PdfBrowserName", "system.pdf_viewer_name" );
542 ret &= fromLegacy<bool>( aCfg, "UseSystemBrowser", "system.use_system_pdf_viewer" );
543 ret &= fromLegacyString( aCfg, "WorkingDir", "system.working_dir" );
544
545 return ret;
546}
bool fromLegacyString(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig string value to a given JSON pointer value.
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...
const std::set< wxString > envVarBlacklist
! The following environment variables will never be migrated from a previous version

References envVarBlacklist, JSON_SETTINGS::fromLegacyString(), JSON_SETTINGS::m_internals, JSON_SETTINGS::Set(), and traceSettings.

◆ migrateSchema0to1()

bool COMMON_SETTINGS::migrateSchema0to1 ( )
private

Schema version 0 to 1:

mousewheel_pan is replaced by explicit settings for scroll wheel behavior

Definition at line 355 of file common_settings.cpp.

356{
363 nlohmann::json::json_pointer mwp_pointer( "/input/mousewheel_pan"_json_pointer );
364
365 bool mwp = false;
366
367 try
368 {
369 mwp = m_internals->at( mwp_pointer );
370 m_internals->At( "input" ).erase( "mousewheel_pan" );
371 }
372 catch( ... )
373 {
374 wxLogTrace( traceSettings, wxT( "COMMON_SETTINGS::Migrate 0->1: mousewheel_pan not found" ) );
375 }
376
377 if( mwp )
378 {
379 ( *m_internals )[nlohmann::json::json_pointer( "/input/horizontal_pan" )] = true;
380
381 ( *m_internals )[nlohmann::json::json_pointer( "/input/scroll_modifier_pan_h" )] = WXK_SHIFT;
382 ( *m_internals )[nlohmann::json::json_pointer( "/input/scroll_modifier_pan_v" )] = 0;
383 ( *m_internals )[nlohmann::json::json_pointer( "/input/scroll_modifier_zoom" )] = WXK_CONTROL;
384 }
385 else
386 {
387 ( *m_internals )[nlohmann::json::json_pointer( "/input/horizontal_pan" )] = false;
388
389 ( *m_internals )[nlohmann::json::json_pointer( "/input/scroll_modifier_pan_h" )] = WXK_CONTROL;
390 ( *m_internals )[nlohmann::json::json_pointer( "/input/scroll_modifier_pan_v" )] = WXK_SHIFT;
391 ( *m_internals )[nlohmann::json::json_pointer( "/input/scroll_modifier_zoom" )] = 0;
392 }
393
394 return true;
395}

References JSON_SETTINGS::m_internals, and traceSettings.

◆ migrateSchema1to2()

bool COMMON_SETTINGS::migrateSchema1to2 ( )
private

Definition at line 398 of file common_settings.cpp.

399{
400 nlohmann::json::json_pointer v1_pointer( "/input/prefer_select_to_drag"_json_pointer );
401
402 bool prefer_selection = false;
403
404 try
405 {
406 prefer_selection = m_internals->at( v1_pointer );
407 m_internals->at( nlohmann::json::json_pointer( "/input"_json_pointer ) ).erase( "prefer_select_to_drag" );
408 }
409 catch( ... )
410 {
411 wxLogTrace( traceSettings, wxT( "COMMON_SETTINGS::Migrate 1->2: prefer_select_to_drag not found" ) );
412 }
413
414 if( prefer_selection )
415 ( *m_internals )[nlohmann::json::json_pointer( "/input/mouse_left" )] = MOUSE_DRAG_ACTION::SELECT;
416 else
417 ( *m_internals )[nlohmann::json::json_pointer( "/input/mouse_left" )] = MOUSE_DRAG_ACTION::DRAG_ANY;
418
419 return true;
420}

References DRAG_ANY, JSON_SETTINGS::m_internals, SELECT, and traceSettings.

◆ migrateSchema2to3()

bool COMMON_SETTINGS::migrateSchema2to3 ( )
private

Definition at line 423 of file common_settings.cpp.

424{
425 wxFileName cfgpath;
426 cfgpath.AssignDir( SETTINGS_MANAGER::GetUserSettingsPath() );
427 cfgpath.AppendDir( wxT( "3d" ) );
428 cfgpath.SetFullName( wxS( "3Dresolver.cfg" ) );
429 cfgpath.MakeAbsolute();
430
431 std::vector<LEGACY_3D_SEARCH_PATH> legacyPaths;
432 readLegacy3DResolverCfg( cfgpath.GetFullPath(), legacyPaths );
433
434 // env variables have a limited allowed character set for names
435 wxRegEx nonValidCharsRegex( wxS( "[^A-Z0-9_]+" ), wxRE_ADVANCED );
436
437 for( const LEGACY_3D_SEARCH_PATH& path : legacyPaths )
438 {
439 wxString key = path.m_Alias;
440 const wxString& val = path.m_Pathvar;
441
442 // The 3d alias config didnt use the same naming restrictions as real env variables
443 // We need to sanitize them
444
445 // upper case only
446 key.MakeUpper();
447 // logically swap - with _
448 key.Replace( wxS( "-" ), wxS( "_" ) );
449
450 // remove any other chars
451 nonValidCharsRegex.Replace( &key, wxEmptyString );
452
453 if( !m_Env.vars.count( key ) )
454 {
455 wxLogTrace( traceEnvVars, wxS( "COMMON_SETTINGS: Loaded new var: %s = %s" ), key, val );
456 m_Env.vars[key] = ENV_VAR_ITEM( key, val );
457 }
458 }
459
460 if( cfgpath.FileExists() )
461 {
462 wxRemoveFile( cfgpath.GetFullPath() );
463 }
464
465 return true;
466}
bool readLegacy3DResolverCfg(const wxString &aPath, std::vector< LEGACY_3D_SEARCH_PATH > &aSearchPaths)
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.

References SETTINGS_MANAGER::GetUserSettingsPath(), m_Env, path, readLegacy3DResolverCfg(), traceEnvVars, and COMMON_SETTINGS::ENVIRONMENT::vars.

◆ readLegacy3DResolverCfg()

bool COMMON_SETTINGS::readLegacy3DResolverCfg ( const wxString &  aPath,
std::vector< LEGACY_3D_SEARCH_PATH > &  aSearchPaths 
)
private

Definition at line 595 of file common_settings.cpp.

597{
598 wxFileName cfgpath( path );
599
600 // This should be the same as wxWidgets 3.0 wxPATH_NORM_ALL which is deprecated in 3.1.
601 // There are known issues with environment variable expansion so maybe we should be using
602 // our own ExpandEnvVarSubstitutions() here instead.
603 cfgpath.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
604 wxString cfgname = cfgpath.GetFullPath();
605
606 std::ifstream cfgFile;
607 std::string cfgLine;
608
609 if( !wxFileName::Exists( cfgname ) )
610 {
611 std::ostringstream ostr;
612 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
613 wxString errmsg = "no 3D configuration file";
614 ostr << " * " << errmsg.ToUTF8() << " '";
615 ostr << cfgname.ToUTF8() << "'";
616 wxLogTrace( traceSettings, "%s\n", ostr.str().c_str() );
617 return false;
618 }
619
620 cfgFile.open( cfgname.ToUTF8() );
621
622 if( !cfgFile.is_open() )
623 {
624 std::ostringstream ostr;
625 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
626 wxString errmsg = wxS( "Could not open configuration file" );
627 ostr << " * " << errmsg.ToUTF8() << " '" << cfgname.ToUTF8() << "'";
628 wxLogTrace( traceSettings, wxS( "%s\n" ), ostr.str().c_str() );
629 return false;
630 }
631
632 int lineno = 0;
633 LEGACY_3D_SEARCH_PATH al;
634 size_t idx;
635 int vnum = 0; // version number
636
637 while( cfgFile.good() )
638 {
639 cfgLine.clear();
640 std::getline( cfgFile, cfgLine );
641 ++lineno;
642
643 if( cfgLine.empty() )
644 {
645 if( cfgFile.eof() )
646 break;
647
648 continue;
649 }
650
651 if( 1 == lineno && cfgLine.compare( 0, 2, "#V" ) == 0 )
652 {
653 // extract the version number and parse accordingly
654 if( cfgLine.size() > 2 )
655 {
656 std::istringstream istr;
657 istr.str( cfgLine.substr( 2 ) );
658 istr >> vnum;
659 }
660
661 continue;
662 }
663
664 idx = 0;
665
666 if( !getLegacy3DHollerith( cfgLine, idx, al.m_Alias ) )
667 continue;
668
669 // Don't add KICAD7_3DMODEL_DIR, one of its legacy equivalents, or KIPRJMOD from a
670 // config file. They're system variables are are defined at runtime.
671 if( al.m_Alias == wxS( "${KICAD7_3DMODEL_DIR}" ) || al.m_Alias == wxS( "${KIPRJMOD}" )
672 || al.m_Alias == wxS( "$(KIPRJMOD)" ) || al.m_Alias == wxS( "${KISYS3DMOD}" )
673 || al.m_Alias == wxS( "$(KISYS3DMOD)" ) )
674 {
675 continue;
676 }
677
678 if( !getLegacy3DHollerith( cfgLine, idx, al.m_Pathvar ) )
679 continue;
680
681 if( !getLegacy3DHollerith( cfgLine, idx, al.m_Description ) )
682 continue;
683
684 aSearchPaths.push_back( al );
685 }
686
687 cfgFile.close();
688
689 return true;
690}
static bool getLegacy3DHollerith(const std::string &aString, size_t &aIndex, wxString &aResult)
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition: wx_filename.h:38

References FN_NORMALIZE_FLAGS, getLegacy3DHollerith(), COMMON_SETTINGS::LEGACY_3D_SEARCH_PATH::m_Alias, COMMON_SETTINGS::LEGACY_3D_SEARCH_PATH::m_Description, COMMON_SETTINGS::LEGACY_3D_SEARCH_PATH::m_Pathvar, path, and traceSettings.

Referenced by migrateSchema2to3().

◆ registerMigration()

void JSON_SETTINGS::registerMigration ( int  aOldSchemaVersion,
int  aNewSchemaVersion,
std::function< bool(void)>  aMigrator 
)
protectedinherited

Registers a migration from one schema version to another.

If the schema version in the file loaded from disk is less than the schema version of the JSON_SETTINGS class, migration functions will be called one after the other until the data is up-to-date.

Parameters
aOldSchemaVersionis the starting schema version for this migration
aNewSchemaVersionis the ending schema version for this migration
aMigratoris a function that performs the migration and returns true if successful

Definition at line 583 of file json_settings.cpp.

585{
586 wxASSERT( aNewSchemaVersion > aOldSchemaVersion );
587 wxASSERT( aNewSchemaVersion <= m_schemaVersion );
588 m_migrators[aOldSchemaVersion] = std::make_pair( aNewSchemaVersion, aMigrator );
589}

References JSON_SETTINGS::m_migrators, and JSON_SETTINGS::m_schemaVersion.

Referenced by BOARD_DESIGN_SETTINGS::BOARD_DESIGN_SETTINGS(), COLOR_SETTINGS::COLOR_SETTINGS(), EDA_3D_VIEWER_SETTINGS::EDA_3D_VIEWER_SETTINGS(), EESCHEMA_SETTINGS::EESCHEMA_SETTINGS(), FOOTPRINT_EDITOR_SETTINGS::FOOTPRINT_EDITOR_SETTINGS(), NET_SETTINGS::NET_SETTINGS(), PCBNEW_SETTINGS::PCBNEW_SETTINGS(), PROJECT_LOCAL_SETTINGS::PROJECT_LOCAL_SETTINGS(), SCHEMATIC_SETTINGS::SCHEMATIC_SETTINGS(), and SYMBOL_EDITOR_SETTINGS::SYMBOL_EDITOR_SETTINGS().

◆ ReleaseNestedSettings()

void JSON_SETTINGS::ReleaseNestedSettings ( NESTED_SETTINGS aSettings)
inherited

Saves and frees a nested settings object, if it exists within this one.

Parameters
aSettingsis a pointer to a NESTED_SETTINGS that has already been added to this one

Definition at line 790 of file json_settings.cpp.

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}
SETTINGS_MANAGER * m_manager
A pointer to the settings manager managing this file (may be null)
void SetParent(JSON_SETTINGS *aParent, bool aLoadFromFile=true)

References JSON_SETTINGS::m_manager, JSON_SETTINGS::m_nested_settings, NESTED_SETTINGS::SetParent(), and traceSettings.

Referenced by BOARD_DESIGN_SETTINGS::~BOARD_DESIGN_SETTINGS(), ERC_SETTINGS::~ERC_SETTINGS(), NESTED_SETTINGS::~NESTED_SETTINGS(), NET_SETTINGS::~NET_SETTINGS(), and SCHEMATIC_SETTINGS::~SCHEMATIC_SETTINGS().

◆ ResetToDefaults()

void JSON_SETTINGS::ResetToDefaults ( )
inherited

Resets all parameters to default values.

Does NOT write to file or update underlying JSON.

Definition at line 364 of file json_settings.cpp.

365{
366 for( auto param : m_params )
367 param->SetDefault();
368}

References JSON_SETTINGS::m_params.

Referenced by EDA_3D_VIEWER_FRAME::Process_Special_Functions(), PANEL_COMMON_SETTINGS::ResetPanel(), and PANEL_MOUSE_SETTINGS::ResetPanel().

◆ SaveToFile()

bool JSON_SETTINGS::SaveToFile ( const wxString &  aDirectory = "",
bool  aForce = false 
)
virtualinherited
   Calls Store() and then writes the contents of the JSON document to a file
   @param aDirectory is the directory to save to, including trailing separator

c *

Returns
true if the file was saved

Reimplemented in PROJECT_FILE, PROJECT_LOCAL_SETTINGS, and NESTED_SETTINGS.

Definition at line 371 of file json_settings.cpp.

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}
bool m_createIfDefault
Whether or not the backing store file should be created if all parameters are still at their default ...
bool m_createIfMissing
Whether or not the backing store file should be created it if doesn't exist.
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...

References dummy, JSON_SETTINGS::getFileExt(), JSON_SETTINGS::GetFullFilename(), JSON_SETTINGS::m_createIfDefault, JSON_SETTINGS::m_createIfMissing, JSON_SETTINGS::m_filename, JSON_SETTINGS::m_internals, JSON_SETTINGS::m_nested_settings, JSON_SETTINGS::m_writeFile, path, JSON_SETTINGS::Store(), and traceSettings.

Referenced by JSON_SETTINGS::LoadFromFile(), SETTINGS_MANAGER::MigrateIfNeeded(), PANEL_COLOR_SETTINGS::OnThemeChanged(), PROJECT::PinLibrary(), PROJECT_FILE::SaveAs(), PROJECT_LOCAL_SETTINGS::SaveAs(), SETTINGS_MANAGER::SaveColorSettings(), PROJECT_FILE::SaveToFile(), PROJECT_LOCAL_SETTINGS::SaveToFile(), PGM_BASE::SetLanguage(), and PROJECT::UnpinLibrary().

◆ Set() [1/3]

template<typename ValueType >
template void JSON_SETTINGS::Set< const char * > ( const std::string &  aPath,
ValueType  aVal 
)
inherited

Stores a value into the JSON document Will throw an exception if ValueType isn't something that the library can handle.

Template Parameters
ValueTypeis the type to store
Parameters
aPathis a path to store in the form "key1.key2.key3"
aValis the value to store

Definition at line 564 of file json_settings.cpp.

565{
566 m_internals->SetFromString( aPath, aVal );
567}

References JSON_SETTINGS::m_internals.

Referenced by COLOR_SETTINGS::COLOR_SETTINGS(), EDA_3D_VIEWER_SETTINGS::EDA_3D_VIEWER_SETTINGS(), EESCHEMA_SETTINGS::EESCHEMA_SETTINGS(), BOARD_DESIGN_SETTINGS::LoadFromFile(), APP_SETTINGS_BASE::migrateFindReplace(), PROJECT_FILE::MigrateFromLegacy(), APP_SETTINGS_BASE::MigrateFromLegacy(), EDA_3D_VIEWER_SETTINGS::MigrateFromLegacy(), EESCHEMA_SETTINGS::MigrateFromLegacy(), SYMBOL_EDITOR_SETTINGS::MigrateFromLegacy(), GERBVIEW_SETTINGS::MigrateFromLegacy(), FOOTPRINT_EDITOR_SETTINGS::MigrateFromLegacy(), MigrateFromLegacy(), KICAD_SETTINGS::MigrateFromLegacy(), PCBNEW_SETTINGS::MigrateFromLegacy(), BOARD_DESIGN_SETTINGS::migrateSchema0to1(), FOOTPRINT_EDITOR_SETTINGS::migrateSchema0to1(), COLOR_SETTINGS::migrateSchema0to1(), PCBNEW_SETTINGS::PCBNEW_SETTINGS(), PROJECT_FILE::SaveAs(), PROJECT_LOCAL_SETTINGS::SaveAs(), PROJECT_FILE::SaveToFile(), PROJECT_LOCAL_SETTINGS::SaveToFile(), SCHEMATIC_SETTINGS::SCHEMATIC_SETTINGS(), COLOR_MAP_PARAM::Store(), PARAM< ValueType >::Store(), PARAM_PATH::Store(), PARAM_ENUM< EnumType >::Store(), PARAM_LAMBDA< ValueType >::Store(), PARAM_SCALED< ValueType >::Store(), PARAM_LIST< Type >::Store(), PARAM_SET< Type >::Store(), PARAM_PATH_LIST::Store(), and PARAM_MAP< Value >::Store().

◆ Set() [2/3]

template<>
void JSON_SETTINGS::Set ( const std::string &  aPath,
wxString  aVal 
)
inherited

Definition at line 822 of file json_settings.cpp.

823{
824 ( *m_internals )[aPath] = aVal.ToUTF8();
825}

◆ Set() [3/3]

template<>
void JSON_SETTINGS::Set ( const std::string &  aPath,
wxString  aVal 
)
inherited

◆ SetFilename()

void JSON_SETTINGS::SetFilename ( const wxString &  aFilename)
inlineinherited

◆ SetIfPresent() [1/4]

bool JSON_SETTINGS::SetIfPresent ( const nlohmann::json aObj,
const std::string &  aPath,
bool &  aTarget 
)
staticinherited

Sets the given bool if the given key/path is present.

Parameters
aObjis the source object
aTargetis the storage destination
Returns
True if set, false if not

Definition at line 649 of file json_settings.cpp.

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}

References JSON_SETTINGS_INTERNALS::PointerFromString().

◆ SetIfPresent() [2/4]

bool JSON_SETTINGS::SetIfPresent ( const nlohmann::json aObj,
const std::string &  aPath,
int &  aTarget 
)
staticinherited

Sets the given int if the given key/path is present.

Parameters
aObjis the source object
aTargetis the storage destination
Returns
True if set, false if not

Definition at line 664 of file json_settings.cpp.

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}

References JSON_SETTINGS_INTERNALS::PointerFromString().

◆ SetIfPresent() [3/4]

bool JSON_SETTINGS::SetIfPresent ( const nlohmann::json aObj,
const std::string &  aPath,
unsigned int &  aTarget 
)
staticinherited

Sets the given unsigned int if the given key/path is present.

Parameters
aObjis the source object
aTargetis the storage destination
Returns
True if set, false if not

Definition at line 679 of file json_settings.cpp.

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}

References JSON_SETTINGS_INTERNALS::PointerFromString().

◆ SetIfPresent() [4/4]

bool JSON_SETTINGS::SetIfPresent ( const nlohmann::json aObj,
const std::string &  aPath,
wxString &  aTarget 
)
staticinherited

Sets the given string if the given key/path is present.

Parameters
aObjis the source object
aTargetis the storage destination
Returns
True if set, false if not

Definition at line 634 of file json_settings.cpp.

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}

References JSON_SETTINGS_INTERNALS::PointerFromString().

Referenced by FOOTPRINT_EDITOR_SETTINGS::FOOTPRINT_EDITOR_SETTINGS(), and PROJECT_LOCAL_SETTINGS::PROJECT_LOCAL_SETTINGS().

◆ SetLegacyFilename()

void JSON_SETTINGS::SetLegacyFilename ( const wxString &  aFilename)
inlineinherited

Definition at line 82 of file json_settings.h.

82{ m_legacy_filename = aFilename; }

References JSON_SETTINGS::m_legacy_filename.

Referenced by SYMBOL_EDITOR_SETTINGS::SYMBOL_EDITOR_SETTINGS().

◆ SetLocation()

void JSON_SETTINGS::SetLocation ( SETTINGS_LOC  aLocation)
inlineinherited

Definition at line 79 of file json_settings.h.

79{ m_location = aLocation; }

References JSON_SETTINGS::m_location.

Referenced by COLOR_SETTINGS::COLOR_SETTINGS().

◆ SetManager()

void JSON_SETTINGS::SetManager ( SETTINGS_MANAGER aManager)
inlineinherited

Definition at line 191 of file json_settings.h.

192 {
193 m_manager = aManager;
194 }

References JSON_SETTINGS::m_manager.

◆ SetReadOnly()

◆ Store()

bool JSON_SETTINGS::Store ( )
virtualinherited

Stores the current parameters into the JSON document represented by this object Note: this doesn't do any writing to disk; that's handled by SETTINGS_MANAGER.

Returns
true if any part of the JSON document was updated

Definition at line 350 of file json_settings.cpp.

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}

References JSON_SETTINGS::m_params.

Referenced by PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS(), SETTINGS_MANAGER::SaveColorSettings(), JSON_SETTINGS::SaveToFile(), and NESTED_SETTINGS::SaveToFile().

Member Data Documentation

◆ m_Appearance

◆ m_Backup

◆ m_createIfDefault

bool JSON_SETTINGS::m_createIfDefault
protectedinherited

Whether or not the backing store file should be created if all parameters are still at their default values.

Ignored if m_createIfMissing is false or m_writeFile is false.

Definition at line 318 of file json_settings.h.

Referenced by JSON_SETTINGS::SaveToFile().

◆ m_createIfMissing

bool JSON_SETTINGS::m_createIfMissing
protectedinherited

Whether or not the backing store file should be created it if doesn't exist.

Definition at line 312 of file json_settings.h.

Referenced by JSON_SETTINGS::SaveToFile().

◆ m_deleteLegacyAfterMigration

bool JSON_SETTINGS::m_deleteLegacyAfterMigration
protectedinherited

Whether or not to delete legacy file after migration.

Definition at line 324 of file json_settings.h.

Referenced by JSON_SETTINGS::LoadFromFile(), PROJECT_FILE::PROJECT_FILE(), and PROJECT_LOCAL_SETTINGS::PROJECT_LOCAL_SETTINGS().

◆ m_DoNotShowAgain

DO_NOT_SHOW_AGAIN COMMON_SETTINGS::m_DoNotShowAgain

Definition at line 188 of file common_settings.h.

◆ m_Env

◆ m_filename

◆ m_Graphics

◆ m_Input

◆ m_internals

◆ m_legacy_filename

wxString JSON_SETTINGS::m_legacy_filename
protectedinherited

The filename of the wxConfig legacy file (if different from m_filename)

Definition at line 300 of file json_settings.h.

Referenced by JSON_SETTINGS::LoadFromFile(), and JSON_SETTINGS::SetLegacyFilename().

◆ m_location

SETTINGS_LOC JSON_SETTINGS::m_location
protectedinherited

The location of this settings file (.

See also
SETTINGS_LOC)

Definition at line 303 of file json_settings.h.

Referenced by JSON_SETTINGS::GetLocation(), and JSON_SETTINGS::SetLocation().

◆ m_manager

SETTINGS_MANAGER* JSON_SETTINGS::m_manager
protectedinherited

A pointer to the settings manager managing this file (may be null)

Definition at line 333 of file json_settings.h.

Referenced by FOOTPRINT_EDITOR_SETTINGS::migrateSchema0to1(), COLOR_SETTINGS::migrateSchema0to1(), JSON_SETTINGS::ReleaseNestedSettings(), and JSON_SETTINGS::SetManager().

◆ m_migrators

std::map<int, std::pair<int, std::function<bool()> > > JSON_SETTINGS::m_migrators
protectedinherited

A map of starting schema version to a pair of <ending version, migrator function>

Definition at line 336 of file json_settings.h.

Referenced by JSON_SETTINGS::Migrate(), and JSON_SETTINGS::registerMigration().

◆ m_nested_settings

std::vector<NESTED_SETTINGS*> JSON_SETTINGS::m_nested_settings
protectedinherited

Nested settings files that live inside this one, if any.

Definition at line 309 of file json_settings.h.

Referenced by JSON_SETTINGS::AddNestedSettings(), JSON_SETTINGS::LoadFromFile(), JSON_SETTINGS::ReleaseNestedSettings(), and JSON_SETTINGS::SaveToFile().

◆ m_NetclassPanel

◆ m_PackageManager

PACKAGE_MANAGER COMMON_SETTINGS::m_PackageManager

◆ m_params

◆ m_resetParamsIfMissing

bool JSON_SETTINGS::m_resetParamsIfMissing
protectedinherited

Whether or not to set parameters to their default value if missing from JSON on Load()

Definition at line 327 of file json_settings.h.

Referenced by BOARD_DESIGN_SETTINGS::BOARD_DESIGN_SETTINGS(), and JSON_SETTINGS::Load().

◆ m_schemaVersion

int JSON_SETTINGS::m_schemaVersion
protectedinherited

◆ m_Session

◆ m_System

◆ m_writeFile

bool JSON_SETTINGS::m_writeFile
protectedinherited

The documentation for this class was generated from the following files: