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)
 Saves a loaded project. More...
 
void SaveProjectAs (const wxString &aFullPath)
 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)
 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)
 
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, int *aMinor)
 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 38 of file settings_manager.h.

Constructor & Destructor Documentation

◆ SETTINGS_MANAGER()

SETTINGS_MANAGER::SETTINGS_MANAGER ( bool  aHeadless = false)

Definition at line 54 of file settings_manager.cpp.

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

References PATHS::EnsureUserPathsExist(), m_common_settings, m_ok, MigrateIfNeeded(), and RegisterSettings().

◆ ~SETTINGS_MANAGER()

SETTINGS_MANAGER::~SETTINGS_MANAGER ( )

Definition at line 76 of file settings_manager.cpp.

77 {
78  m_settings.clear();
79  m_color_settings.clear();
80  m_projects.clear();
81 }
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< JSON_SETTINGS > > m_settings

References m_color_settings, m_projects, and m_settings.

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 268 of file settings_manager.cpp.

269 {
270  if( aName.EndsWith( wxT( ".json" ) ) )
271  return registerColorSettings( aName.BeforeLast( '.' ) );
272  else
273  return registerColorSettings( aName );
274 }
COLOR_SETTINGS * registerColorSettings(const wxString &aFilename)

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 1071 of file settings_manager.cpp.

1072 {
1073  wxDateTime timestamp = wxDateTime::Now();
1074 
1075  wxString fileName = wxString::Format( wxT( "%s-%s" ), Prj().GetProjectName(),
1076  timestamp.Format( backupDateTimeFormat ) );
1077 
1078  wxFileName target;
1079  target.SetPath( GetProjectBackupsPath() );
1080  target.SetName( fileName );
1081  target.SetExt( ArchiveFileExtension );
1082 
1083  wxDir dir( target.GetPath() );
1084 
1085  if( !target.DirExists() && !wxMkdir( target.GetPath() ) )
1086  {
1087  wxLogTrace( traceSettings, "Could not create project backup path %s", target.GetPath() );
1088  return false;
1089  }
1090 
1091  if( !target.IsDirWritable() )
1092  {
1093  wxLogTrace( traceSettings, "Backup directory %s is not writeable", target.GetPath() );
1094  return false;
1095  }
1096 
1097  wxLogTrace( traceSettings, "Backing up project to %s", target.GetPath() );
1098 
1099  PROJECT_ARCHIVER archiver;
1100 
1101  return archiver.Archive( Prj().GetProjectPath(), target.GetFullPath(), aReporter );
1102 }
static wxString backupDateTimeFormat
bool Archive(const wxString &aSrcDir, const wxString &aDestFile, REPORTER &aReporter, bool aVerbose=true, bool aIncludeExtraFiles=false)
Creates an archive of the project.
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
wxString GetProjectBackupsPath() const
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
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
const std::string ArchiveFileExtension

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 680 of file settings_manager.cpp.

681 {
682  wxFileName cfgpath;
683 
684  // http://docs.wxwidgets.org/3.0/classwx_standard_paths.html#a7c7cf595d94d29147360d031647476b0
685 
686  wxString envstr;
687  if( aUseEnv && wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
688  {
689  // Override the assignment above with KICAD_CONFIG_HOME
690  cfgpath.AssignDir( envstr );
691  }
692  else
693  {
694  cfgpath.AssignDir( KIPLATFORM::ENV::GetUserConfigPath() );
695 
696  cfgpath.AppendDir( TO_STR( KICAD_CONFIG_DIR ) );
697  }
698 
699  if( aIncludeVer )
700  cfgpath.AppendDir( GetSettingsVersion() );
701 
702  return cfgpath.GetPath();
703 }
#define TO_STR(x)
Definition: macros.h:105
wxString GetUserConfigPath()
Retrieves the operating system specific path for a user's configuration store.
static std::string GetSettingsVersion()
Parses the current KiCad build version and extracts the major and minor revision to use as the name o...

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 713 of file settings_manager.cpp.

714 {
715  int a_maj = 0;
716  int a_min = 0;
717  int b_maj = 0;
718  int b_min = 0;
719 
720  if( !extractVersion( aFirst, &a_maj, &a_min ) || !extractVersion( aSecond, &b_maj, &b_min ) )
721  {
722  wxLogTrace( traceSettings, "compareSettingsVersions: bad input (%s, %s)", aFirst, aSecond );
723  return -1;
724  }
725 
726  if( a_maj < b_maj )
727  {
728  return -1;
729  }
730  else if( a_maj > b_maj )
731  {
732  return 1;
733  }
734  else
735  {
736  if( a_min < b_min )
737  {
738  return -1;
739  }
740  else if( a_min > b_min )
741  {
742  return 1;
743  }
744  else
745  {
746  return 0;
747  }
748  }
749 }
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
static bool extractVersion(const std::string &aVersionString, int *aMajor, int *aMinor)
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,
int *  aMinor 
)
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 752 of file settings_manager.cpp.

753 {
754  std::regex re_version( "(\\d+)\\.(\\d+)" );
755  std::smatch match;
756 
757  if( std::regex_match( aVersionString, match, re_version ) )
758  {
759  try
760  {
761  *aMajor = std::stoi( match[1].str() );
762  *aMinor = std::stoi( match[2].str() );
763  }
764  catch( ... )
765  {
766  return false;
767  }
768 
769  return true;
770  }
771 
772  return false;
773 }

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 152 of file settings_manager.cpp.

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

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 93 of file settings_manager.h.

94  {
95  T* ret = nullptr;
96  size_t typeHash = typeid( T ).hash_code();
97 
98  if( m_app_settings_cache.count( typeHash ) )
99  ret = dynamic_cast<T*>( m_app_settings_cache.at( typeHash ) );
100 
101  if( ret )
102  return ret;
103 
104  auto it = std::find_if( m_settings.begin(), m_settings.end(),
105  []( const std::unique_ptr<JSON_SETTINGS>& aSettings )
106  {
107  return dynamic_cast<T*>( aSettings.get() );
108  } );
109 
110  if( it != m_settings.end() )
111  {
112  ret = dynamic_cast<T*>( it->get() );
113  }
114  else
115  {
116  try
117  {
118  ret = static_cast<T*>( RegisterSettings( new T, aLoadNow ) );
119  }
120  catch( ... )
121  {
122  }
123 
124  }
125 
126  m_app_settings_cache[typeHash] = ret;
127 
128  return ret;
129  }
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
std::unordered_map< size_t, JSON_SETTINGS * > m_app_settings_cache
Cache for app settings.
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings

References m_app_settings_cache, m_settings, and RegisterSettings().

Referenced by PL_EDITOR_FRAME::CommonSettingsChanged(), DIALOG_EXPORT_SVG::CreateSVGFile(), DIALOG_PCM::DIALOG_PCM(), SYMBOL_EDITOR_DRAWING_TOOLS::DrawShape(), SYMBOL_EDIT_FRAME::GetColorSettings(), SCH_BASE_FRAME::GetColorSettings(), LIB_PIN::LIB_PIN(), 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_PCBNEW_COLOR_SETTINGS::PANEL_PCBNEW_COLOR_SETTINGS(), PL_DRAW_PANEL_GAL::PL_DRAW_PANEL_GAL(), DIALOG_PLOT::Plot(), PANEL_PL_EDITOR_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_SYM_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_FP_EDITOR_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_PCBNEW_COLOR_SETTINGS::TransferDataFromWindow(), and PANEL_EESCHEMA_COLOR_SETTINGS::TransferDataFromWindow().

◆ 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 177 of file settings_manager.cpp.

178 {
179  if( m_color_settings.count( aName ) )
180  return m_color_settings.at( aName );
181 
182  if( !aName.empty() )
183  {
184  COLOR_SETTINGS* ret = loadColorSettingsByName( aName );
185 
186  if( !ret )
187  {
188  ret = registerColorSettings( aName );
189  *ret = *m_color_settings.at( "_builtin_default" );
190  ret->SetFilename( wxT( "user" ) );
191  ret->SetReadOnly( false );
192  }
193 
194  return ret;
195  }
196 
197  // This had better work
198  return m_color_settings.at( "_builtin_default" );
199 }
void SetReadOnly(bool aReadOnly)
Definition: json_settings.h:83
COLOR_SETTINGS * registerColorSettings(const wxString &aFilename)
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
COLOR_SETTINGS * loadColorSettingsByName(const wxString &aName)
Attempts to load a color theme by name (the color theme directory and .json ext are assumed)
Color settings are a bit different than most of the settings objects in that there can be more than o...
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:76

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

Referenced by PL_EDITOR_FRAME::CommonSettingsChanged(), DIALOG_EXPORT_SVG::CreateSVGFile(), DIALOG_PLOT_SCHEMATIC::getColorSettings(), SYMBOL_EDIT_FRAME::GetColorSettings(), SCH_BASE_FRAME::GetColorSettings(), GERBER_LAYER_WIDGET::OnLayerColorChange(), GERBER_LAYER_WIDGET::OnRenderColorChange(), PANEL_EESCHEMA_COLOR_SETTINGS::PANEL_EESCHEMA_COLOR_SETTINGS(), PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS(), PANEL_PCBNEW_COLOR_SETTINGS::PANEL_PCBNEW_COLOR_SETTINGS(), PL_DRAW_PANEL_GAL::PL_DRAW_PANEL_GAL(), DIALOG_PLOT::Plot(), SCH_PRINTOUT::PrintPage(), PANEL_COLOR_SETTINGS::saveCurrentTheme(), PANEL_SYM_COLOR_SETTINGS::TransferDataFromWindow(), and PANEL_SYM_COLOR_SETTINGS::TransferDataToWindow().

◆ GetColorSettingsList()

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

Definition at line 140 of file settings_manager.h.

141  {
142  std::vector<COLOR_SETTINGS*> ret;
143 
144  for( const std::pair<const wxString, COLOR_SETTINGS*>& entry : m_color_settings )
145  ret.push_back( entry.second );
146 
147  std::sort( ret.begin(), ret.end(), []( COLOR_SETTINGS* a, COLOR_SETTINGS* b )
148  {
149  return a->GetName() < b->GetName();
150  } );
151 
152  return ret;
153  }
const wxString & GetName() const
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
Color settings are a bit different than most of the settings objects in that there can be more than o...

References COLOR_SETTINGS::GetName(), and 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 648 of file settings_manager.cpp.

649 {
650  wxFileName path;
651 
652  path.AssignDir( GetUserSettingsPath() );
653  path.AppendDir( "colors" );
654 
655  if( !path.DirExists() )
656  {
657  if( !wxMkdir( path.GetPath() ) )
658  {
659  wxLogTrace( traceSettings,
660  "GetColorSettingsPath(): Path %s missing and could not be created!",
661  path.GetPath() );
662  }
663  }
664 
665  return path.GetPath();
666 }
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

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 184 of file settings_manager.h.

184 { return m_common_settings; }
COMMON_SETTINGS * m_common_settings

References m_common_settings.

Referenced by PGM_BASE::GetCommonSettings(), and 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 277 of file settings_manager.cpp.

278 {
279  if( !m_color_settings.count( "user" ) )
280  {
281  COLOR_SETTINGS* settings = registerColorSettings( wxT( "user" ) );
282  settings->SetName( wxT( "User" ) );
283  Save( settings );
284  }
285 
286  return m_color_settings.at( "user" );
287 }
void SetName(const wxString &aName)
COLOR_SETTINGS * registerColorSettings(const wxString &aFilename)
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
Color settings are a bit different than most of the settings objects in that there can be more than o...

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 916 of file settings_manager.cpp.

917 {
918  std::vector<wxString> ret;
919 
920  for( const std::pair<const wxString, PROJECT*>& pair : m_projects )
921  ret.emplace_back( pair.first );
922 
923  return ret;
924 }
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.

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 384 of file settings_manager.cpp.

385 {
386  wxASSERT( aSettings );
387 
388  switch( aSettings->GetLocation() )
389  {
390  case SETTINGS_LOC::USER:
391  return GetUserSettingsPath();
392 
394  return Prj().GetProjectPath();
395 
397  return GetColorSettingsPath();
398 
399  case SETTINGS_LOC::NONE:
400  return "";
401 
402  default:
403  wxASSERT_MSG( false, "Unknown settings location!" );
404  }
405 
406  return "";
407 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition: project.cpp:122
The color scheme directory (e.g. ~/.config/kicad/colors/)
The settings directory inside a project folder.
SETTINGS_LOC GetLocation() const
Definition: json_settings.h:78
No directory prepended, full path in filename (used for PROJECT_FILE)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
The main config directory (e.g. ~/.config/kicad/)

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

Referenced by FlushAndRelease(), Load(), PANEL_COLOR_SETTINGS::OnThemeChanged(), registerSettings(), Save(), SaveProject(), 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 539 of file settings_manager.cpp.

540 {
541  wxASSERT( aPaths );
542 
543  aPaths->clear();
544 
545  wxDir dir;
546  std::vector<wxFileName> base_paths;
547 
548  base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false ), "" ) );
549 
550  // If the env override is set, also check the default paths
551  if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), nullptr ) )
552  base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false, false ), "" ) );
553 
554 #ifdef __WXGTK__
555  // When running inside FlatPak, KIPLATFORM::ENV::GetUserConfigPath() will return a sandboxed
556  // path. In case the user wants to move from non-FlatPak KiCad to FlatPak KiCad, let's add our
557  // best guess as to the non-FlatPak config path. Unfortunately FlatPak also hides the host
558  // XDG_CONFIG_HOME, so if the user customizes their config path, they will have to browse
559  // for it.
560  {
561  wxFileName wxGtkPath;
562  wxGtkPath.AssignDir( "~/.config/kicad" );
563  wxGtkPath.MakeAbsolute();
564  base_paths.emplace_back( wxGtkPath.GetPath() );
565 
566  // We also want to pick up regular flatpak if we are nightly
567  wxGtkPath.AssignDir( "~/.var/app/org.kicad.KiCad/config/kicad" );
568  wxGtkPath.MakeAbsolute();
569  base_paths.emplace_back( wxGtkPath.GetPath() );
570  }
571 #endif
572 
573  wxString subdir;
574  std::string mine = GetSettingsVersion();
575 
576  auto check_dir = [&] ( const wxString& aSubDir )
577  {
578  // Only older versions are valid for migration
579  if( compareVersions( aSubDir.ToStdString(), mine ) <= 0 )
580  {
581  wxString sub_path = dir.GetNameWithSep() + aSubDir;
582 
583  if( IsSettingsPathValid( sub_path ) )
584  {
585  aPaths->push_back( sub_path );
586  wxLogTrace( traceSettings, "GetPreviousVersionName: %s is valid", sub_path );
587  }
588  }
589  };
590 
591  std::set<wxString> checkedPaths;
592 
593  for( auto base_path : base_paths )
594  {
595  if( checkedPaths.count( base_path.GetFullPath() ) )
596  continue;
597 
598  checkedPaths.insert( base_path.GetFullPath() );
599 
600  if( !dir.Open( base_path.GetFullPath() ) )
601  {
602  wxLogTrace( traceSettings, "GetPreviousVersionName: could not open base path %s",
603  base_path.GetFullPath() );
604  continue;
605  }
606 
607  wxLogTrace( traceSettings, "GetPreviousVersionName: checking base path %s",
608  base_path.GetFullPath() );
609 
610  if( dir.GetFirst( &subdir, wxEmptyString, wxDIR_DIRS ) )
611  {
612  if( subdir != mine )
613  check_dir( subdir );
614 
615  while( dir.GetNext( &subdir ) )
616  {
617  if( subdir != mine )
618  check_dir( subdir );
619  }
620  }
621 
622  // If we didn't find one yet, check for legacy settings without a version directory
623  if( IsSettingsPathValid( dir.GetNameWithSep() ) )
624  {
625  wxLogTrace( traceSettings,
626  "GetPreviousVersionName: root path %s is valid", dir.GetName() );
627  aPaths->push_back( dir.GetName() );
628  }
629  }
630 
631  return aPaths->size() > 0;
632 }
static bool IsSettingsPathValid(const wxString &aPath)
Checks if a given path is probably a valid KiCad configuration directory.
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 std::string GetSettingsVersion()
Parses the current KiCad build version and extracts the major and minor revision to use as the name o...
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

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 907 of file settings_manager.cpp.

908 {
909  if( m_projects.count( aFullPath ) )
910  return m_projects.at( aFullPath );
911 
912  return nullptr;
913 }
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.

References m_projects.

Referenced by GetDefaultProject(), LoadBoard(), 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 1062 of file settings_manager.cpp.

1063 {
1065 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
#define PROJECT_BACKUPS_DIR_SUFFIX
Project settings path will be <projectname> + this.
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition: project.cpp:122
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:128

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 706 of file settings_manager.cpp.

707 {
708  // CMake computes the major.minor string for us.
709  return GetMajorMinorVersion().ToStdString();
710 }
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 669 of file settings_manager.cpp.

670 {
671  static wxString user_settings_path;
672 
673  if( user_settings_path.empty() )
674  user_settings_path = calculateUserSettingsPath();
675 
676  return user_settings_path;
677 }
static wxString calculateUserSettingsPath(bool aIncludeVer=true, bool aUseEnv=true)
Determines the base path for user settings files.

References calculateUserSettingsPath().

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

◆ IsOK()

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

Definition at line 48 of file settings_manager.h.

48 { return m_ok; }
bool m_ok
True if settings loaded successfully at construction.

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 901 of file settings_manager.cpp.

902 {
903  return !m_projects.empty();
904 }
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.

References m_projects.

Referenced by PCB_BASE_EDIT_FRAME::doCloseWindow(), and FOOTPRINT_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 635 of file settings_manager.cpp.

636 {
637  wxFileName test( aPath, "kicad_common" );
638 
639  if( test.Exists() )
640  return true;
641 
642  test.SetExt( "json" );
643 
644  return test.Exists();
645 }

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

◆ Load() [1/2]

void SETTINGS_MANAGER::Load ( )

Definition at line 100 of file settings_manager.cpp.

101 {
102  // TODO(JE) We should check for dirty settings here and write them if so, because
103  // Load() could be called late in the application lifecycle
104 
105  for( auto&& settings : m_settings )
106  settings->LoadFromFile( GetPathForSettingsFile( settings.get() ) );
107 }
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

References GetPathForSettingsFile(), and m_settings.

Referenced by PGM_BASE::InitPgm().

◆ Load() [2/2]

void SETTINGS_MANAGER::Load ( JSON_SETTINGS aSettings)

Definition at line 110 of file settings_manager.cpp.

111 {
112  auto it = std::find_if( m_settings.begin(), m_settings.end(),
113  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
114  {
115  return aPtr.get() == aSettings;
116  } );
117 
118  if( it != m_settings.end() )
119  ( *it )->LoadFromFile( GetPathForSettingsFile( it->get() ) );
120 }
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

References GetPathForSettingsFile(), and m_settings.

◆ loadAllColorSettings()

void SETTINGS_MANAGER::loadAllColorSettings ( )
private

Definition at line 290 of file settings_manager.cpp.

291 {
292  // Create the built-in color settings
294  m_color_settings[settings->GetFilename()] = RegisterSettings( settings, false );
295 
296  wxFileName third_party_path;
297  const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
298  auto it = env.find( "KICAD6_3RD_PARTY" );
299 
300  if( it != env.end() && !it->second.GetValue().IsEmpty() )
301  third_party_path.SetPath( it->second.GetValue() );
302  else
303  third_party_path.SetPath( PATHS::GetDefault3rdPartyPath() );
304 
305  third_party_path.AppendDir( "colors" );
306 
307  wxDir third_party_colors_dir( third_party_path.GetFullPath() );
308  wxString color_settings_path = GetColorSettingsPath();
309 
310  JSON_DIR_TRAVERSER copier(
311  [&]( const wxFileName& aFilename )
312  {
313  wxFileName new_file( color_settings_path, aFilename.GetFullName() );
314 
315  if( !new_file.Exists() )
316  wxCopyFile( aFilename.GetFullPath(), new_file.GetFullPath());
317  } );
318 
319  // Search for and load any other settings
320  JSON_DIR_TRAVERSER loader( [&]( const wxFileName& aFilename )
321  {
322  registerColorSettings( aFilename.GetName() );
323  } );
324 
325  wxDir colors_dir( color_settings_path );
326 
327  if( colors_dir.IsOpened() )
328  {
329  if( third_party_colors_dir.IsOpened() )
330  third_party_colors_dir.Traverse( copier );
331 
332  colors_dir.Traverse( loader );
333  }
334 }
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:106
static std::vector< COLOR_SETTINGS * > CreateBuiltinColorSettings()
Constructs and returns a list of color settings objects based on the built-in color themes.
COLOR_SETTINGS * registerColorSettings(const wxString &aFilename)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
Color settings are a bit different than most of the settings objects in that there can be more than o...
static wxString GetDefault3rdPartyPath()
Gets the default path for PCM packages.
Definition: paths.cpp:129

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

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 202 of file settings_manager.cpp.

203 {
204  wxLogTrace( traceSettings, "Attempting to load color theme %s", aName );
205 
206  wxFileName fn( GetColorSettingsPath(), aName, "json" );
207 
208  if( !fn.IsOk() || !fn.Exists() )
209  {
210  wxLogTrace( traceSettings, "Theme file %s.json not found, falling back to user", aName );
211  return nullptr;
212  }
213 
214  COLOR_SETTINGS* settings = RegisterSettings( new COLOR_SETTINGS( aName ) );
215 
216  if( settings->GetFilename() != aName.ToStdString() )
217  {
218  wxLogTrace( traceSettings, "Warning: stored filename is actually %s, ",
219  settings->GetFilename() );
220  }
221 
222  m_color_settings[aName] = settings;
223 
224  return settings;
225 }
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
wxString GetFilename() const
Definition: json_settings.h:72
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
Color settings are a bit different than most of the settings objects in that there can be more than o...
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

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 776 of file settings_manager.cpp.

777 {
778  // Normalize path to new format even if migrating from a legacy file
779  wxFileName path( aFullPath );
780 
781  if( path.GetExt() == LegacyProjectFileExtension )
782  path.SetExt( ProjectFileExtension );
783 
784  wxString fullPath = path.GetFullPath();
785 
786  // If already loaded, we are all set. This might be called more than once over a project's
787  // lifetime in case the project is first loaded by the KiCad manager and then eeschema or
788  // pcbnew try to load it again when they are launched.
789  if( m_projects.count( fullPath ) )
790  return true;
791 
792  bool readOnly = false;
793  std::unique_ptr<wxSingleInstanceChecker> lockFile = ::LockFile( fullPath );
794 
795  if( !lockFile )
796  {
797  wxLogTrace( traceSettings, "Project %s is locked; opening read-only", fullPath );
798  readOnly = true;
799  }
800 
801  // No MDI yet
802  if( aSetActive && !m_projects.empty() )
803  {
804  PROJECT* oldProject = m_projects.begin()->second;
805  unloadProjectFile( oldProject, false );
806  m_projects.erase( m_projects.begin() );
807 
808  auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
809  [&]( const std::unique_ptr<PROJECT>& ptr )
810  {
811  return ptr.get() == oldProject;
812  } );
813 
814  wxASSERT( it != m_projects_list.end() );
815  m_projects_list.erase( it );
816  }
817 
818  wxLogTrace( traceSettings, "Load project %s", fullPath );
819 
820  std::unique_ptr<PROJECT> project = std::make_unique<PROJECT>();
821  project->setProjectFullName( fullPath );
822 
823  bool success = loadProjectFile( *project );
824 
825  if( success )
826  {
827  project->SetReadOnly( readOnly || project->GetProjectFile().IsReadOnly() );
828 
829  if( lockFile )
830  m_project_lock.reset( lockFile.release() );
831  }
832 
833  m_projects_list.push_back( std::move( project ) );
834  m_projects[fullPath] = m_projects_list.back().get();
835 
836  wxString fn( path.GetName() );
837 
838  PROJECT_LOCAL_SETTINGS* settings = new PROJECT_LOCAL_SETTINGS( m_projects[fullPath], fn );
839 
840  if( aSetActive )
841  settings = RegisterSettings( settings );
842 
843  m_projects[fullPath]->setLocalSettings( settings );
844 
845  if( aSetActive && m_kiway )
847 
848  return success;
849 }
Container for project specific data.
Definition: project.h:62
std::unique_ptr< wxSingleInstanceChecker > m_project_lock
Lock for loaded project (expand to multiple once we support MDI)
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
const std::string ProjectFileExtension
KIWAY * m_kiway
The kiway this settings manager interacts with.
The project local settings are things that are attached to a particular project, but also might be pa...
bool unloadProjectFile(PROJECT *aProject, bool aSave)
Optionally saves, and then unloads and unregisters the given PROJECT_FILE.
virtual void ProjectChanged()
Calls ProjectChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:576
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
const std::string LegacyProjectFileExtension
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.
bool loadProjectFile(PROJECT &aProject)
Registers a PROJECT_FILE and attempts to load it from disk.
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
std::vector< std::unique_ptr< PROJECT > > m_projects_list
Loaded projects (ownership here)

References LegacyProjectFileExtension, 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(), GetDefaultProject(), PGM_BASE::InitPgm(), LoadBoard(), KI_TEST::LoadBoard(), TEST_SCH_SHEET_LIST_FIXTURE::loadSchematic(), TEST_NETLISTS_FIXTURE::loadSchematic(), DIALOG_SCHEMATIC_SETUP::OnAuxiliaryAction(), DIALOG_BOARD_SETUP::OnAuxiliaryAction(), SCH_EDIT_FRAME::OnImportProject(), KICAD_MANAGER_FRAME::OnUnarchiveFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), SCH_EDIT_FRAME::OpenProjectFiles(), SCH::readSchematicFromFile(), TEST_NETLIST_EXPORTER_PSPICE_SIM::TEST_NETLIST_EXPORTER_PSPICE_SIM(), 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 1008 of file settings_manager.cpp.

1009 {
1010  wxFileName fullFn( aProject.GetProjectFullName() );
1011  wxString fn( fullFn.GetName() );
1012 
1013  PROJECT_FILE* file = RegisterSettings( new PROJECT_FILE( fn ), false );
1014 
1015  m_project_files[aProject.GetProjectFullName()] = file;
1016 
1017  aProject.setProjectFile( file );
1018  file->SetProject( &aProject );
1019 
1020  wxString path( fullFn.GetPath() );
1021 
1022  return file->LoadFromFile( path );
1023 }
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:64
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:116
virtual void setProjectFile(PROJECT_FILE *aFile)
Set the backing store file for this project.
Definition: project.h:320

References PROJECT::GetProjectFullName(), m_project_files, path, RegisterSettings(), 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 482 of file settings_manager.cpp.

483 {
484  if( m_headless )
485  {
486  wxLogTrace( traceSettings, "Settings migration not checked; running headless" );
487  return false;
488  }
489 
490  wxFileName path( GetUserSettingsPath(), "" );
491  wxLogTrace( traceSettings, "Using settings path %s", path.GetFullPath() );
492 
493  if( path.DirExists() )
494  {
495  wxFileName common = path;
496  common.SetName( "kicad_common" );
497  common.SetExt( "json" );
498 
499  if( common.Exists() )
500  {
501  wxLogTrace( traceSettings, "Path exists and has a kicad_common, continuing!" );
502  return true;
503  }
504  }
505 
506  // Now we have an empty path, let's figure out what to put in it
507  DIALOG_MIGRATE_SETTINGS dlg( this );
508 
509  if( dlg.ShowModal() != wxID_OK )
510  {
511  wxLogTrace( traceSettings, "Migration dialog canceled; exiting" );
512  return false;
513  }
514 
515  if( !path.DirExists() )
516  {
517  wxLogTrace( traceSettings, "Path didn't exist; creating it" );
518  path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
519  }
520 
521  if( m_migration_source.IsEmpty() )
522  {
523  wxLogTrace( traceSettings, "No migration source given; starting with defaults" );
524  return true;
525  }
526 
528  wxDir source_dir( m_migration_source );
529 
530  source_dir.Traverse( traverser );
531 
532  if( !traverser.GetErrors().empty() )
533  DisplayErrorMessage( nullptr, traverser.GetErrors() );
534 
535  return true;
536 }
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:284
bool m_migrateLibraryTables
If true, the symbol and footprint library tables will be migrated from the previous version.
wxString m_migration_source
bool m_headless
True if running outside a UI context.
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

References DisplayErrorMessage(), GetUserSettingsPath(), m_headless, m_migrateLibraryTables, m_migration_source, path, and traceSettings.

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 893 of file settings_manager.cpp.

894 {
895  // No MDI yet: First project in the list is the active project
896  wxASSERT_MSG( m_projects_list.size(), "no project in list" );
897  return *m_projects_list.begin()->get();
898 }
std::vector< std::unique_ptr< PROJECT > > m_projects_list
Loaded projects (ownership here)

References m_projects_list.

Referenced by BackupProject(), PCB_EDIT_FRAME::Files_io_from_id(), GetPathForSettingsFile(), GetProjectBackupsPath(), KI_TEST::LoadBoard(), TEST_SCH_SHEET_LIST_FIXTURE::loadSchematic(), TEST_NETLISTS_FIXTURE::loadSchematic(), PCB_EDIT_FRAME::OpenProjectFiles(), SaveProject(), SaveProjectAs(), SaveProjectCopy(), TEST_NETLIST_EXPORTER_PSPICE_SIM::TEST_NETLIST_EXPORTER_PSPICE_SIM(), TriggerBackupIfNeeded(), and WriteDRCReport().

◆ registerColorSettings()

COLOR_SETTINGS * SETTINGS_MANAGER::registerColorSettings ( const wxString &  aFilename)
private

Definition at line 256 of file settings_manager.cpp.

257 {
258  if( !m_color_settings.count( aName ) )
259  {
260  COLOR_SETTINGS* colorSettings = RegisterSettings( new COLOR_SETTINGS( aName ) );
261  m_color_settings[aName] = colorSettings;
262  }
263 
264  return m_color_settings.at( aName );
265 }
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
Color settings are a bit different than most of the settings objects in that there can be more than o...

References m_color_settings, and RegisterSettings().

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

◆ 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 63 of file settings_manager.h.

64  {
65  return static_cast<T*>( registerSettings( aSettings, aLoadNow ) );
66  }
JSON_SETTINGS * registerSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)

References registerSettings().

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

◆ registerSettings()

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

Definition at line 84 of file settings_manager.cpp.

85 {
86  std::unique_ptr<JSON_SETTINGS> ptr( aSettings );
87 
88  ptr->SetManager( this );
89 
90  wxLogTrace( traceSettings, "Registered new settings object <%s>", ptr->GetFullFilename() );
91 
92  if( aLoadNow )
93  ptr->LoadFromFile( GetPathForSettingsFile( ptr.get() ) );
94 
95  m_settings.push_back( std::move( ptr ) );
96  return m_settings.back().get();
97 }
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

References GetPathForSettingsFile(), m_settings, and traceSettings.

Referenced by RegisterSettings().

◆ ReloadColorSettings()

void SETTINGS_MANAGER::ReloadColorSettings ( )

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

Definition at line 337 of file settings_manager.cpp.

338 {
339  m_color_settings.clear();
341 }
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings

References loadAllColorSettings(), and m_color_settings.

Referenced by PANEL_EESCHEMA_COLOR_SETTINGS::PANEL_EESCHEMA_COLOR_SETTINGS(), and PANEL_FP_EDITOR_COLOR_SETTINGS::PANEL_FP_EDITOR_COLOR_SETTINGS().

◆ Save() [1/2]

void SETTINGS_MANAGER::Save ( )

Definition at line 123 of file settings_manager.cpp.

124 {
125  for( auto&& settings : m_settings )
126  {
127  // Never automatically save color settings, caller should use SaveColorSettings
128  if( dynamic_cast<COLOR_SETTINGS*>( settings.get() ) )
129  continue;
130 
131  settings->SaveToFile( GetPathForSettingsFile( settings.get() ) );
132  }
133 }
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

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 136 of file settings_manager.cpp.

137 {
138  auto it = std::find_if( m_settings.begin(), m_settings.end(),
139  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
140  {
141  return aPtr.get() == aSettings;
142  } );
143 
144  if( it != m_settings.end() )
145  {
146  wxLogTrace( traceSettings, "Saving %s", ( *it )->GetFullFilename() );
147  ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
148  }
149 }
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

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 344 of file settings_manager.cpp.

345 {
346  // The passed settings should already be managed
347  wxASSERT( std::find_if( m_color_settings.begin(), m_color_settings.end(),
348  [aSettings] ( const std::pair<wxString, COLOR_SETTINGS*>& el )
349  {
350  return el.second->GetFilename() == aSettings->GetFilename();
351  }
352  ) != m_color_settings.end() );
353 
354  if( aSettings->IsReadOnly() )
355  return;
356 
357  if( !aSettings->Store() )
358  {
359  wxLogTrace( traceSettings, "Color scheme %s not modified; skipping save",
360  aNamespace );
361  return;
362  }
363 
364  wxASSERT( aSettings->Contains( aNamespace ) );
365 
366  wxLogTrace( traceSettings, "Saving color scheme %s, preserving %s",
367  aSettings->GetFilename(),
368  aNamespace );
369 
370  OPT<nlohmann::json> backup = aSettings->GetJson( aNamespace );
371  wxString path = GetColorSettingsPath();
372 
373  aSettings->LoadFromFile( path );
374 
375  if( backup )
376  ( *aSettings->Internals() )[aNamespace].update( *backup );
377 
378  aSettings->Load();
379 
380  aSettings->SaveToFile( path, true );
381 }
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
JSON_SETTINGS_INTERNALS * Internals()
wxString GetFilename() const
Definition: json_settings.h:72
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
OPT< 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....
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
bool IsReadOnly() const
Definition: json_settings.h:82
boost::optional< T > OPT
Definition: optional.h:7
bool Contains(const std::string &aPath) const
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.

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(), PANEL_COLOR_SETTINGS::saveCurrentTheme(), FOOTPRINT_EDIT_FRAME::SaveSettings(), and PCB_EDIT_FRAME::SaveSettings().

◆ SaveProject()

bool SETTINGS_MANAGER::SaveProject ( const wxString &  aFullPath = wxEmptyString)

Saves a loaded project.

Parameters
aFullPathis the project name to save. If empty, will save the first loaded project.
Returns
true if save was successful

Definition at line 927 of file settings_manager.cpp.

928 {
929  wxString path = aFullPath;
930 
931  if( path.empty() )
933 
934  // TODO: refactor for MDI
935  if( Prj().IsReadOnly() )
936  return false;
937 
938  if( !m_project_files.count( path ) )
939  return false;
940 
942  wxString projectPath = GetPathForSettingsFile( project );
943 
944  project->SaveToFile( projectPath );
945  Prj().GetLocalSettings().SaveToFile( projectPath );
946 
947  return true;
948 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:64
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:151
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:116
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

References PROJECT::GetLocalSettings(), GetPathForSettingsFile(), PROJECT::GetProjectFullName(), 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)

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

Definition at line 951 of file settings_manager.cpp.

952 {
953  wxString oldName = Prj().GetProjectFullName();
954 
955  if( aFullPath.IsSameAs( oldName ) )
956  {
957  SaveProject( aFullPath );
958  return;
959  }
960 
961  // Changing this will cause UnloadProject to not save over the "old" project when loading below
962  Prj().setProjectFullName( aFullPath );
963 
964  wxFileName fn( aFullPath );
965 
966  PROJECT_FILE* project = m_project_files.at( oldName );
967 
968  // Ensure read-only flags are copied; this allows doing a "Save As" on a standalong board/sch
969  // without creating project files if the checkbox is turned off
970  project->SetReadOnly( Prj().IsReadOnly() );
971  Prj().GetLocalSettings().SetReadOnly( Prj().IsReadOnly() );
972 
973  project->SetFilename( fn.GetName() );
974  project->SaveToFile( fn.GetPath() );
975 
976  Prj().GetLocalSettings().SetFilename( fn.GetName() );
977  Prj().GetLocalSettings().SaveToFile( fn.GetPath() );
978 
979  m_project_files[fn.GetFullPath()] = project;
980  m_project_files.erase( oldName );
981 
982  m_projects[fn.GetFullPath()] = m_projects[oldName];
983  m_projects.erase( oldName );
984 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
void SetReadOnly(bool aReadOnly)
Definition: json_settings.h:83
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:64
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:151
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:116
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.
virtual void setProjectFullName(const wxString &aFullPathAndName)
Set the full directory, basename, and extension of the project.
Definition: project.cpp:84
bool SaveProject(const wxString &aFullPath=wxEmptyString)
Saves a loaded project.
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:76

References PROJECT::GetLocalSettings(), PROJECT::GetProjectFullName(), 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)

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.

Definition at line 987 of file settings_manager.cpp.

988 {
989  PROJECT_FILE* project = m_project_files.at( Prj().GetProjectFullName() );
990  wxString oldName = project->GetFilename();
991  wxFileName fn( aFullPath );
992 
993  bool readOnly = project->IsReadOnly();
994  project->SetReadOnly( false );
995 
996  project->SetFilename( fn.GetName() );
997  project->SaveToFile( fn.GetPath() );
998  project->SetFilename( oldName );
999 
1000  Prj().GetLocalSettings().SetFilename( fn.GetName() );
1001  Prj().GetLocalSettings().SaveToFile( fn.GetPath() );
1002  Prj().GetLocalSettings().SetFilename( oldName );
1003 
1004  project->SetReadOnly( readOnly );
1005 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:64
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:151
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:76

References PROJECT::GetLocalSettings(), 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 55 of file settings_manager.h.

55 { m_kiway = aKiway; }
KIWAY * m_kiway
The kiway this settings manager interacts with.

References m_kiway.

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

◆ SetMigrateLibraryTables()

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

Definition at line 214 of file settings_manager.h.

214 { m_migrateLibraryTables = aMigrate; }
bool m_migrateLibraryTables
If true, the symbol and footprint library tables will be migrated from the previous version.

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 212 of file settings_manager.h.

212 { m_migration_source = aSource; }
wxString m_migration_source

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 1135 of file settings_manager.cpp.

1136 {
1138 
1139  if( !settings.enabled )
1140  return true;
1141 
1142  wxString prefix = Prj().GetProjectName() + '-';
1143 
1144  auto modTime =
1145  [&prefix]( const wxString& aFile )
1146  {
1147  wxDateTime dt;
1148  wxString fn( wxFileName( aFile ).GetName() );
1149  fn.Replace( prefix, "" );
1150  dt.ParseFormat( fn, backupDateTimeFormat );
1151  return dt;
1152  };
1153 
1154  wxFileName projectPath( Prj().GetProjectPath() );
1155 
1156  // Skip backup if project path isn't valid or writeable
1157  if( !projectPath.IsOk() || !projectPath.Exists() || !projectPath.IsDirWritable() )
1158  return true;
1159 
1160  wxString backupPath = GetProjectBackupsPath();
1161 
1162  if( !wxDirExists( backupPath ) )
1163  {
1164  wxLogTrace( traceSettings, "Backup path %s doesn't exist, creating it", backupPath );
1165 
1166  if( !wxMkdir( backupPath ) )
1167  {
1168  wxLogTrace( traceSettings, "Could not create backups path! Skipping backup" );
1169  return false;
1170  }
1171  }
1172 
1173  wxDir dir( backupPath );
1174 
1175  if( !dir.IsOpened() )
1176  {
1177  wxLogTrace( traceSettings, "Could not open project backups path %s", dir.GetName() );
1178  return false;
1179  }
1180 
1181  std::vector<wxString> files;
1182 
1183  VECTOR_INSERT_TRAVERSER traverser( files,
1184  [&modTime]( const wxString& aFile )
1185  {
1186  return modTime( aFile ).IsValid();
1187  } );
1188 
1189  dir.Traverse( traverser, wxT( "*.zip" ) );
1190 
1191  // Sort newest-first
1192  std::sort( files.begin(), files.end(),
1193  [&]( const wxString& aFirst, const wxString& aSecond ) -> bool
1194  {
1195  wxDateTime first = modTime( aFirst );
1196  wxDateTime second = modTime( aSecond );
1197 
1198  return first.GetTicks() > second.GetTicks();
1199  } );
1200 
1201  // Do we even need to back up?
1202  if( !files.empty() )
1203  {
1204  wxDateTime lastTime = modTime( files[0] );
1205 
1206  if( lastTime.IsValid() )
1207  {
1208  wxTimeSpan delta = wxDateTime::Now() - modTime( files[0] );
1209 
1210  if( delta.IsShorterThan( wxTimeSpan::Seconds( settings.min_interval ) ) )
1211  return true;
1212  }
1213  }
1214 
1215  // Now that we know a backup is needed, apply the retention policy
1216 
1217  // Step 1: if we're over the total file limit, remove the oldest
1218  if( !files.empty() && settings.limit_total_files > 0 )
1219  {
1220  while( files.size() > static_cast<size_t>( settings.limit_total_files ) )
1221  {
1222  wxRemoveFile( files.back() );
1223  files.pop_back();
1224  }
1225  }
1226 
1227  // Step 2: Stay under the total size limit
1228  if( settings.limit_total_size > 0 )
1229  {
1230  wxULongLong totalSize = 0;
1231 
1232  for( const wxString& file : files )
1233  totalSize += wxFileName::GetSize( file );
1234 
1235  while( !files.empty() && totalSize > static_cast<wxULongLong>( settings.limit_total_size ) )
1236  {
1237  totalSize -= wxFileName::GetSize( files.back() );
1238  wxRemoveFile( files.back() );
1239  files.pop_back();
1240  }
1241  }
1242 
1243  // Step 3: Stay under the daily limit
1244  if( settings.limit_daily_files > 0 && files.size() > 1 )
1245  {
1246  wxDateTime day = modTime( files[0] );
1247  int num = 1;
1248 
1249  wxASSERT( day.IsValid() );
1250 
1251  std::vector<wxString> filesToDelete;
1252 
1253  for( size_t i = 1; i < files.size(); i++ )
1254  {
1255  wxDateTime dt = modTime( files[i] );
1256 
1257  if( dt.IsSameDate( day ) )
1258  {
1259  num++;
1260 
1261  if( num > settings.limit_daily_files )
1262  filesToDelete.emplace_back( files[i] );
1263  }
1264  else
1265  {
1266  day = dt;
1267  num = 1;
1268  }
1269  }
1270 
1271  for( const wxString& file : filesToDelete )
1272  wxRemoveFile( file );
1273  }
1274 
1275  return BackupProject( aReporter );
1276 }
static wxString backupDateTimeFormat
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
unsigned long long limit_total_size
Maximum total size of backups (bytes), 0 for unlimited.
bool enabled
Automatically back up the project when files are saved.
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.
wxString GetProjectBackupsPath() const
int min_interval
Minimum time, in seconds, between subsequent backups.
constexpr int delta
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:128
int limit_daily_files
Maximum files to keep per day, 0 for unlimited.
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
int limit_total_files
Maximum number of backup archives to retain.

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(), PCB_EDIT_FRAME::doAutoSave(), and SCH_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 852 of file settings_manager.cpp.

853 {
854  if( !aProject || !m_projects.count( aProject->GetProjectFullName() ) )
855  return false;
856 
857  if( !unloadProjectFile( aProject, aSave ) )
858  return false;
859 
860  wxString projectPath = aProject->GetProjectFullName();
861  wxLogTrace( traceSettings, "Unload project %s", projectPath );
862 
863  PROJECT* toRemove = m_projects.at( projectPath );
864  auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
865  [&]( const std::unique_ptr<PROJECT>& ptr )
866  {
867  return ptr.get() == toRemove;
868  } );
869 
870  wxASSERT( it != m_projects_list.end() );
871  m_projects_list.erase( it );
872 
873  m_projects.erase( projectPath );
874 
875  // Immediately reload a null project; this is required until the rest of the application
876  // is refactored to not assume that Prj() always works
877  if( m_projects.empty() )
878  LoadProject( "" );
879 
880  // Remove the reference in the environment to the previous project
881  wxSetEnv( PROJECT_VAR_NAME, "" );
882 
883  // Release lock on the file, in case we had one
884  m_project_lock = nullptr;
885 
886  if( m_kiway )
888 
889  return true;
890 }
Container for project specific data.
Definition: project.h:62
std::unique_ptr< wxSingleInstanceChecker > m_project_lock
Lock for loaded project (expand to multiple once we support MDI)
KIWAY * m_kiway
The kiway this settings manager interacts with.
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition: project.h:38
bool unloadProjectFile(PROJECT *aProject, bool aSave)
Optionally saves, and then unloads and unregisters the given PROJECT_FILE.
virtual void ProjectChanged()
Calls ProjectChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:576
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:116
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Loads a project or sets up a new project with a specified path.
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
std::vector< std::unique_ptr< PROJECT > > m_projects_list
Loaded projects (ownership here)

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(), DIALOG_SCHEMATIC_SETUP::OnAuxiliaryAction(), DIALOG_BOARD_SETUP::OnAuxiliaryAction(), SCH_EDIT_FRAME::OnImportProject(), KICAD_MANAGER_FRAME::OnUnarchiveFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), SCH_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 1026 of file settings_manager.cpp.

1027 {
1028  if( !aProject )
1029  return false;
1030 
1031  wxString name = aProject->GetProjectFullName();
1032 
1033  if( !m_project_files.count( name ) )
1034  return false;
1035 
1037 
1038  auto it = std::find_if( m_settings.begin(), m_settings.end(),
1039  [&file]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
1040  {
1041  return aPtr.get() == file;
1042  } );
1043 
1044  if( it != m_settings.end() )
1045  {
1046  wxString projectPath = GetPathForSettingsFile( it->get() );
1047 
1048  FlushAndRelease( &aProject->GetLocalSettings(), aSave );
1049 
1050  if( aSave )
1051  ( *it )->SaveToFile( projectPath );
1052 
1053  m_settings.erase( it );
1054  }
1055 
1056  m_project_files.erase( name );
1057 
1058  return true;
1059 }
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:64
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:151
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:116
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
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.
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.

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 446 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 421 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 424 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 411 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 414 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 429 of file settings_manager.h.

Referenced by MigrateIfNeeded(), and SetMigrateLibraryTables().

◆ m_migration_source

wxString SETTINGS_MANAGER::m_migration_source
private

Definition at line 426 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 432 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 441 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 444 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 438 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 435 of file settings_manager.h.

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

◆ 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: