KiCad PCB EDA Suite
SETTINGS_MANAGER Class Reference

#include <settings_manager.h>

Public Member Functions

 SETTINGS_MANAGER (bool aHeadless=false)
 
 ~SETTINGS_MANAGER ()
 
bool IsOK ()
 
void SetKiway (KIWAY *aKiway)
 Associate this setting manager with the given Kiway. More...
 
template<typename T >
T * RegisterSettings (T *aSettings, bool aLoadNow=true)
 Takes ownership of the pointer passed in. More...
 
void Load ()
 
void Load (JSON_SETTINGS *aSettings)
 
void Save ()
 
void Save (JSON_SETTINGS *aSettings)
 
void FlushAndRelease (JSON_SETTINGS *aSettings, bool aSave=true)
 If the given settings object is registered, save it to disk and unregister it. More...
 
template<typename T >
T * GetAppSettings (bool aLoadNow=true)
 Returns a handle to the a given settings by type If the settings have already been loaded, returns the existing pointer. More...
 
COLOR_SETTINGSGetColorSettings (const wxString &aName="user")
 Retrieves a color settings object that applications can read colors from. More...
 
std::vector< COLOR_SETTINGS * > GetColorSettingsList ()
 
void SaveColorSettings (COLOR_SETTINGS *aSettings, const std::string &aNamespace="")
 Safely saves a COLOR_SETTINGS to disk, preserving any changes outside the given namespace. More...
 
COLOR_SETTINGSAddNewColorSettings (const wxString &aFilename)
 Registers a new color settings object with the given filename. More...
 
COLOR_SETTINGSGetMigratedColorSettings ()
 Returns a color theme for storing colors migrated from legacy (5.x and earlier) settings, creating the theme if necessary. More...
 
COMMON_SETTINGSGetCommonSettings () const
 Retrieves the common settings shared by all applications. More...
 
wxString GetPathForSettingsFile (JSON_SETTINGS *aSettings)
 Returns the path a given settings file should be loaded from / stored to. More...
 
bool MigrateIfNeeded ()
 Handles the initialization of the user settings directory and migration from previous KiCad versions as needed. More...
 
void SetMigrationSource (const wxString &aSource)
 Helper for DIALOG_MIGRATE_SETTINGS to specify a source for migration. More...
 
void SetMigrateLibraryTables (bool aMigrate=true)
 
bool GetPreviousVersionPaths (std::vector< wxString > *aName=nullptr)
 Retrieves the name of the most recent previous KiCad version that can be found in the user settings directory. More...
 
void ReloadColorSettings ()
 Re-scans the color themes directory, reloading any changes it finds. More...
 
bool LoadProject (const wxString &aFullPath, bool aSetActive=true)
 Loads a project or sets up a new project with a specified path. More...
 
bool UnloadProject (PROJECT *aProject, bool aSave=true)
 Saves, unloads and unregisters the given PROJECT. More...
 
bool IsProjectOpen () const
 Helper for checking if we have a project open TODO: This should be deprecated along with Prj() once we support multiple projects fully. More...
 
PROJECTPrj () const
 A helper while we are not MDI-capable – return the one and only project. More...
 
PROJECTGetProject (const wxString &aFullPath) const
 Retrieves a loaded project by name. More...
 
std::vector< wxString > GetOpenProjects () const
 
bool SaveProject (const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
 Saves a loaded project. More...
 
void SaveProjectAs (const wxString &aFullPath, PROJECT *aProject=nullptr)
 Sets the currently loaded project path and saves it (pointers remain valid) Note that this will not modify the read-only state of the project, so it will have no effect if the project is marked as read-only! More...
 
void SaveProjectCopy (const wxString &aFullPath, PROJECT *aProject=nullptr)
 Saves a copy of the current project under the given path. More...
 
wxString GetProjectBackupsPath () const
 
bool BackupProject (REPORTER &aReporter) const
 Creates a backup archive of the current project. More...
 
bool TriggerBackupIfNeeded (REPORTER &aReporter) const
 Calls BackupProject if a new backup is needed according to the current backup policy. More...
 

Static Public Member Functions

static bool IsSettingsPathValid (const wxString &aPath)
 Checks if a given path is probably a valid KiCad configuration directory. More...
 
static wxString GetColorSettingsPath ()
 Returns the path where color scheme files are stored; creating it if missing (normally . More...
 
static wxString GetUserSettingsPath ()
 Return the user configuration path used to store KiCad's configuration files. More...
 
static std::string GetSettingsVersion ()
 Parses the current KiCad build version and extracts the major and minor revision to use as the name of the settings directory for this KiCad version. More...
 

Private Member Functions

JSON_SETTINGSregisterSettings (JSON_SETTINGS *aSettings, bool aLoadNow=true)
 
COLOR_SETTINGSloadColorSettingsByName (const wxString &aName)
 Attempts to load a color theme by name (the color theme directory and .json ext are assumed) More...
 
COLOR_SETTINGSregisterColorSettings (const wxString &aFilename, bool aAbsolutePath=false)
 
void loadAllColorSettings ()
 
bool loadProjectFile (PROJECT &aProject)
 Registers a PROJECT_FILE and attempts to load it from disk. More...
 
bool unloadProjectFile (PROJECT *aProject, bool aSave)
 Optionally saves, and then unloads and unregisters the given PROJECT_FILE. More...
 

Static Private Member Functions

static wxString calculateUserSettingsPath (bool aIncludeVer=true, bool aUseEnv=true)
 Determines the base path for user settings files. More...
 
static int compareVersions (const std::string &aFirst, const std::string &aSecond)
 Compares two settings versions, like "5.99" and "6.0". More...
 
static bool extractVersion (const std::string &aVersionString, int *aMajor=nullptr, int *aMinor=nullptr)
 Extracts the numeric version from a given settings string. More...
 

Private Attributes

bool m_headless
 True if running outside a UI context. More...
 
KIWAYm_kiway
 The kiway this settings manager interacts with. More...
 
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
 
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
 
std::unordered_map< size_t, JSON_SETTINGS * > m_app_settings_cache
 Cache for app settings. More...
 
COMMON_SETTINGSm_common_settings
 
wxString m_migration_source
 
bool m_migrateLibraryTables
 If true, the symbol and footprint library tables will be migrated from the previous version. More...
 
bool m_ok
 True if settings loaded successfully at construction. More...
 
std::vector< std::unique_ptr< PROJECT > > m_projects_list
 Loaded projects (ownership here) More...
 
std::map< wxString, PROJECT * > m_projects
 Loaded projects, mapped according to project full name. More...
 
std::map< wxString, PROJECT_FILE * > m_project_files
 Loaded project files, mapped according to project full name. More...
 
std::unique_ptr< wxSingleInstanceChecker > m_project_lock
 Lock for loaded project (expand to multiple once we support MDI) More...
 

Static Private Attributes

static wxString backupDateTimeFormat = wxT( "%Y-%m-%d_%H%M%S" )
 

Detailed Description

Definition at line 42 of file settings_manager.h.

Constructor & Destructor Documentation

◆ SETTINGS_MANAGER()

SETTINGS_MANAGER::SETTINGS_MANAGER ( bool  aHeadless = false)

Definition at line 51 of file settings_manager.cpp.

51 :
52 m_headless( aHeadless ),
53 m_kiway( nullptr ),
54 m_common_settings( nullptr ),
57{
58 // Check if the settings directory already exists, and if not, perform a migration if possible
59 if( !MigrateIfNeeded() )
60 {
61 m_ok = false;
62 return;
63 }
64
65 m_ok = true;
66
67 // create the common settings shared by all applications. Not loaded immediately
69}
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
bool MigrateIfNeeded()
Handles the initialization of the user settings directory and migration from previous KiCad versions ...
wxString m_migration_source
bool m_headless
True if running outside a UI context.
bool m_migrateLibraryTables
If true, the symbol and footprint library tables will be migrated from the previous version.
bool m_ok
True if settings loaded successfully at construction.
COMMON_SETTINGS * m_common_settings
KIWAY * m_kiway
The kiway this settings manager interacts with.

References m_common_settings, m_ok, MigrateIfNeeded(), and RegisterSettings().

◆ ~SETTINGS_MANAGER()

SETTINGS_MANAGER::~SETTINGS_MANAGER ( )

Definition at line 71 of file settings_manager.cpp.

72{
73 for( std::unique_ptr<PROJECT>& project : m_projects_list )
74 project.reset();
75
76 m_projects.clear();
77
78 for( std::unique_ptr<JSON_SETTINGS>& settings : m_settings )
79 settings.reset();
80
81 m_settings.clear();
82
83 m_color_settings.clear();
84}
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
std::vector< std::unique_ptr< PROJECT > > m_projects_list
Loaded projects (ownership here)
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings

References m_color_settings, m_projects, m_projects_list, m_settings, and project.

Member Function Documentation

◆ AddNewColorSettings()

COLOR_SETTINGS * SETTINGS_MANAGER::AddNewColorSettings ( const wxString &  aFilename)

Registers a new color settings object with the given filename.

Parameters
aFilenameis the location to store the new settings object
Returns
a pointer to the new object

Definition at line 286 of file settings_manager.cpp.

287{
288 if( aName.EndsWith( wxT( ".json" ) ) )
289 return registerColorSettings( aName.BeforeLast( '.' ) );
290 else
291 return registerColorSettings( aName );
292}
COLOR_SETTINGS * registerColorSettings(const wxString &aFilename, bool aAbsolutePath=false)

References registerColorSettings().

Referenced by FOOTPRINT_EDITOR_SETTINGS::MigrateFromLegacy(), COLOR_SETTINGS::migrateSchema0to1(), and PANEL_COLOR_SETTINGS::OnThemeChanged().

◆ BackupProject()

bool SETTINGS_MANAGER::BackupProject ( REPORTER aReporter) const

Creates a backup archive of the current project.

Parameters
aReporteris used for progress reporting
Returns
true if everything succeeded

Definition at line 1167 of file settings_manager.cpp.

1168{
1169 wxDateTime timestamp = wxDateTime::Now();
1170
1171 wxString fileName = wxString::Format( wxT( "%s-%s" ), Prj().GetProjectName(),
1172 timestamp.Format( backupDateTimeFormat ) );
1173
1174 wxFileName target;
1175 target.SetPath( GetProjectBackupsPath() );
1176 target.SetName( fileName );
1177 target.SetExt( ArchiveFileExtension );
1178
1179 if( !target.DirExists() && !wxMkdir( target.GetPath() ) )
1180 {
1181 wxLogTrace( traceSettings, wxT( "Could not create project backup path %s" ), target.GetPath() );
1182 return false;
1183 }
1184
1185 if( !target.IsDirWritable() )
1186 {
1187 wxLogTrace( traceSettings, wxT( "Backup directory %s is not writable" ), target.GetPath() );
1188 return false;
1189 }
1190
1191 wxLogTrace( traceSettings, wxT( "Backing up project to %s" ), target.GetPath() );
1192
1193 PROJECT_ARCHIVER archiver;
1194
1195 return archiver.Archive( Prj().GetProjectPath(), target.GetFullPath(), aReporter );
1196}
bool Archive(const wxString &aSrcDir, const wxString &aDestFile, REPORTER &aReporter, bool aVerbose=true, bool aIncludeExtraFiles=false)
Creates an archive of the project.
wxString GetProjectBackupsPath() const
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
static wxString backupDateTimeFormat
const std::string ArchiveFileExtension
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:200

References PROJECT_ARCHIVER::Archive(), ArchiveFileExtension, backupDateTimeFormat, Format(), GetProjectBackupsPath(), Prj(), and traceSettings.

Referenced by TriggerBackupIfNeeded().

◆ calculateUserSettingsPath()

wxString SETTINGS_MANAGER::calculateUserSettingsPath ( bool  aIncludeVer = true,
bool  aUseEnv = true 
)
staticprivate

Determines the base path for user settings files.

The configuration path order of precedence is determined by the following criteria:

  • The value of the KICAD_CONFIG_HOME environment variable
  • The value of the XDG_CONFIG_HOME environment variable.
  • The result of the call to wxStandardPaths::GetUserConfigDir() with ".config" appended as required on Linux builds.
Parameters
aIncludeVerwill append the current KiCad version if true (default)
aUseEnvwill prefer the base path found in the KICAD_CONFIG_DIR if found (default)
Returns
A string containing the config path for Kicad

Definition at line 757 of file settings_manager.cpp.

758{
759 wxFileName cfgpath;
760
761 // http://docs.wxwidgets.org/3.0/classwx_standard_paths.html#a7c7cf595d94d29147360d031647476b0
762
763 wxString envstr;
764 if( aUseEnv && wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
765 {
766 // Override the assignment above with KICAD_CONFIG_HOME
767 cfgpath.AssignDir( envstr );
768 }
769 else
770 {
771 cfgpath.AssignDir( KIPLATFORM::ENV::GetUserConfigPath() );
772
773 cfgpath.AppendDir( TO_STR( KICAD_CONFIG_DIR ) );
774 }
775
776 if( aIncludeVer )
777 cfgpath.AppendDir( GetSettingsVersion() );
778
779 return cfgpath.GetPath();
780}
static std::string GetSettingsVersion()
Parses the current KiCad build version and extracts the major and minor revision to use as the name o...
#define TO_STR(x)
Definition: macros.h:105
wxString GetUserConfigPath()
Retrieves the operating system specific path for a user's configuration store.

References GetSettingsVersion(), KIPLATFORM::ENV::GetUserConfigPath(), and TO_STR.

Referenced by GetPreviousVersionPaths(), and GetUserSettingsPath().

◆ compareVersions()

int SETTINGS_MANAGER::compareVersions ( const std::string &  aFirst,
const std::string &  aSecond 
)
staticprivate

Compares two settings versions, like "5.99" and "6.0".

Returns
-1 if aFirst is older than aSecond, 1 if aFirst is newer than aSecond, 0 otherwise

Definition at line 790 of file settings_manager.cpp.

791{
792 int a_maj = 0;
793 int a_min = 0;
794 int b_maj = 0;
795 int b_min = 0;
796
797 if( !extractVersion( aFirst, &a_maj, &a_min ) || !extractVersion( aSecond, &b_maj, &b_min ) )
798 {
799 wxLogTrace( traceSettings, wxT( "compareSettingsVersions: bad input (%s, %s)" ), aFirst, aSecond );
800 return -1;
801 }
802
803 if( a_maj < b_maj )
804 {
805 return -1;
806 }
807 else if( a_maj > b_maj )
808 {
809 return 1;
810 }
811 else
812 {
813 if( a_min < b_min )
814 {
815 return -1;
816 }
817 else if( a_min > b_min )
818 {
819 return 1;
820 }
821 else
822 {
823 return 0;
824 }
825 }
826}
static bool extractVersion(const std::string &aVersionString, int *aMajor=nullptr, int *aMinor=nullptr)
Extracts the numeric version from a given settings string.

References extractVersion(), and traceSettings.

Referenced by GetPreviousVersionPaths().

◆ extractVersion()

bool SETTINGS_MANAGER::extractVersion ( const std::string &  aVersionString,
int *  aMajor = nullptr,
int *  aMinor = nullptr 
)
staticprivate

Extracts the numeric version from a given settings string.

Parameters
aVersionStringis the string to split at the "."
aMajorwill store the first part
aMinorwill store the second part
Returns
true if extraction succeeded

Definition at line 829 of file settings_manager.cpp.

830{
831 std::regex re_version( "(\\d+)\\.(\\d+)" );
832 std::smatch match;
833
834 if( std::regex_match( aVersionString, match, re_version ) )
835 {
836 try
837 {
838 int major = std::stoi( match[1].str() );
839 int minor = std::stoi( match[2].str() );
840
841 if( aMajor )
842 *aMajor = major;
843
844 if( aMinor )
845 *aMinor = minor;
846 }
847 catch( ... )
848 {
849 return false;
850 }
851
852 return true;
853 }
854
855 return false;
856}

Referenced by compareVersions().

◆ FlushAndRelease()

void SETTINGS_MANAGER::FlushAndRelease ( JSON_SETTINGS aSettings,
bool  aSave = true 
)

If the given settings object is registered, save it to disk and unregister it.

Parameters
aSettingsis the object to release

Definition at line 155 of file settings_manager.cpp.

156{
157 auto it = std::find_if( m_settings.begin(), m_settings.end(),
158 [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
159 {
160 return aPtr.get() == aSettings;
161 } );
162
163 if( it != m_settings.end() )
164 {
165 wxLogTrace( traceSettings, wxT( "Flush and release %s" ), ( *it )->GetFullFilename() );
166
167 if( aSave )
168 ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
169
170 size_t typeHash = typeid( *it->get() ).hash_code();
171
172 if( m_app_settings_cache.count( typeHash ) )
173 m_app_settings_cache.erase( typeHash );
174
175 m_settings.erase( it );
176 }
177}
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.
std::unordered_map< size_t, JSON_SETTINGS * > m_app_settings_cache
Cache for app settings.

References GetPathForSettingsFile(), m_app_settings_cache, m_settings, and traceSettings.

Referenced by FOOTPRINT_EDIT_FRAME::doCloseWindow(), and unloadProjectFile().

◆ GetAppSettings()

template<typename T >
T * SETTINGS_MANAGER::GetAppSettings ( bool  aLoadNow = true)
inline

Returns a handle to the a given settings by type If the settings have already been loaded, returns the existing pointer.

If the settings have not been loaded, creates a new object owned by the settings manager and returns a pointer to it.

Template Parameters
Tis a type derived from APP_SETTINGS_BASE
Parameters
aLoadNowis true to load the registered file from disk immediately
Returns
a pointer to a loaded settings object

Definition at line 97 of file settings_manager.h.

98 {
99 T* ret = nullptr;
100 size_t typeHash = typeid( T ).hash_code();
101
102 if( m_app_settings_cache.count( typeHash ) )
103 ret = dynamic_cast<T*>( m_app_settings_cache.at( typeHash ) );
104
105 if( ret )
106 return ret;
107
108 auto it = std::find_if( m_settings.begin(), m_settings.end(),
109 []( const std::unique_ptr<JSON_SETTINGS>& aSettings )
110 {
111 return dynamic_cast<T*>( aSettings.get() );
112 } );
113
114 if( it != m_settings.end() )
115 {
116 ret = dynamic_cast<T*>( it->get() );
117 }
118 else
119 {
120 try
121 {
122 ret = static_cast<T*>( RegisterSettings( new T, aLoadNow ) );
123 }
124 catch( ... )
125 {
126 }
127
128 }
129
130 m_app_settings_cache[typeHash] = ret;
131
132 return ret;
133 }

References m_app_settings_cache, m_settings, and RegisterSettings().

Referenced by SYMBOL_EDIT_FRAME::CommonSettingsChanged(), PL_EDITOR_FRAME::CommonSettingsChanged(), PCB::IFACE::CreateKiWindow(), PCB_TEST_FRAME_BASE::createView(), GRID_CELL_LAYER_RENDERER::Draw(), SYMBOL_EDITOR_DRAWING_TOOLS::DrawShape(), EVT_TOOL_RANGE(), PCB_EDITOR_CONDITIONS::get45degModeFunc(), SCH_BASE_FRAME::GetColorSettings(), SYMBOL_EDIT_FRAME::GetColorSettings(), GERBVIEW_FRAME::GetColorSettings(), PCB_LAYER_BOX_SELECTOR::getLayerColor(), PCB_TOOL_BASE::Is45Limited(), LIB_PIN::LIB_PIN(), FP_LIB_TABLE::LoadGlobalTable(), SYMBOL_LIB_TABLE::LoadGlobalTable(), PCB_VIEWER_TOOLS::MeasureTool(), PANEL_PACKAGES_VIEW::OnDownloadVersionClicked(), DIALOG_PCM::OnManageRepositoriesClicked(), PANEL_EESCHEMA_COLOR_SETTINGS::PANEL_EESCHEMA_COLOR_SETTINGS(), PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS(), PANEL_GERBVIEW_COLOR_SETTINGS::PANEL_GERBVIEW_COLOR_SETTINGS(), PANEL_PCBNEW_COLOR_SETTINGS::PANEL_PCBNEW_COLOR_SETTINGS(), PL_DRAW_PANEL_GAL::PL_DRAW_PANEL_GAL(), DIALOG_PLOT::Plot(), EDA_3D_CANVAS::RenderEngineChanged(), SaveFileAs(), PCB_TEST_FRAME_BASE::SetBoard(), DRAWING_TOOL::ToggleHV45Mode(), PANEL_3D_RAYTRACING_OPTIONS::TransferDataFromWindow(), PANEL_EESCHEMA_ANNOTATION_OPTIONS::TransferDataFromWindow(), PANEL_EESCHEMA_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_EESCHEMA_DISPLAY_OPTIONS::TransferDataFromWindow(), PANEL_EESCHEMA_EDITING_OPTIONS::TransferDataFromWindow(), PANEL_SYM_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_SYM_EDITING_OPTIONS::TransferDataFromWindow(), PANEL_GERBVIEW_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_PCM_SETTINGS::TransferDataFromWindow(), PANEL_PL_EDITOR_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_EDIT_OPTIONS::TransferDataFromWindow(), PANEL_FP_EDITOR_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_FP_EDITOR_DEFAULTS::TransferDataFromWindow(), PANEL_PCBNEW_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_3D_RAYTRACING_OPTIONS::TransferDataToWindow(), PANEL_EESCHEMA_ANNOTATION_OPTIONS::TransferDataToWindow(), PANEL_EESCHEMA_DISPLAY_OPTIONS::TransferDataToWindow(), PANEL_EESCHEMA_EDITING_OPTIONS::TransferDataToWindow(), PANEL_SYM_COLOR_SETTINGS::TransferDataToWindow(), PANEL_SYM_EDITING_OPTIONS::TransferDataToWindow(), PANEL_PCM_SETTINGS::TransferDataToWindow(), PANEL_DISPLAY_OPTIONS::TransferDataToWindow(), PANEL_EDIT_OPTIONS::TransferDataToWindow(), PANEL_FP_EDITOR_DEFAULTS::TransferDataToWindow(), and DRAWING_TOOL::UpdateStatusBar().

◆ GetColorSettings()

COLOR_SETTINGS * SETTINGS_MANAGER::GetColorSettings ( const wxString &  aName = "user")

Retrieves a color settings object that applications can read colors from.

If the given settings file cannot be found, returns the default settings.

Parameters
aNameis the name of the color scheme to load
Returns
a loaded COLOR_SETTINGS object

Definition at line 180 of file settings_manager.cpp.

181{
182 // Find settings the fast way
183 if( m_color_settings.count( aName ) )
184 return m_color_settings.at( aName );
185
186 // Maybe it's the display name (cli is one method of invoke)
187 auto it = std::find_if( m_color_settings.begin(), m_color_settings.end(),
188 [&aName]( const std::pair<wxString, COLOR_SETTINGS*>& p )
189 {
190 return p.second->GetName().Lower() == aName.Lower();
191 } );
192
193 if( it != m_color_settings.end() )
194 {
195 return it->second;
196 }
197
198 // No match? See if we can load it
199 if( !aName.empty() )
200 {
202
203 if( !ret )
204 {
205 ret = registerColorSettings( aName );
206 *ret = *m_color_settings.at( "_builtin_default" );
207 ret->SetFilename( wxT( "user" ) );
208 ret->SetReadOnly( false );
209 }
210
211 return ret;
212 }
213
214 // This had better work
215 return m_color_settings.at( "_builtin_default" );
216}
Color settings are a bit different than most of the settings objects in that there can be more than o...
void SetReadOnly(bool aReadOnly)
Definition: json_settings.h:85
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:77
COLOR_SETTINGS * loadColorSettingsByName(const wxString &aName)
Attempts to load a color theme by name (the color theme directory and .json ext are assumed)

References loadColorSettingsByName(), m_color_settings, registerColorSettings(), JSON_SETTINGS::SetFilename(), and JSON_SETTINGS::SetReadOnly().

Referenced by PL_EDITOR_FRAME::CommonSettingsChanged(), GRID_CELL_LAYER_RENDERER::Draw(), DIALOG_PLOT_SCHEMATIC::getColorSettings(), SCH_BASE_FRAME::GetColorSettings(), SYMBOL_EDIT_FRAME::GetColorSettings(), GERBVIEW_FRAME::GetColorSettings(), PCB_LAYER_BOX_SELECTOR::getLayerColor(), PANEL_EESCHEMA_EDITING_OPTIONS::loadEEschemaSettings(), PANEL_EESCHEMA_COLOR_SETTINGS::PANEL_EESCHEMA_COLOR_SETTINGS(), PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS(), PANEL_GERBVIEW_COLOR_SETTINGS::PANEL_GERBVIEW_COLOR_SETTINGS(), PANEL_PCBNEW_COLOR_SETTINGS::PANEL_PCBNEW_COLOR_SETTINGS(), PL_DRAW_PANEL_GAL::PL_DRAW_PANEL_GAL(), PCB_PLOT_SVG::Plot(), SCH_PLOTTER::Plot(), DIALOG_PLOT::Plot(), SCH_PRINTOUT::PrintPage(), PANEL_COLOR_SETTINGS::saveCurrentTheme(), and PANEL_SYM_COLOR_SETTINGS::TransferDataToWindow().

◆ GetColorSettingsList()

std::vector< COLOR_SETTINGS * > SETTINGS_MANAGER::GetColorSettingsList ( )
inline

Definition at line 144 of file settings_manager.h.

145 {
146 std::vector<COLOR_SETTINGS*> ret;
147
148 for( const std::pair<const wxString, COLOR_SETTINGS*>& entry : m_color_settings )
149 ret.push_back( entry.second );
150
151 std::sort( ret.begin(), ret.end(), []( COLOR_SETTINGS* a, COLOR_SETTINGS* b )
152 {
153 return a->GetName() < b->GetName();
154 } );
155
156 return ret;
157 }

References m_color_settings.

Referenced by DIALOG_PLOT_SCHEMATIC::initDlg(), PANEL_SYM_COLOR_SETTINGS::TransferDataToWindow(), and DIALOG_PRINT_PCBNEW::TransferDataToWindow().

◆ GetColorSettingsPath()

wxString SETTINGS_MANAGER::GetColorSettingsPath ( )
static

Returns the path where color scheme files are stored; creating it if missing (normally .

/colors/ under the user settings path)

Definition at line 725 of file settings_manager.cpp.

726{
727 wxFileName path;
728
729 path.AssignDir( GetUserSettingsPath() );
730 path.AppendDir( wxS( "colors" ) );
731
732 if( !path.DirExists() )
733 {
734 if( !wxMkdir( path.GetPath() ) )
735 {
736 wxLogTrace( traceSettings,
737 wxT( "GetColorSettingsPath(): Path %s missing and could not be created!" ),
738 path.GetPath() );
739 }
740 }
741
742 return path.GetPath();
743}
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.

References GetUserSettingsPath(), path, and traceSettings.

Referenced by GetPathForSettingsFile(), loadAllColorSettings(), loadColorSettingsByName(), PANEL_COLOR_SETTINGS::OnBtnOpenThemeFolderClicked(), PANEL_COLOR_SETTINGS::OnThemeChanged(), and SaveColorSettings().

◆ GetCommonSettings()

COMMON_SETTINGS * SETTINGS_MANAGER::GetCommonSettings ( ) const
inline

Retrieves the common settings shared by all applications.

Returns
a pointer to a loaded COMMON_SETTINGS

Definition at line 188 of file settings_manager.h.

188{ return m_common_settings; }

References m_common_settings.

Referenced by TriggerBackupIfNeeded().

◆ GetMigratedColorSettings()

COLOR_SETTINGS * SETTINGS_MANAGER::GetMigratedColorSettings ( )

Returns a color theme for storing colors migrated from legacy (5.x and earlier) settings, creating the theme if necessary.

This theme will be called "user.json" / "User".

Returns
the color settings to be used for migrating legacy settings

Definition at line 295 of file settings_manager.cpp.

296{
297 if( !m_color_settings.count( "user" ) )
298 {
299 COLOR_SETTINGS* settings = registerColorSettings( wxT( "user" ) );
300 settings->SetName( wxT( "User" ) );
301 Save( settings );
302 }
303
304 return m_color_settings.at( "user" );
305}
void SetName(const wxString &aName)

References m_color_settings, registerColorSettings(), Save(), and COLOR_SETTINGS::SetName().

◆ GetOpenProjects()

std::vector< wxString > SETTINGS_MANAGER::GetOpenProjects ( ) const
Returns
a list of open projects

Definition at line 1001 of file settings_manager.cpp.

1002{
1003 std::vector<wxString> ret;
1004
1005 for( const std::pair<const wxString, PROJECT*>& pair : m_projects )
1006 ret.emplace_back( pair.first );
1007
1008 return ret;
1009}

References m_projects.

Referenced by KICAD_MANAGER_FRAME::canCloseWindow().

◆ GetPathForSettingsFile()

wxString SETTINGS_MANAGER::GetPathForSettingsFile ( JSON_SETTINGS aSettings)

Returns the path a given settings file should be loaded from / stored to.

Parameters
aSettingsis the settings object
Returns
a path based on aSettings->m_location

Definition at line 400 of file settings_manager.cpp.

401{
402 wxASSERT( aSettings );
403
404 switch( aSettings->GetLocation() )
405 {
407 return GetUserSettingsPath();
408
410 // TODO: MDI support
411 return Prj().GetProjectPath();
412
414 return GetColorSettingsPath();
415
417 return "";
418
419 default:
420 wxASSERT_MSG( false, wxT( "Unknown settings location!" ) );
421 }
422
423 return "";
424}
SETTINGS_LOC GetLocation() const
Definition: json_settings.h:80
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition: project.cpp:126
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
@ PROJECT
The settings directory inside a project folder.
@ USER
The main config directory (e.g. ~/.config/kicad/)
@ COLORS
The color scheme directory (e.g. ~/.config/kicad/colors/)
@ NONE
No directory prepended, full path in filename (used for PROJECT_FILE)

References COLORS, GetColorSettingsPath(), JSON_SETTINGS::GetLocation(), PROJECT::GetProjectPath(), GetUserSettingsPath(), NONE, Prj(), PROJECT, and USER.

Referenced by FlushAndRelease(), Load(), MigrateIfNeeded(), PANEL_COLOR_SETTINGS::OnThemeChanged(), registerSettings(), Save(), and unloadProjectFile().

◆ GetPreviousVersionPaths()

bool SETTINGS_MANAGER::GetPreviousVersionPaths ( std::vector< wxString > *  aName = nullptr)

Retrieves the name of the most recent previous KiCad version that can be found in the user settings directory.

For legacy versions (5.x, and 5.99 builds before this code was written), this will return "5.x"

Parameters
aNameis filled with the name of the previous version, if one exists
Returns
true if a previous version to migrate from exists

Definition at line 601 of file settings_manager.cpp.

602{
603 wxASSERT( aPaths );
604
605 aPaths->clear();
606
607 wxDir dir;
608 std::vector<wxFileName> base_paths;
609
610 base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false ), wxS( "" ) ) );
611
612 // If the env override is set, also check the default paths
613 if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), nullptr ) )
614 base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false, false ), wxS( "" ) ) );
615
616#ifdef __WXGTK__
617 // When running inside FlatPak, KIPLATFORM::ENV::GetUserConfigPath() will return a sandboxed
618 // path. In case the user wants to move from non-FlatPak KiCad to FlatPak KiCad, let's add our
619 // best guess as to the non-FlatPak config path. Unfortunately FlatPak also hides the host
620 // XDG_CONFIG_HOME, so if the user customizes their config path, they will have to browse
621 // for it.
622 {
623 wxFileName wxGtkPath;
624 wxGtkPath.AssignDir( wxS( "~/.config/kicad" ) );
625 wxGtkPath.MakeAbsolute();
626 base_paths.emplace_back( wxGtkPath.GetPath() );
627
628 // We also want to pick up regular flatpak if we are nightly
629 wxGtkPath.AssignDir( wxS( "~/.var/app/org.kicad.KiCad/config/kicad" ) );
630 wxGtkPath.MakeAbsolute();
631 base_paths.emplace_back( wxGtkPath.GetPath() );
632 }
633#endif
634
635 wxString subdir;
636 std::string mine = GetSettingsVersion();
637
638 auto check_dir = [&] ( const wxString& aSubDir )
639 {
640 // Only older versions are valid for migration
641 if( compareVersions( aSubDir.ToStdString(), mine ) <= 0 )
642 {
643 wxString sub_path = dir.GetNameWithSep() + aSubDir;
644
645 if( IsSettingsPathValid( sub_path ) )
646 {
647 aPaths->push_back( sub_path );
648 wxLogTrace( traceSettings, wxT( "GetPreviousVersionName: %s is valid" ), sub_path );
649 }
650 }
651 };
652
653 std::set<wxString> checkedPaths;
654
655 for( const wxFileName& base_path : base_paths )
656 {
657 if( checkedPaths.count( base_path.GetFullPath() ) )
658 continue;
659
660 checkedPaths.insert( base_path.GetFullPath() );
661
662 if( !dir.Open( base_path.GetFullPath() ) )
663 {
664 wxLogTrace( traceSettings, wxT( "GetPreviousVersionName: could not open base path %s" ),
665 base_path.GetFullPath() );
666 continue;
667 }
668
669 wxLogTrace( traceSettings, wxT( "GetPreviousVersionName: checking base path %s" ),
670 base_path.GetFullPath() );
671
672 if( dir.GetFirst( &subdir, wxEmptyString, wxDIR_DIRS ) )
673 {
674 if( subdir != mine )
675 check_dir( subdir );
676
677 while( dir.GetNext( &subdir ) )
678 {
679 if( subdir != mine )
680 check_dir( subdir );
681 }
682 }
683
684 // If we didn't find one yet, check for legacy settings without a version directory
685 if( IsSettingsPathValid( dir.GetNameWithSep() ) )
686 {
687 wxLogTrace( traceSettings,
688 wxT( "GetPreviousVersionName: root path %s is valid" ), dir.GetName() );
689 aPaths->push_back( dir.GetName() );
690 }
691 }
692
693 std::sort( aPaths->begin(), aPaths->end(),
694 [&]( const wxString& a, const wxString& b ) -> bool
695 {
696 wxString verA = wxFileName::DirName( a ).GetDirs().back();
697 wxString verB = wxFileName::DirName( b ).GetDirs().back();
698
699 if( !extractVersion( verA.ToStdString() )
700 || !extractVersion( verB.ToStdString() ) )
701 {
702 return false;
703 }
704
705 return compareVersions( verA.ToStdString(), verB.ToStdString() ) >= 0;
706 } );
707
708 return aPaths->size() > 0;
709}
static int compareVersions(const std::string &aFirst, const std::string &aSecond)
Compares two settings versions, like "5.99" and "6.0".
static wxString calculateUserSettingsPath(bool aIncludeVer=true, bool aUseEnv=true)
Determines the base path for user settings files.
static bool IsSettingsPathValid(const wxString &aPath)
Checks if a given path is probably a valid KiCad configuration directory.

References calculateUserSettingsPath(), compareVersions(), GetSettingsVersion(), IsSettingsPathValid(), and traceSettings.

Referenced by DIALOG_MIGRATE_SETTINGS::TransferDataToWindow().

◆ GetProject()

PROJECT * SETTINGS_MANAGER::GetProject ( const wxString &  aFullPath) const

Retrieves a loaded project by name.

Parameters
aFullPathis the full path including name and extension to the project file
Returns
a pointer to the project if loaded, or nullptr

Definition at line 992 of file settings_manager.cpp.

993{
994 if( m_projects.count( aFullPath ) )
995 return m_projects.at( aFullPath );
996
997 return nullptr;
998}

References m_projects.

Referenced by EESCHEMA_HELPERS::GetDefaultProject(), GetDefaultProject(), LoadBoard(), EESCHEMA_HELPERS::LoadSchematic(), NewBoard(), DIALOG_SCHEMATIC_SETUP::onAuxiliaryAction(), and DIALOG_BOARD_SETUP::onAuxiliaryAction().

◆ GetProjectBackupsPath()

wxString SETTINGS_MANAGER::GetProjectBackupsPath ( ) const
Returns
the full path to where project backups should be stored

Definition at line 1158 of file settings_manager.cpp.

1159{
1161}
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:132
#define PROJECT_BACKUPS_DIR_SUFFIX
Project settings path will be <projectname> + this.

References PROJECT::GetProjectName(), PROJECT::GetProjectPath(), Prj(), and PROJECT_BACKUPS_DIR_SUFFIX.

Referenced by BackupProject(), and TriggerBackupIfNeeded().

◆ GetSettingsVersion()

std::string SETTINGS_MANAGER::GetSettingsVersion ( )
static

Parses the current KiCad build version and extracts the major and minor revision to use as the name of the settings directory for this KiCad version.

Returns
a string such as "5.1"

Definition at line 783 of file settings_manager.cpp.

784{
785 // CMake computes the major.minor string for us.
786 return GetMajorMinorVersion().ToStdString();
787}
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.

References GetMajorMinorVersion().

Referenced by calculateUserSettingsPath(), GetPreviousVersionPaths(), PATHS::GetUserCachePath(), PATHS::getUserDocumentPath(), and DIALOG_MIGRATE_SETTINGS::TransferDataToWindow().

◆ GetUserSettingsPath()

wxString SETTINGS_MANAGER::GetUserSettingsPath ( )
static

Return the user configuration path used to store KiCad's configuration files.

See also
calculateUserSettingsPath

NOTE: The path is cached at startup, it will never change during program lifetime!

Returns
A string containing the config path for Kicad

Definition at line 746 of file settings_manager.cpp.

747{
748 static wxString user_settings_path;
749
750 if( user_settings_path.empty() )
751 user_settings_path = calculateUserSettingsPath();
752
753 return user_settings_path;
754}

References calculateUserSettingsPath().

Referenced by getAdvancedCfgFilename(), GetColorSettingsPath(), SYMBOL_LIB_TABLE::GetGlobalTableFileName(), FP_LIB_TABLE::GetGlobalTableFileName(), GetPathForSettingsFile(), MigrateIfNeeded(), COMMON_SETTINGS::migrateSchema2to3(), PLUGIN_CONTENT_MANAGER::PLUGIN_CONTENT_MANAGER(), ReadHotKeyConfig(), ReadLegacyHotkeyConfigFile(), PLUGIN_CONTENT_MANAGER::SaveInstalledPackages(), and WriteHotKeyConfig().

◆ IsOK()

bool SETTINGS_MANAGER::IsOK ( )
inline
Returns
true if settings load was successful

Definition at line 52 of file settings_manager.h.

52{ return m_ok; }

References m_ok.

◆ IsProjectOpen()

bool SETTINGS_MANAGER::IsProjectOpen ( ) const

Helper for checking if we have a project open TODO: This should be deprecated along with Prj() once we support multiple projects fully.

Returns
true if a call to Prj() will succeed

Definition at line 986 of file settings_manager.cpp.

987{
988 return !m_projects.empty();
989}

References m_projects.

Referenced by FOOTPRINT_EDIT_FRAME::doCloseWindow(), and PCB_BASE_EDIT_FRAME::doCloseWindow().

◆ IsSettingsPathValid()

bool SETTINGS_MANAGER::IsSettingsPathValid ( const wxString &  aPath)
static

Checks if a given path is probably a valid KiCad configuration directory.

Actually it just checks if a file called "kicad_common" exists, because that's probably good enough for now.

Parameters
aPathis the path to check
Returns
true if the path contains KiCad settings

Definition at line 712 of file settings_manager.cpp.

713{
714 wxFileName test( aPath, wxS( "kicad_common" ) );
715
716 if( test.Exists() )
717 return true;
718
719 test.SetExt( "json" );
720
721 return test.Exists();
722}

Referenced by GetPreviousVersionPaths(), and DIALOG_MIGRATE_SETTINGS::validatePath().

◆ Load() [1/2]

void SETTINGS_MANAGER::Load ( )

Definition at line 103 of file settings_manager.cpp.

104{
105 // TODO(JE) We should check for dirty settings here and write them if so, because
106 // Load() could be called late in the application lifecycle
107
108 for( auto&& settings : m_settings )
109 settings->LoadFromFile( GetPathForSettingsFile( settings.get() ) );
110}

References GetPathForSettingsFile(), and m_settings.

Referenced by PGM_BASE::InitPgm().

◆ Load() [2/2]

void SETTINGS_MANAGER::Load ( JSON_SETTINGS aSettings)

Definition at line 113 of file settings_manager.cpp.

114{
115 auto it = std::find_if( m_settings.begin(), m_settings.end(),
116 [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
117 {
118 return aPtr.get() == aSettings;
119 } );
120
121 if( it != m_settings.end() )
122 ( *it )->LoadFromFile( GetPathForSettingsFile( it->get() ) );
123}

References GetPathForSettingsFile(), and m_settings.

◆ loadAllColorSettings()

void SETTINGS_MANAGER::loadAllColorSettings ( )
private

Definition at line 308 of file settings_manager.cpp.

309{
310 // Create the built-in color settings
312 m_color_settings[settings->GetFilename()] = RegisterSettings( settings, false );
313
314 wxFileName third_party_path;
315 const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
316 auto it = env.find( wxS( "KICAD7_3RD_PARTY" ) );
317
318 if( it != env.end() && !it->second.GetValue().IsEmpty() )
319 third_party_path.SetPath( it->second.GetValue() );
320 else
321 third_party_path.SetPath( PATHS::GetDefault3rdPartyPath() );
322
323 third_party_path.AppendDir( wxS( "colors" ) );
324
325 wxDir third_party_colors_dir( third_party_path.GetFullPath() );
326 wxString color_settings_path = GetColorSettingsPath();
327
328 // Search for and load any other settings
329 JSON_DIR_TRAVERSER loader( [&]( const wxFileName& aFilename )
330 {
331 registerColorSettings( aFilename.GetName() );
332 } );
333
334 JSON_DIR_TRAVERSER thirdPartyLoader(
335 [&]( const wxFileName& aFilename )
336 {
337 COLOR_SETTINGS* settings = registerColorSettings( aFilename.GetFullPath(), true );
338 settings->SetReadOnly( true );
339 } );
340
341 wxDir colors_dir( color_settings_path );
342
343 if( colors_dir.IsOpened() )
344 {
345 if( third_party_colors_dir.IsOpened() )
346 third_party_colors_dir.Traverse( thirdPartyLoader );
347
348 colors_dir.Traverse( loader );
349 }
350}
static std::vector< COLOR_SETTINGS * > CreateBuiltinColorSettings()
Constructs and returns a list of color settings objects based on the built-in color themes.
static wxString GetDefault3rdPartyPath()
Gets the default path for PCM packages.
Definition: paths.cpp:129
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:111

References COLOR_SETTINGS::CreateBuiltinColorSettings(), GetColorSettingsPath(), PATHS::GetDefault3rdPartyPath(), m_color_settings, Pgm(), registerColorSettings(), RegisterSettings(), and JSON_SETTINGS::SetReadOnly().

Referenced by ReloadColorSettings().

◆ loadColorSettingsByName()

COLOR_SETTINGS * SETTINGS_MANAGER::loadColorSettingsByName ( const wxString &  aName)
private

Attempts to load a color theme by name (the color theme directory and .json ext are assumed)

Parameters
aNameis the filename of the color theme (without the extension or path)
Returns
the loaded settings, or nullptr if load failed

Definition at line 219 of file settings_manager.cpp.

220{
221 wxLogTrace( traceSettings, wxT( "Attempting to load color theme %s" ), aName );
222
223 wxFileName fn( GetColorSettingsPath(), aName, wxS( "json" ) );
224
225 if( !fn.IsOk() || !fn.Exists() )
226 {
227 wxLogTrace( traceSettings, wxT( "Theme file %s.json not found, falling back to user" ), aName );
228 return nullptr;
229 }
230
231 COLOR_SETTINGS* settings = RegisterSettings( new COLOR_SETTINGS( aName ) );
232
233 if( settings->GetFilename() != aName.ToStdString() )
234 {
235 wxLogTrace( traceSettings, wxT( "Warning: stored filename is actually %s, " ),
236 settings->GetFilename() );
237 }
238
239 m_color_settings[aName] = settings;
240
241 return settings;
242}
wxString GetFilename() const
Definition: json_settings.h:73

References GetColorSettingsPath(), JSON_SETTINGS::GetFilename(), m_color_settings, RegisterSettings(), and traceSettings.

Referenced by GetColorSettings().

◆ LoadProject()

bool SETTINGS_MANAGER::LoadProject ( const wxString &  aFullPath,
bool  aSetActive = true 
)

Loads a project or sets up a new project with a specified path.

Parameters
aFullPathis the full path to the project
aSetActiveif true will set the loaded project as the active project
Returns
true if the PROJECT_FILE was successfully loaded from disk

Definition at line 859 of file settings_manager.cpp.

860{
861 // Normalize path to new format even if migrating from a legacy file
862 wxFileName path( aFullPath );
863
864 if( path.GetExt() == LegacyProjectFileExtension )
865 path.SetExt( ProjectFileExtension );
866
867 wxString fullPath = path.GetFullPath();
868
869 // If already loaded, we are all set. This might be called more than once over a project's
870 // lifetime in case the project is first loaded by the KiCad manager and then eeschema or
871 // pcbnew try to load it again when they are launched.
872 if( m_projects.count( fullPath ) )
873 return true;
874
875 bool readOnly = false;
876 std::unique_ptr<wxSingleInstanceChecker> lockFile = ::LockFile( fullPath );
877
878 if( !lockFile )
879 {
880 wxLogTrace( traceSettings, wxT( "Project %s is locked; opening read-only" ), fullPath );
881 readOnly = true;
882 }
883
884 // No MDI yet
885 if( aSetActive && !m_projects.empty() )
886 {
887 PROJECT* oldProject = m_projects.begin()->second;
888 unloadProjectFile( oldProject, false );
889 m_projects.erase( m_projects.begin() );
890
891 auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
892 [&]( const std::unique_ptr<PROJECT>& ptr )
893 {
894 return ptr.get() == oldProject;
895 } );
896
897 wxASSERT( it != m_projects_list.end() );
898 m_projects_list.erase( it );
899 }
900
901 wxLogTrace( traceSettings, wxT( "Load project %s" ), fullPath );
902
903 std::unique_ptr<PROJECT> project = std::make_unique<PROJECT>();
904 project->setProjectFullName( fullPath );
905
906 bool success = loadProjectFile( *project );
907
908 if( success )
909 {
910 project->SetReadOnly( readOnly || project->GetProjectFile().IsReadOnly() );
911
912 if( lockFile )
913 m_project_lock.reset( lockFile.release() );
914 }
915
916 m_projects_list.push_back( std::move( project ) );
917 m_projects[fullPath] = m_projects_list.back().get();
918
919 wxString fn( path.GetName() );
920
921 PROJECT_LOCAL_SETTINGS* settings = new PROJECT_LOCAL_SETTINGS( m_projects[fullPath], fn );
922
923 if( aSetActive )
924 settings = RegisterSettings( settings );
925 else
926 settings->LoadFromFile( path.GetPath() );
927
928 m_projects[fullPath]->setLocalSettings( settings );
929
930 if( aSetActive && m_kiway )
932
933 return success;
934}
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
virtual void ProjectChanged()
Calls ProjectChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:598
The project local settings are things that are attached to a particular project, but also might be pa...
Container for project specific data.
Definition: project.h:64
std::unique_ptr< wxSingleInstanceChecker > m_project_lock
Lock for loaded project (expand to multiple once we support MDI)
bool unloadProjectFile(PROJECT *aProject, bool aSave)
Optionally saves, and then unloads and unregisters the given PROJECT_FILE.
bool loadProjectFile(PROJECT &aProject)
Registers a PROJECT_FILE and attempts to load it from disk.
const std::string LegacyProjectFileExtension
const std::string ProjectFileExtension
std::unique_ptr< wxSingleInstanceChecker > LockFile(const wxString &aFileName)
Test to see if aFileName can be locked (is not already locked) and only then returns a wxSingleInstan...
Definition: lockfile.cpp:34

References LegacyProjectFileExtension, JSON_SETTINGS::LoadFromFile(), loadProjectFile(), LockFile(), m_kiway, m_project_lock, m_projects, m_projects_list, path, project, KIWAY::ProjectChanged(), ProjectFileExtension, RegisterSettings(), traceSettings, and unloadProjectFile().

Referenced by KICAD_MANAGER_FRAME::CreateNewProject(), EESCHEMA_HELPERS::GetDefaultProject(), GetDefaultProject(), PGM_BASE::InitPgm(), KI_TEST::LoadBoard(), LoadBoard(), KI_TEST::SCHEMATIC_TEST_FIXTURE::LoadSchematic(), KI_TEST::LoadSchematic(), EESCHEMA_HELPERS::LoadSchematic(), NewBoard(), DIALOG_SCHEMATIC_SETUP::onAuxiliaryAction(), DIALOG_BOARD_SETUP::onAuxiliaryAction(), SCH_EDIT_FRAME::OnImportProject(), KICAD_MANAGER_FRAME::OnUnarchiveFiles(), SCH_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), SCH::readSchematicFromFile(), TEST_NGSPICE_HELPERS::TEST_NGSPICE_HELPERS(), and UnloadProject().

◆ loadProjectFile()

bool SETTINGS_MANAGER::loadProjectFile ( PROJECT aProject)
private

Registers a PROJECT_FILE and attempts to load it from disk.

Parameters
aProjectis the project object to load the file for
Returns
true if the PROJECT_FILE was successfully loaded

Definition at line 1104 of file settings_manager.cpp.

1105{
1106 wxFileName fullFn( aProject.GetProjectFullName() );
1107 wxString fn( fullFn.GetName() );
1108
1109 PROJECT_FILE* file = RegisterSettings( new PROJECT_FILE( fn ), false );
1110
1111 m_project_files[aProject.GetProjectFullName()] = file;
1112
1113 aProject.setProjectFile( file );
1114 file->SetProject( &aProject );
1115
1116 wxString path( fullFn.GetPath() );
1117
1118 return file->LoadFromFile( path );
1119}
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:65
void SetProject(PROJECT *aProject)
Definition: project_file.h:81
virtual void setProjectFile(PROJECT_FILE *aFile)
Set the backing store file for this project.
Definition: project.h:326
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:120
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.

References PROJECT::GetProjectFullName(), JSON_SETTINGS::LoadFromFile(), m_project_files, path, RegisterSettings(), PROJECT_FILE::SetProject(), and PROJECT::setProjectFile().

Referenced by LoadProject().

◆ MigrateIfNeeded()

bool SETTINGS_MANAGER::MigrateIfNeeded ( )

Handles the initialization of the user settings directory and migration from previous KiCad versions as needed.

This method will check for the existence of the user settings path for this KiCad version. If it exists, settings load will proceed normally using that path.

If that directory is empty or does not exist, the migration wizard will be launched, which will give users the option to migrate settings from a previous KiCad version (if one is found), manually specify a directory to migrate fromm, or start with default settings.

Returns
true if migration was successful or not necessary, false otherwise

Definition at line 503 of file settings_manager.cpp.

504{
505 wxFileName path( GetUserSettingsPath(), wxS( "" ) );
506 wxLogTrace( traceSettings, wxT( "Using settings path %s" ), path.GetFullPath() );
507
508 if( m_headless )
509 {
510 // Special case namely for cli
511 // Ensure the settings directory at least exists to prevent additional loading errors from subdirectories
512 // TODO review headless (unit tests) vs cli needs, this should be fine for unit tests though
513 if( !path.DirExists() )
514 {
515 wxLogTrace( traceSettings, wxT( "Path didn't exist; creating it" ) );
516 path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
517 }
518
519 wxLogTrace( traceSettings, wxT( "Settings migration not checked; running headless" ) );
520 return true;
521 }
522
523 if( path.DirExists() )
524 {
525 wxFileName common = path;
526 common.SetName( wxS( "kicad_common" ) );
527 common.SetExt( wxS( "json" ) );
528
529 if( common.Exists() )
530 {
531 wxLogTrace( traceSettings, wxT( "Path exists and has a kicad_common, continuing!" ) );
532 return true;
533 }
534 }
535
536 // Now we have an empty path, let's figure out what to put in it
537 DIALOG_MIGRATE_SETTINGS dlg( this );
538
539 if( dlg.ShowModal() != wxID_OK )
540 {
541 wxLogTrace( traceSettings, wxT( "Migration dialog canceled; exiting" ) );
542 return false;
543 }
544
545 if( !path.DirExists() )
546 {
547 wxLogTrace( traceSettings, wxT( "Path didn't exist; creating it" ) );
548 path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
549 }
550
551 if( m_migration_source.IsEmpty() )
552 {
553 wxLogTrace( traceSettings, wxT( "No migration source given; starting with defaults" ) );
554 return true;
555 }
556
557 wxLogTrace( traceSettings, wxT( "Migrating from path %s" ), m_migration_source );
558
560 wxDir source_dir( m_migration_source );
561
562 source_dir.Traverse( traverser );
563
564 if( !traverser.GetErrors().empty() )
565 DisplayErrorMessage( nullptr, traverser.GetErrors() );
566
567 // Remove any library configuration if we didn't choose to import
569 {
570 COMMON_SETTINGS common;
571 wxString commonPath = GetPathForSettingsFile( &common );
572 common.LoadFromFile( commonPath );
573
574 const std::vector<wxString> libKeys = {
575 wxT( "KICAD6_SYMBOL_DIR" ),
576 wxT( "KICAD6_3DMODEL_DIR" ),
577 wxT( "KICAD6_FOOTPRINT_DIR" ),
578 wxT( "KICAD6_TEMPLATE_DIR" ), // Stores the default library table to be copied
579 wxT( "KICAD7_SYMBOL_DIR" ),
580 wxT( "KICAD7_3DMODEL_DIR" ),
581 wxT( "KICAD7_FOOTPRINT_DIR" ),
582 wxT( "KICAD7_TEMPLATE_DIR" ), // Stores the default library table to be copied
583
584 // Deprecated keys
585 wxT( "KICAD_PTEMPLATES" ),
586 wxT( "KISYS3DMOD" ),
587 wxT( "KISYSMOD" ),
588 wxT( "KICAD_SYMBOL_DIR" ),
589 };
590
591 for( const wxString& key : libKeys )
592 common.m_Env.vars.erase( key );
593
594 common.SaveToFile( commonPath );
595 }
596
597 return true;
598}
ENVIRONMENT m_Env
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:325

References DisplayErrorMessage(), MIGRATION_TRAVERSER::GetErrors(), GetPathForSettingsFile(), GetUserSettingsPath(), JSON_SETTINGS::LoadFromFile(), COMMON_SETTINGS::m_Env, m_headless, m_migrateLibraryTables, m_migration_source, path, JSON_SETTINGS::SaveToFile(), traceSettings, and COMMON_SETTINGS::ENVIRONMENT::vars.

Referenced by SETTINGS_MANAGER().

◆ Prj()

PROJECT & SETTINGS_MANAGER::Prj ( ) const

A helper while we are not MDI-capable – return the one and only project.

Returns
the loaded project

Definition at line 978 of file settings_manager.cpp.

979{
980 // No MDI yet: First project in the list is the active project
981 wxASSERT_MSG( m_projects_list.size(), wxT( "no project in list" ) );
982 return *m_projects_list.begin()->get();
983}

References m_projects_list.

Referenced by BackupProject(), PCB_EDIT_FRAME::Files_io_from_id(), GetPathForSettingsFile(), GetProjectBackupsPath(), KI_TEST::LoadBoard(), KI_TEST::SCHEMATIC_TEST_FIXTURE::LoadSchematic(), KI_TEST::LoadSchematic(), PCB_EDIT_FRAME::OpenProjectFiles(), SaveProject(), SaveProjectAs(), SaveProjectCopy(), TEST_NGSPICE_HELPERS::TEST_NGSPICE_HELPERS(), TriggerBackupIfNeeded(), and WriteDRCReport().

◆ registerColorSettings()

COLOR_SETTINGS * SETTINGS_MANAGER::registerColorSettings ( const wxString &  aFilename,
bool  aAbsolutePath = false 
)
private

Definition at line 273 of file settings_manager.cpp.

274{
275 if( !m_color_settings.count( aName ) )
276 {
277 COLOR_SETTINGS* colorSettings = RegisterSettings( new COLOR_SETTINGS( aName,
278 aAbsolutePath ) );
279 m_color_settings[aName] = colorSettings;
280 }
281
282 return m_color_settings.at( aName );
283}

References m_color_settings, and RegisterSettings().

Referenced by AddNewColorSettings(), GetColorSettings(), GetMigratedColorSettings(), and loadAllColorSettings().

◆ registerSettings()

JSON_SETTINGS * SETTINGS_MANAGER::registerSettings ( JSON_SETTINGS aSettings,
bool  aLoadNow = true 
)
private

Definition at line 87 of file settings_manager.cpp.

88{
89 std::unique_ptr<JSON_SETTINGS> ptr( aSettings );
90
91 ptr->SetManager( this );
92
93 wxLogTrace( traceSettings, wxT( "Registered new settings object <%s>" ), ptr->GetFullFilename() );
94
95 if( aLoadNow )
96 ptr->LoadFromFile( GetPathForSettingsFile( ptr.get() ) );
97
98 m_settings.push_back( std::move( ptr ) );
99 return m_settings.back().get();
100}

References GetPathForSettingsFile(), m_settings, and traceSettings.

Referenced by RegisterSettings().

◆ RegisterSettings()

template<typename T >
T * SETTINGS_MANAGER::RegisterSettings ( T *  aSettings,
bool  aLoadNow = true 
)
inline

Takes ownership of the pointer passed in.

Parameters
aSettingsis a settings object to register
Returns
a handle to the owned pointer

Definition at line 67 of file settings_manager.h.

68 {
69 return static_cast<T*>( registerSettings( aSettings, aLoadNow ) );
70 }
JSON_SETTINGS * registerSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)

References registerSettings().

Referenced by GetAppSettings(), loadAllColorSettings(), loadColorSettingsByName(), LoadProject(), loadProjectFile(), CV::IFACE::OnKifaceStart(), SCH::IFACE::OnKifaceStart(), GERBV::IFACE::OnKifaceStart(), PGE::IFACE::OnKifaceStart(), PCBCALC::IFACE::OnKifaceStart(), PCB::IFACE::OnKifaceStart(), PGM_KICAD::OnPgmInit(), registerColorSettings(), and SETTINGS_MANAGER().

◆ ReloadColorSettings()

void SETTINGS_MANAGER::ReloadColorSettings ( )

Re-scans the color themes directory, reloading any changes it finds.

Definition at line 353 of file settings_manager.cpp.

354{
355 m_color_settings.clear();
357}

References loadAllColorSettings(), and m_color_settings.

Referenced by PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS().

◆ Save() [1/2]

void SETTINGS_MANAGER::Save ( )

Definition at line 126 of file settings_manager.cpp.

127{
128 for( auto&& settings : m_settings )
129 {
130 // Never automatically save color settings, caller should use SaveColorSettings
131 if( dynamic_cast<COLOR_SETTINGS*>( settings.get() ) )
132 continue;
133
134 settings->SaveToFile( GetPathForSettingsFile( settings.get() ) );
135 }
136}

References GetPathForSettingsFile(), and m_settings.

Referenced by GetMigratedColorSettings(), FOOTPRINT_EDITOR_SETTINGS::MigrateFromLegacy(), and COLOR_SETTINGS::migrateSchema0to1().

◆ Save() [2/2]

void SETTINGS_MANAGER::Save ( JSON_SETTINGS aSettings)

Definition at line 139 of file settings_manager.cpp.

140{
141 auto it = std::find_if( m_settings.begin(), m_settings.end(),
142 [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
143 {
144 return aPtr.get() == aSettings;
145 } );
146
147 if( it != m_settings.end() )
148 {
149 wxLogTrace( traceSettings, wxT( "Saving %s" ), ( *it )->GetFullFilename() );
150 ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
151 }
152}

References GetPathForSettingsFile(), m_settings, and traceSettings.

◆ SaveColorSettings()

void SETTINGS_MANAGER::SaveColorSettings ( COLOR_SETTINGS aSettings,
const std::string &  aNamespace = "" 
)

Safely saves a COLOR_SETTINGS to disk, preserving any changes outside the given namespace.

A color settings namespace is one of the top-level JSON objects like "board", etc. This will perform a read-modify-write

Parameters
aSettingsis a pointer to a valid COLOR_SETTINGS object managed by SETTINGS_MANAGER
aNamespaceis the namespace of settings to save

Definition at line 360 of file settings_manager.cpp.

361{
362 // The passed settings should already be managed
363 wxASSERT( std::find_if( m_color_settings.begin(), m_color_settings.end(),
364 [aSettings] ( const std::pair<wxString, COLOR_SETTINGS*>& el )
365 {
366 return el.second->GetFilename() == aSettings->GetFilename();
367 }
368 ) != m_color_settings.end() );
369
370 if( aSettings->IsReadOnly() )
371 return;
372
373 if( !aSettings->Store() )
374 {
375 wxLogTrace( traceSettings, wxT( "Color scheme %s not modified; skipping save" ),
376 aNamespace );
377 return;
378 }
379
380 wxASSERT( aSettings->Contains( aNamespace ) );
381
382 wxLogTrace( traceSettings, wxT( "Saving color scheme %s, preserving %s" ),
383 aSettings->GetFilename(),
384 aNamespace );
385
386 std::optional<nlohmann::json> backup = aSettings->GetJson( aNamespace );
387 wxString path = GetColorSettingsPath();
388
389 aSettings->LoadFromFile( path );
390
391 if( backup )
392 ( *aSettings->Internals() )[aNamespace].update( *backup );
393
394 aSettings->Load();
395
396 aSettings->SaveToFile( path, true );
397}
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 Contains(const std::string &aPath) const
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.
bool IsReadOnly() const
Definition: json_settings.h:84
JSON_SETTINGS_INTERNALS * Internals()
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...

References JSON_SETTINGS::Contains(), GetColorSettingsPath(), JSON_SETTINGS::GetFilename(), JSON_SETTINGS::GetJson(), JSON_SETTINGS::Internals(), JSON_SETTINGS::IsReadOnly(), JSON_SETTINGS::Load(), JSON_SETTINGS::LoadFromFile(), m_color_settings, path, JSON_SETTINGS::SaveToFile(), JSON_SETTINGS::Store(), and traceSettings.

Referenced by FOOTPRINT_EDITOR_SETTINGS::MigrateFromLegacy(), PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS(), and PANEL_COLOR_SETTINGS::saveCurrentTheme().

◆ SaveProject()

bool SETTINGS_MANAGER::SaveProject ( const wxString &  aFullPath = wxEmptyString,
PROJECT aProject = nullptr 
)

Saves a loaded project.

Parameters
aFullPathis the project name to save. If empty, will save the first loaded project.
aProjectis the project to save, or nullptr to save the active project (Prj() return)
Returns
true if save was successful

Definition at line 1012 of file settings_manager.cpp.

1013{
1014 if( !aProject )
1015 aProject = &Prj();
1016
1017 wxString path = aFullPath;
1018
1019 if( path.empty() )
1020 path = aProject->GetProjectFullName();
1021
1022 // TODO: refactor for MDI
1023 if( aProject->IsReadOnly() )
1024 return false;
1025
1026 if( !m_project_files.count( path ) )
1027 return false;
1028
1030 wxString projectPath = aProject->GetProjectPath();
1031
1032 project->SaveToFile( projectPath );
1033 aProject->GetLocalSettings().SaveToFile( projectPath );
1034
1035 return true;
1036}
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
virtual bool IsReadOnly() const
Definition: project.h:125
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:155

References PROJECT::GetLocalSettings(), PROJECT::GetProjectFullName(), PROJECT::GetProjectPath(), PROJECT::IsReadOnly(), m_project_files, path, Prj(), project, and PROJECT_LOCAL_SETTINGS::SaveToFile().

Referenced by KICAD_MANAGER_FRAME::CloseProject(), KICAD_MANAGER_FRAME::CreateNewProject(), PCB_EDIT_FRAME::Files_io_from_id(), SCH_EDIT_FRAME::OpenProjectFiles(), SCH_EDIT_FRAME::SaveProject(), SaveProjectAs(), SCH_EDIT_FRAME::SaveProjectSettings(), and PCB_EDIT_FRAME::SaveProjectSettings().

◆ SaveProjectAs()

void SETTINGS_MANAGER::SaveProjectAs ( const wxString &  aFullPath,
PROJECT aProject = nullptr 
)

Sets the currently loaded project path and saves it (pointers remain valid) Note that this will not modify the read-only state of the project, so it will have no effect if the project is marked as read-only!

Parameters
aFullPathis the full filename to set for the project
aProjectis the project to save, or nullptr to save the active project (Prj() return)

Definition at line 1039 of file settings_manager.cpp.

1040{
1041 if( !aProject )
1042 aProject = &Prj();
1043
1044 wxString oldName = aProject->GetProjectFullName();
1045
1046 if( aFullPath.IsSameAs( oldName ) )
1047 {
1048 SaveProject( aFullPath, aProject );
1049 return;
1050 }
1051
1052 // Changing this will cause UnloadProject to not save over the "old" project when loading below
1053 aProject->setProjectFullName( aFullPath );
1054
1055 wxFileName fn( aFullPath );
1056
1057 PROJECT_FILE* project = m_project_files.at( oldName );
1058
1059 // Ensure read-only flags are copied; this allows doing a "Save As" on a standalong board/sch
1060 // without creating project files if the checkbox is turned off
1061 project->SetReadOnly( aProject->IsReadOnly() );
1062 aProject->GetLocalSettings().SetReadOnly( aProject->IsReadOnly() );
1063
1064 project->SetFilename( fn.GetName() );
1065 project->SaveToFile( fn.GetPath() );
1066
1067 aProject->GetLocalSettings().SetFilename( fn.GetName() );
1068 aProject->GetLocalSettings().SaveToFile( fn.GetPath() );
1069
1070 m_project_files[fn.GetFullPath()] = project;
1071 m_project_files.erase( oldName );
1072
1073 m_projects[fn.GetFullPath()] = m_projects[oldName];
1074 m_projects.erase( oldName );
1075}
virtual void setProjectFullName(const wxString &aFullPathAndName)
Set the full directory, basename, and extension of the project.
Definition: project.cpp:88
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Saves a loaded project.

References PROJECT::GetLocalSettings(), PROJECT::GetProjectFullName(), PROJECT::IsReadOnly(), m_project_files, m_projects, Prj(), project, SaveProject(), PROJECT_LOCAL_SETTINGS::SaveToFile(), JSON_SETTINGS::SetFilename(), PROJECT::setProjectFullName(), and JSON_SETTINGS::SetReadOnly().

Referenced by SaveBoard(), PCB_EDIT_FRAME::SavePcbFile(), and SCH_EDIT_FRAME::SaveProject().

◆ SaveProjectCopy()

void SETTINGS_MANAGER::SaveProjectCopy ( const wxString &  aFullPath,
PROJECT aProject = nullptr 
)

Saves a copy of the current project under the given path.

Will save the copy even if the current project is marked as read-only.

Parameters
aFullPathis the full filename to set for the project
aProjectis the project to save, or nullptr to save the active project (Prj() return)

Definition at line 1078 of file settings_manager.cpp.

1079{
1080 if( !aProject )
1081 aProject = &Prj();
1082
1084 wxString oldName = project->GetFilename();
1085 wxFileName fn( aFullPath );
1086
1087 bool readOnly = project->IsReadOnly();
1088 project->SetReadOnly( false );
1089
1090 project->SetFilename( fn.GetName() );
1091 project->SaveToFile( fn.GetPath() );
1092 project->SetFilename( oldName );
1093
1094 PROJECT_LOCAL_SETTINGS& localSettings = aProject->GetLocalSettings();
1095
1096 localSettings.SetFilename( fn.GetName() );
1097 localSettings.SaveToFile( fn.GetPath() );
1098 localSettings.SetFilename( oldName );
1099
1100 project->SetReadOnly( readOnly );
1101}

References PROJECT::GetLocalSettings(), PROJECT::GetProjectFullName(), m_project_files, Prj(), project, PROJECT_LOCAL_SETTINGS::SaveToFile(), and JSON_SETTINGS::SetFilename().

Referenced by PCB_EDIT_FRAME::SavePcbCopy(), and SCH_EDIT_FRAME::SaveProject().

◆ SetKiway()

void SETTINGS_MANAGER::SetKiway ( KIWAY aKiway)
inline

Associate this setting manager with the given Kiway.

Parameters
aKiwayis the kiway this settings manager should use

Definition at line 59 of file settings_manager.h.

59{ m_kiway = aKiway; }

References m_kiway.

Referenced by PGM_SINGLE_TOP::OnPgmInit(), and PGM_KICAD::OnPgmInit().

◆ SetMigrateLibraryTables()

void SETTINGS_MANAGER::SetMigrateLibraryTables ( bool  aMigrate = true)
inline

Definition at line 218 of file settings_manager.h.

218{ m_migrateLibraryTables = aMigrate; }

References m_migrateLibraryTables.

Referenced by DIALOG_MIGRATE_SETTINGS::TransferDataFromWindow().

◆ SetMigrationSource()

void SETTINGS_MANAGER::SetMigrationSource ( const wxString &  aSource)
inline

Helper for DIALOG_MIGRATE_SETTINGS to specify a source for migration.

Parameters
aSourceis a directory containing settings files to migrate from (can be empty)

Definition at line 216 of file settings_manager.h.

216{ m_migration_source = aSource; }

References m_migration_source.

Referenced by DIALOG_MIGRATE_SETTINGS::TransferDataFromWindow().

◆ TriggerBackupIfNeeded()

bool SETTINGS_MANAGER::TriggerBackupIfNeeded ( REPORTER aReporter) const

Calls BackupProject if a new backup is needed according to the current backup policy.

Parameters
aReporteris used for progress reporting
Returns
if everything succeeded

Definition at line 1229 of file settings_manager.cpp.

1230{
1232
1233 if( !settings.enabled )
1234 return true;
1235
1236 wxString prefix = Prj().GetProjectName() + '-';
1237
1238 auto modTime =
1239 [&prefix]( const wxString& aFile )
1240 {
1241 wxDateTime dt;
1242 wxString fn( wxFileName( aFile ).GetName() );
1243 fn.Replace( prefix, wxS( "" ) );
1244 dt.ParseFormat( fn, backupDateTimeFormat );
1245 return dt;
1246 };
1247
1248 wxFileName projectPath( Prj().GetProjectPath() );
1249
1250 // Skip backup if project path isn't valid or writable
1251 if( !projectPath.IsOk() || !projectPath.Exists() || !projectPath.IsDirWritable() )
1252 return true;
1253
1254 wxString backupPath = GetProjectBackupsPath();
1255
1256 if( !wxDirExists( backupPath ) )
1257 {
1258 wxLogTrace( traceSettings, wxT( "Backup path %s doesn't exist, creating it" ), backupPath );
1259
1260 if( !wxMkdir( backupPath ) )
1261 {
1262 wxLogTrace( traceSettings, wxT( "Could not create backups path! Skipping backup" ) );
1263 return false;
1264 }
1265 }
1266
1267 wxDir dir( backupPath );
1268
1269 if( !dir.IsOpened() )
1270 {
1271 wxLogTrace( traceSettings, wxT( "Could not open project backups path %s" ), dir.GetName() );
1272 return false;
1273 }
1274
1275 std::vector<wxString> files;
1276
1277 VECTOR_INSERT_TRAVERSER traverser( files,
1278 [&modTime]( const wxString& aFile )
1279 {
1280 return modTime( aFile ).IsValid();
1281 } );
1282
1283 dir.Traverse( traverser, wxT( "*.zip" ) );
1284
1285 // Sort newest-first
1286 std::sort( files.begin(), files.end(),
1287 [&]( const wxString& aFirst, const wxString& aSecond ) -> bool
1288 {
1289 wxDateTime first = modTime( aFirst );
1290 wxDateTime second = modTime( aSecond );
1291
1292 return first.GetTicks() > second.GetTicks();
1293 } );
1294
1295 // Do we even need to back up?
1296 if( !files.empty() )
1297 {
1298 wxDateTime lastTime = modTime( files[0] );
1299
1300 if( lastTime.IsValid() )
1301 {
1302 wxTimeSpan delta = wxDateTime::Now() - modTime( files[0] );
1303
1304 if( delta.IsShorterThan( wxTimeSpan::Seconds( settings.min_interval ) ) )
1305 return true;
1306 }
1307 }
1308
1309 // Now that we know a backup is needed, apply the retention policy
1310
1311 // Step 1: if we're over the total file limit, remove the oldest
1312 if( !files.empty() && settings.limit_total_files > 0 )
1313 {
1314 while( files.size() > static_cast<size_t>( settings.limit_total_files ) )
1315 {
1316 wxRemoveFile( files.back() );
1317 files.pop_back();
1318 }
1319 }
1320
1321 // Step 2: Stay under the total size limit
1322 if( settings.limit_total_size > 0 )
1323 {
1324 wxULongLong totalSize = 0;
1325
1326 for( const wxString& file : files )
1327 totalSize += wxFileName::GetSize( file );
1328
1329 while( !files.empty() && totalSize > static_cast<wxULongLong>( settings.limit_total_size ) )
1330 {
1331 totalSize -= wxFileName::GetSize( files.back() );
1332 wxRemoveFile( files.back() );
1333 files.pop_back();
1334 }
1335 }
1336
1337 // Step 3: Stay under the daily limit
1338 if( settings.limit_daily_files > 0 && files.size() > 1 )
1339 {
1340 wxDateTime day = modTime( files[0] );
1341 int num = 1;
1342
1343 wxASSERT( day.IsValid() );
1344
1345 std::vector<wxString> filesToDelete;
1346
1347 for( size_t i = 1; i < files.size(); i++ )
1348 {
1349 wxDateTime dt = modTime( files[i] );
1350
1351 if( dt.IsSameDate( day ) )
1352 {
1353 num++;
1354
1355 if( num > settings.limit_daily_files )
1356 filesToDelete.emplace_back( files[i] );
1357 }
1358 else
1359 {
1360 day = dt;
1361 num = 1;
1362 }
1363 }
1364
1365 for( const wxString& file : filesToDelete )
1366 wxRemoveFile( file );
1367 }
1368
1369 return BackupProject( aReporter );
1370}
AUTO_BACKUP m_Backup
bool BackupProject(REPORTER &aReporter) const
Creates a backup archive of the current project.
COMMON_SETTINGS * GetCommonSettings() const
Retrieves the common settings shared by all applications.
int min_interval
Minimum time, in seconds, between subsequent backups.
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.
constexpr int delta

References backupDateTimeFormat, BackupProject(), delta, COMMON_SETTINGS::AUTO_BACKUP::enabled, GetCommonSettings(), GetProjectBackupsPath(), PROJECT::GetProjectName(), COMMON_SETTINGS::AUTO_BACKUP::limit_daily_files, COMMON_SETTINGS::AUTO_BACKUP::limit_total_files, COMMON_SETTINGS::AUTO_BACKUP::limit_total_size, COMMON_SETTINGS::m_Backup, COMMON_SETTINGS::AUTO_BACKUP::min_interval, Prj(), and traceSettings.

Referenced by KICAD_MANAGER_FRAME::CloseProject(), SCH_EDIT_FRAME::doAutoSave(), and PCB_EDIT_FRAME::doAutoSave().

◆ UnloadProject()

bool SETTINGS_MANAGER::UnloadProject ( PROJECT aProject,
bool  aSave = true 
)

Saves, unloads and unregisters the given PROJECT.

Parameters
aProjectis the project object to unload
aSaveif true will save the project before unloading
Returns
true if the PROJECT file was successfully saved

Definition at line 937 of file settings_manager.cpp.

938{
939 if( !aProject || !m_projects.count( aProject->GetProjectFullName() ) )
940 return false;
941
942 if( !unloadProjectFile( aProject, aSave ) )
943 return false;
944
945 wxString projectPath = aProject->GetProjectFullName();
946 wxLogTrace( traceSettings, wxT( "Unload project %s" ), projectPath );
947
948 PROJECT* toRemove = m_projects.at( projectPath );
949 auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
950 [&]( const std::unique_ptr<PROJECT>& ptr )
951 {
952 return ptr.get() == toRemove;
953 } );
954
955 wxASSERT( it != m_projects_list.end() );
956 m_projects_list.erase( it );
957
958 m_projects.erase( projectPath );
959
960 // Immediately reload a null project; this is required until the rest of the application
961 // is refactored to not assume that Prj() always works
962 if( m_projects.empty() )
963 LoadProject( "" );
964
965 // Remove the reference in the environment to the previous project
966 wxSetEnv( PROJECT_VAR_NAME, wxS( "" ) );
967
968 // Release lock on the file, in case we had one
969 m_project_lock = nullptr;
970
971 if( m_kiway )
973
974 return true;
975}
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Loads a project or sets up a new project with a specified path.
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition: project.h:39

References PROJECT::GetProjectFullName(), LoadProject(), m_kiway, m_project_lock, m_projects, m_projects_list, PROJECT_VAR_NAME, KIWAY::ProjectChanged(), traceSettings, and unloadProjectFile().

Referenced by KICAD_MANAGER_FRAME::CloseProject(), PCB_BASE_EDIT_FRAME::doCloseWindow(), PCB_EDIT_FRAME::Files_io_from_id(), KI_TEST::LoadSchematic(), DIALOG_SCHEMATIC_SETUP::onAuxiliaryAction(), DIALOG_BOARD_SETUP::onAuxiliaryAction(), SCH_EDIT_FRAME::OnImportProject(), KICAD_MANAGER_FRAME::OnUnarchiveFiles(), SCH_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), and SCH_EDIT_FRAME::~SCH_EDIT_FRAME().

◆ unloadProjectFile()

bool SETTINGS_MANAGER::unloadProjectFile ( PROJECT aProject,
bool  aSave 
)
private

Optionally saves, and then unloads and unregisters the given PROJECT_FILE.

Parameters
aProjectis the project object to unload the file for
aSaveif true will save the project file before unloading
Returns
true if the PROJECT file was successfully saved

Definition at line 1122 of file settings_manager.cpp.

1123{
1124 if( !aProject )
1125 return false;
1126
1127 wxString name = aProject->GetProjectFullName();
1128
1129 if( !m_project_files.count( name ) )
1130 return false;
1131
1133
1134 auto it = std::find_if( m_settings.begin(), m_settings.end(),
1135 [&file]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
1136 {
1137 return aPtr.get() == file;
1138 } );
1139
1140 if( it != m_settings.end() )
1141 {
1142 wxString projectPath = GetPathForSettingsFile( it->get() );
1143
1144 FlushAndRelease( &aProject->GetLocalSettings(), aSave );
1145
1146 if( aSave )
1147 ( *it )->SaveToFile( projectPath );
1148
1149 m_settings.erase( it );
1150 }
1151
1152 m_project_files.erase( name );
1153
1154 return true;
1155}
const char * name
Definition: DXF_plotter.cpp:56
void FlushAndRelease(JSON_SETTINGS *aSettings, bool aSave=true)
If the given settings object is registered, save it to disk and unregister it.

References FlushAndRelease(), PROJECT::GetLocalSettings(), GetPathForSettingsFile(), PROJECT::GetProjectFullName(), m_project_files, m_settings, and name.

Referenced by LoadProject(), and UnloadProject().

Member Data Documentation

◆ backupDateTimeFormat

wxString SETTINGS_MANAGER::backupDateTimeFormat = wxT( "%Y-%m-%d_%H%M%S" )
staticprivate

Definition at line 455 of file settings_manager.h.

Referenced by BackupProject(), and TriggerBackupIfNeeded().

◆ m_app_settings_cache

std::unordered_map<size_t, JSON_SETTINGS*> SETTINGS_MANAGER::m_app_settings_cache
private

Cache for app settings.

Definition at line 430 of file settings_manager.h.

Referenced by FlushAndRelease(), and GetAppSettings().

◆ m_color_settings

◆ m_common_settings

COMMON_SETTINGS* SETTINGS_MANAGER::m_common_settings
private

Definition at line 433 of file settings_manager.h.

Referenced by GetCommonSettings(), and SETTINGS_MANAGER().

◆ m_headless

bool SETTINGS_MANAGER::m_headless
private

True if running outside a UI context.

Definition at line 420 of file settings_manager.h.

Referenced by MigrateIfNeeded().

◆ m_kiway

KIWAY* SETTINGS_MANAGER::m_kiway
private

The kiway this settings manager interacts with.

Definition at line 423 of file settings_manager.h.

Referenced by LoadProject(), SetKiway(), and UnloadProject().

◆ m_migrateLibraryTables

bool SETTINGS_MANAGER::m_migrateLibraryTables
private

If true, the symbol and footprint library tables will be migrated from the previous version.

Definition at line 438 of file settings_manager.h.

Referenced by MigrateIfNeeded(), and SetMigrateLibraryTables().

◆ m_migration_source

wxString SETTINGS_MANAGER::m_migration_source
private

Definition at line 435 of file settings_manager.h.

Referenced by MigrateIfNeeded(), and SetMigrationSource().

◆ m_ok

bool SETTINGS_MANAGER::m_ok
private

True if settings loaded successfully at construction.

Definition at line 441 of file settings_manager.h.

Referenced by IsOK(), and SETTINGS_MANAGER().

◆ m_project_files

std::map<wxString, PROJECT_FILE*> SETTINGS_MANAGER::m_project_files
private

Loaded project files, mapped according to project full name.

Definition at line 450 of file settings_manager.h.

Referenced by loadProjectFile(), SaveProject(), SaveProjectAs(), SaveProjectCopy(), and unloadProjectFile().

◆ m_project_lock

std::unique_ptr<wxSingleInstanceChecker> SETTINGS_MANAGER::m_project_lock
private

Lock for loaded project (expand to multiple once we support MDI)

Definition at line 453 of file settings_manager.h.

Referenced by LoadProject(), and UnloadProject().

◆ m_projects

std::map<wxString, PROJECT*> SETTINGS_MANAGER::m_projects
private

Loaded projects, mapped according to project full name.

Definition at line 447 of file settings_manager.h.

Referenced by GetOpenProjects(), GetProject(), IsProjectOpen(), LoadProject(), SaveProjectAs(), UnloadProject(), and ~SETTINGS_MANAGER().

◆ m_projects_list

std::vector<std::unique_ptr<PROJECT> > SETTINGS_MANAGER::m_projects_list
private

Loaded projects (ownership here)

Definition at line 444 of file settings_manager.h.

Referenced by LoadProject(), Prj(), UnloadProject(), and ~SETTINGS_MANAGER().

◆ m_settings

std::vector<std::unique_ptr<JSON_SETTINGS> > SETTINGS_MANAGER::m_settings
private

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