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...
 
JSON_SETTINGSRegisterSettings (JSON_SETTINGS *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 AppSettings >
AppSettings * 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)
 Retreives 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) 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

COLOR_SETTINGSloadColorSettingsByName (const wxString &aName)
 Attempts to load a color theme by name (the color theme directory and .json ext are assumed) More...
 
void registerColorSettings (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 37 of file settings_manager.h.

Constructor & Destructor Documentation

◆ SETTINGS_MANAGER()

SETTINGS_MANAGER::SETTINGS_MANAGER ( bool  aHeadless = false)

Definition at line 52 of file settings_manager.cpp.

52  :
53  m_headless( aHeadless ),
54  m_kiway( nullptr ),
55  m_common_settings( nullptr ),
58 {
60 
61  // Check if the settings directory already exists, and if not, perform a migration if possible
62  if( !MigrateIfNeeded() )
63  {
64  m_ok = false;
65  return;
66  }
67 
68  m_ok = true;
69 
70  // create the common settings shared by all applications. Not loaded immediately
72  static_cast<COMMON_SETTINGS*>( RegisterSettings( new COMMON_SETTINGS, false ) );
73 
75 }
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:263
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
COMMON_SETTINGS * m_common_settings

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

◆ ~SETTINGS_MANAGER()

SETTINGS_MANAGER::~SETTINGS_MANAGER ( )

Definition at line 77 of file settings_manager.cpp.

78 {
79  m_settings.clear();
80  m_color_settings.clear();
81  m_projects.clear();
82 }
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 264 of file settings_manager.cpp.

265 {
266  wxString filename = aFilename;
267 
268  if( filename.EndsWith( wxT( ".json" ) ) )
269  filename = filename.BeforeLast( '.' );
270 
271  registerColorSettings( filename );
272  return m_color_settings[filename];
273 }
void registerColorSettings(const wxString &aFilename)
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings

References m_color_settings, and 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 1015 of file settings_manager.cpp.

1016 {
1017  wxDateTime timestamp = wxDateTime::Now();
1018 
1019  wxString fileName = wxString::Format( wxT( "%s-%s" ), Prj().GetProjectName(),
1020  timestamp.Format( backupDateTimeFormat ) );
1021 
1022  wxFileName target;
1023  target.SetPath( GetProjectBackupsPath() );
1024  target.SetName( fileName );
1025  target.SetExt( ArchiveFileExtension );
1026 
1027  wxDir dir( target.GetPath() );
1028 
1029  if( !target.DirExists() && !wxMkdir( target.GetPath() ) )
1030  {
1031  wxLogTrace( traceSettings, "Could not create project backup path %s", target.GetPath() );
1032  return false;
1033  }
1034 
1035  if( !target.IsDirWritable() )
1036  {
1037  wxLogTrace( traceSettings, "Backup directory %s is not writeable", target.GetPath() );
1038  return false;
1039  }
1040 
1041  wxLogTrace( traceSettings, "Backing up project to %s", target.GetPath() );
1042 
1043  PROJECT_ARCHIVER archiver;
1044 
1045  return archiver.Archive( Prj().GetProjectPath(), target.GetFullPath(), aReporter );
1046 }
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 650 of file settings_manager.cpp.

651 {
652  wxFileName cfgpath;
653 
654  // http://docs.wxwidgets.org/3.0/classwx_standard_paths.html#a7c7cf595d94d29147360d031647476b0
655 
656  wxString envstr;
657  if( aUseEnv && wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
658  {
659  // Override the assignment above with KICAD_CONFIG_HOME
660  cfgpath.AssignDir( envstr );
661  }
662  else
663  {
664  cfgpath.AssignDir( KIPLATFORM::ENV::GetUserConfigPath() );
665 
666  cfgpath.AppendDir( TO_STR( KICAD_CONFIG_DIR ) );
667  }
668 
669  if( aIncludeVer )
670  cfgpath.AppendDir( GetSettingsVersion() );
671 
672  return cfgpath.GetPath();
673 }
#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 683 of file settings_manager.cpp.

684 {
685  int a_maj = 0;
686  int a_min = 0;
687  int b_maj = 0;
688  int b_min = 0;
689 
690  if( !extractVersion( aFirst, &a_maj, &a_min ) || !extractVersion( aSecond, &b_maj, &b_min ) )
691  {
692  wxLogTrace( traceSettings, "compareSettingsVersions: bad input (%s, %s)", aFirst, aSecond );
693  return -1;
694  }
695 
696  if( a_maj < b_maj )
697  {
698  return -1;
699  }
700  else if( a_maj > b_maj )
701  {
702  return 1;
703  }
704  else
705  {
706  if( a_min < b_min )
707  {
708  return -1;
709  }
710  else if( a_min > b_min )
711  {
712  return 1;
713  }
714  else
715  {
716  return 0;
717  }
718  }
719 }
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 722 of file settings_manager.cpp.

723 {
724  std::regex re_version( "(\\d+)\\.(\\d+)" );
725  std::smatch match;
726 
727  if( std::regex_match( aVersionString, match, re_version ) )
728  {
729  try
730  {
731  *aMajor = std::stoi( match[1].str() );
732  *aMinor = std::stoi( match[2].str() );
733  }
734  catch( ... )
735  {
736  return false;
737  }
738 
739  return true;
740  }
741 
742  return false;
743 }

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

154 {
155  auto it = std::find_if( m_settings.begin(), m_settings.end(),
156  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
157  {
158  return aPtr.get() == aSettings;
159  } );
160 
161  if( it != m_settings.end() )
162  {
163  wxLogTrace( traceSettings, "Flush and release %s", ( *it )->GetFullFilename() );
164 
165  if( aSave )
166  ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
167 
168  size_t typeHash = typeid( *it->get() ).hash_code();
169 
170  if( m_app_settings_cache.count( typeHash ) )
171  m_app_settings_cache.erase( typeHash );
172 
173  m_settings.erase( it );
174 
175 
176  }
177 }
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 AppSettings >
AppSettings* 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
AppSettingsis 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 88 of file settings_manager.h.

89  {
90  AppSettings* ret = nullptr;
91  size_t typeHash = typeid( AppSettings ).hash_code();
92 
93  if( m_app_settings_cache.count( typeHash ) )
94  ret = dynamic_cast<AppSettings*>( m_app_settings_cache.at( typeHash ) );
95 
96  if( ret )
97  return ret;
98 
99  auto it = std::find_if( m_settings.begin(), m_settings.end(),
100  []( const std::unique_ptr<JSON_SETTINGS>& aSettings )
101  {
102  return dynamic_cast<AppSettings*>( aSettings.get() );
103  } );
104 
105  if( it != m_settings.end() )
106  {
107  ret = dynamic_cast<AppSettings*>( it->get() );
108  }
109  else
110  {
111  try
112  {
113  ret = static_cast<AppSettings*>( RegisterSettings( new AppSettings, aLoadNow ) );
114  }
115  catch( ... )
116  {
117  wxLogTrace( traceSettings, "Unable to create application settings object" );
118  }
119 
120  }
121 
122  m_app_settings_cache[typeHash] = ret;
123 
124  return ret;
125  }
std::unordered_map< size_t, JSON_SETTINGS * > m_app_settings_cache
Cache for app settings.
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

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

Referenced by PL_EDITOR_FRAME::CommonSettingsChanged(), DIALOG_EXPORT_SVG::CreateSVGFile(), SYMBOL_EDIT_FRAME::GetColorSettings(), SCH_BASE_FRAME::GetColorSettings(), LIB_PIN::LIB_PIN(), 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 180 of file settings_manager.cpp.

181 {
182  if( m_color_settings.count( aName ) )
183  return m_color_settings.at( aName );
184 
185  COLOR_SETTINGS* ret = nullptr;
186 
187  if( !aName.empty() )
188  ret = loadColorSettingsByName( aName );
189 
190  // This had better work
191  if( !ret )
192  ret = m_color_settings.at( "_builtin_default" );
193 
194  return ret;
195 }
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...

References loadColorSettingsByName(), and m_color_settings.

Referenced by PL_EDITOR_FRAME::CommonSettingsChanged(), DIALOG_EXPORT_SVG::CreateSVGFile(), SYMBOL_EDIT_FRAME::GetColorSettings(), SCH_BASE_FRAME::GetColorSettings(), 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(), and PANEL_SYM_COLOR_SETTINGS::TransferDataFromWindow().

◆ GetColorSettingsList()

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

Definition at line 136 of file settings_manager.h.

137  {
138  std::vector<COLOR_SETTINGS*> ret;
139 
140  for( const std::pair<const wxString, COLOR_SETTINGS*>& entry : m_color_settings )
141  ret.push_back( entry.second );
142 
143  std::sort( ret.begin(), ret.end(), []( COLOR_SETTINGS* a, COLOR_SETTINGS* b )
144  {
145  return a->GetName() < b->GetName();
146  } );
147 
148  return ret;
149  }
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.

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

619 {
620  wxFileName path;
621 
622  path.AssignDir( GetUserSettingsPath() );
623  path.AppendDir( "colors" );
624 
625  if( !path.DirExists() )
626  {
627  if( !wxMkdir( path.GetPath() ) )
628  {
629  wxLogTrace( traceSettings,
630  "GetColorSettingsPath(): Path %s missing and could not be created!",
631  path.GetPath() );
632  }
633  }
634 
635  return path.GetPath();
636 }
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 180 of file settings_manager.h.

180 { return m_common_settings; }
COMMON_SETTINGS * m_common_settings

References m_common_settings.

Referenced by SCH_EDIT_FRAME::doAutoSave(), 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 276 of file settings_manager.cpp.

277 {
278  if( !m_color_settings.count( "user" ) )
279  {
280  registerColorSettings( wxT( "user" ) );
281  m_color_settings.at( "user" )->SetName( wxT( "User" ) );
282  Save( m_color_settings.at( "user" ) );
283  }
284 
285  return m_color_settings.at( "user" );
286 }
void registerColorSettings(const wxString &aFilename)
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings

References m_color_settings, registerColorSettings(), and Save().

◆ GetOpenProjects()

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

Definition at line 876 of file settings_manager.cpp.

877 {
878  std::vector<wxString> ret;
879 
880  for( const std::pair<const wxString, PROJECT*>& pair : m_projects )
881  ret.emplace_back( pair.first );
882 
883  return ret;
884 }
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 354 of file settings_manager.cpp.

355 {
356  wxASSERT( aSettings );
357 
358  switch( aSettings->GetLocation() )
359  {
360  case SETTINGS_LOC::USER:
361  return GetUserSettingsPath();
362 
364  return Prj().GetProjectPath();
365 
367  return GetColorSettingsPath();
368 
369  case SETTINGS_LOC::NONE:
370  return "";
371 
372  default:
373  wxASSERT_MSG( false, "Unknown settings location!" );
374  }
375 
376  return "";
377 }
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:123
The color scheme directory (e.g. ~/.config/kicad/colors/)
The settings directory inside a project folder.
SETTINGS_LOC GetLocation() const
Definition: json_settings.h:72
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)

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

510 {
511  wxASSERT( aPaths );
512 
513  aPaths->clear();
514 
515  wxDir dir;
516  std::vector<wxFileName> base_paths;
517 
518  base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false ), "" ) );
519 
520  // If the env override is set, also check the default paths
521  if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), nullptr ) )
522  base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false, false ), "" ) );
523 
524 #ifdef __WXGTK__
525  // When running inside FlatPak, KIPLATFORM::ENV::GetUserConfigPath() will return a sandboxed
526  // path. In case the user wants to move from non-FlatPak KiCad to FlatPak KiCad, let's add our
527  // best guess as to the non-FlatPak config path. Unfortunately FlatPak also hides the host
528  // XDG_CONFIG_HOME, so if the user customizes their config path, they will have to browse
529  // for it.
530  {
531  wxFileName wxGtkPath;
532  wxGtkPath.AssignDir( "~/.config/kicad" );
533  wxGtkPath.MakeAbsolute();
534  base_paths.emplace_back( wxGtkPath.GetPath() );
535 
536  // We also want to pick up regular flatpak if we are nightly
537  wxGtkPath.AssignDir( "~/.var/app/org.kicad.KiCad/config/kicad" );
538  wxGtkPath.MakeAbsolute();
539  base_paths.emplace_back( wxGtkPath.GetPath() );
540  }
541 #endif
542 
543  wxString subdir;
544  std::string mine = GetSettingsVersion();
545 
546  auto check_dir = [&] ( const wxString& aSubDir )
547  {
548  // Only older versions are valid for migration
549  if( compareVersions( aSubDir.ToStdString(), mine ) <= 0 )
550  {
551  wxString sub_path = dir.GetNameWithSep() + aSubDir;
552 
553  if( IsSettingsPathValid( sub_path ) )
554  {
555  aPaths->push_back( sub_path );
556  wxLogTrace( traceSettings, "GetPreviousVersionName: %s is valid", sub_path );
557  }
558  }
559  };
560 
561  std::set<wxString> checkedPaths;
562 
563  for( auto base_path : base_paths )
564  {
565  if( checkedPaths.count( base_path.GetFullPath() ) )
566  continue;
567 
568  checkedPaths.insert( base_path.GetFullPath() );
569 
570  if( !dir.Open( base_path.GetFullPath() ) )
571  {
572  wxLogTrace( traceSettings, "GetPreviousVersionName: could not open base path %s",
573  base_path.GetFullPath() );
574  continue;
575  }
576 
577  wxLogTrace( traceSettings, "GetPreviousVersionName: checking base path %s",
578  base_path.GetFullPath() );
579 
580  if( dir.GetFirst( &subdir, wxEmptyString, wxDIR_DIRS ) )
581  {
582  if( subdir != mine )
583  check_dir( subdir );
584 
585  while( dir.GetNext( &subdir ) )
586  {
587  if( subdir != mine )
588  check_dir( subdir );
589  }
590  }
591 
592  // If we didn't find one yet, check for legacy settings without a version directory
593  if( IsSettingsPathValid( dir.GetNameWithSep() ) )
594  {
595  wxLogTrace( traceSettings,
596  "GetPreviousVersionName: root path %s is valid", dir.GetName() );
597  aPaths->push_back( dir.GetName() );
598  }
599  }
600 
601  return aPaths->size() > 0;
602 }
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 867 of file settings_manager.cpp.

868 {
869  if( m_projects.count( aFullPath ) )
870  return m_projects.at( aFullPath );
871 
872  return nullptr;
873 }
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 1006 of file settings_manager.cpp.

1007 {
1009 }
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:123
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:129

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

677 {
678  // CMake computes the major.minor string for us.
679  return GetMajorMinorVersion().ToStdString();
680 }
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 639 of file settings_manager.cpp.

640 {
641  static wxString user_settings_path;
642 
643  if( user_settings_path.empty() )
644  user_settings_path = calculateUserSettingsPath();
645 
646  return user_settings_path;
647 }
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(), ReadHotKeyConfig(), ReadLegacyHotkeyConfigFile(), and WriteHotKeyConfig().

◆ IsOK()

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

Definition at line 47 of file settings_manager.h.

47 { 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 861 of file settings_manager.cpp.

862 {
863  return !m_projects.empty();
864 }
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 605 of file settings_manager.cpp.

606 {
607  wxFileName test( aPath, "kicad_common" );
608 
609  if( test.Exists() )
610  return true;
611 
612  test.SetExt( "json" );
613 
614  return test.Exists();
615 }

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

◆ Load() [1/2]

void SETTINGS_MANAGER::Load ( )

Definition at line 101 of file settings_manager.cpp.

102 {
103  // TODO(JE) We should check for dirty settings here and write them if so, because
104  // Load() could be called late in the application lifecycle
105 
106  for( auto&& settings : m_settings )
107  settings->LoadFromFile( GetPathForSettingsFile( settings.get() ) );
108 }
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 111 of file settings_manager.cpp.

112 {
113  auto it = std::find_if( m_settings.begin(), m_settings.end(),
114  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
115  {
116  return aPtr.get() == aSettings;
117  } );
118 
119  if( it != m_settings.end() )
120  ( *it )->LoadFromFile( GetPathForSettingsFile( it->get() ) );
121 }
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 289 of file settings_manager.cpp.

290 {
291  // Create the built-in color settings
293  {
294  m_color_settings[settings->GetFilename()] =
295  static_cast<COLOR_SETTINGS*>( RegisterSettings( settings, false ) );
296  }
297 
298  // Search for and load any other settings
299  COLOR_SETTINGS_LOADER loader( [&]( const wxString& aFilename )
300  {
301  registerColorSettings( aFilename );
302  } );
303 
304  wxDir colors_dir( GetColorSettingsPath() );
305 
306  if( colors_dir.IsOpened() )
307  colors_dir.Traverse( loader );
308 }
static std::vector< COLOR_SETTINGS * > CreateBuiltinColorSettings()
Constructs and returns a list of color settings objects based on the built-in color themes.
void registerColorSettings(const wxString &aFilename)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *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 COLOR_SETTINGS::CreateBuiltinColorSettings(), GetColorSettingsPath(), m_color_settings, registerColorSettings(), and RegisterSettings().

Referenced by ReloadColorSettings(), and SETTINGS_MANAGER().

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

199 {
200  wxLogTrace( traceSettings, "Attempting to load color theme %s", aName );
201 
202  wxFileName fn( GetColorSettingsPath(), aName, "json" );
203 
204  if( !fn.IsOk() || !fn.Exists() )
205  {
206  wxLogTrace( traceSettings, "Theme file %s.json not found, falling back to user", aName );
207  return nullptr;
208  }
209 
210  auto cs = static_cast<COLOR_SETTINGS*>(
211  RegisterSettings( new COLOR_SETTINGS( aName.ToStdString() ) ) );
212 
213  if( cs->GetFilename() != aName.ToStdString() )
214  {
215  wxLogTrace( traceSettings, "Warning: stored filename is actually %s, ", cs->GetFilename() );
216  }
217 
218  m_color_settings[aName] = cs;
219 
220  return cs;
221 }
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored; creating it if missing (normally .
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *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...
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.

References GetColorSettingsPath(), 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 746 of file settings_manager.cpp.

747 {
748  // Normalize path to new format even if migrating from a legacy file
749  wxFileName path( aFullPath );
750 
751  if( path.GetExt() == LegacyProjectFileExtension )
752  path.SetExt( ProjectFileExtension );
753 
754  wxString fullPath = path.GetFullPath();
755 
756  // If already loaded, we are all set. This might be called more than once over a project's
757  // lifetime in case the project is first loaded by the KiCad manager and then eeschema or
758  // pcbnew try to load it again when they are launched.
759  if( m_projects.count( fullPath ) )
760  return true;
761 
762  bool readOnly = false;
763  std::unique_ptr<wxSingleInstanceChecker> lockFile = ::LockFile( fullPath );
764 
765  if( !lockFile )
766  {
767  wxLogTrace( traceSettings, "Project %s is locked; opening read-only", fullPath );
768  readOnly = true;
769  }
770 
771  // No MDI yet
772  if( aSetActive && !m_projects.empty() )
773  {
774  PROJECT* oldProject = m_projects.begin()->second;
775  unloadProjectFile( oldProject, false );
776  m_projects.erase( m_projects.begin() );
777  }
778 
779  wxLogTrace( traceSettings, "Load project %s", fullPath );
780 
781  std::unique_ptr<PROJECT> project = std::make_unique<PROJECT>();
782  project->setProjectFullName( fullPath );
783 
784  bool success = loadProjectFile( *project );
785 
786  if( success )
787  {
788  project->SetReadOnly( readOnly || project->GetProjectFile().IsReadOnly() );
789 
790  if( lockFile )
791  m_project_lock.reset( lockFile.release() );
792  }
793 
794  m_projects_list.push_back( std::move( project ) );
795  m_projects[fullPath] = m_projects_list.back().get();
796 
797  wxString fn( path.GetName() );
798 
799  PROJECT_LOCAL_SETTINGS* settings = new PROJECT_LOCAL_SETTINGS( m_projects[fullPath], fn );
800 
801  if( aSetActive )
802  settings = static_cast<PROJECT_LOCAL_SETTINGS*>( RegisterSettings( settings ) );
803 
804  m_projects[fullPath]->setLocalSettings( settings );
805 
806  if( aSetActive && m_kiway )
808 
809  return success;
810 }
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)
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:550
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.
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
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(), 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 951 of file settings_manager.cpp.

952 {
953  wxFileName fullFn( aProject.GetProjectFullName() );
954  wxString fn( fullFn.GetName() );
955 
956  PROJECT_FILE* file = static_cast<PROJECT_FILE*>( RegisterSettings( new PROJECT_FILE( fn ),
957  false ) );
958 
959  m_project_files[aProject.GetProjectFullName()] = file;
960 
961  aProject.setProjectFile( file );
962  file->SetProject( &aProject );
963 
964  wxString path( fullFn.GetPath() );
965 
966  return file->LoadFromFile( path );
967 }
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:117
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
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 452 of file settings_manager.cpp.

453 {
454  if( m_headless )
455  {
456  wxLogTrace( traceSettings, "Settings migration not checked; running headless" );
457  return false;
458  }
459 
460  wxFileName path( GetUserSettingsPath(), "" );
461  wxLogTrace( traceSettings, "Using settings path %s", path.GetFullPath() );
462 
463  if( path.DirExists() )
464  {
465  wxFileName common = path;
466  common.SetName( "kicad_common" );
467  common.SetExt( "json" );
468 
469  if( common.Exists() )
470  {
471  wxLogTrace( traceSettings, "Path exists and has a kicad_common, continuing!" );
472  return true;
473  }
474  }
475 
476  // Now we have an empty path, let's figure out what to put in it
477  DIALOG_MIGRATE_SETTINGS dlg( this );
478 
479  if( dlg.ShowModal() != wxID_OK )
480  {
481  wxLogTrace( traceSettings, "Migration dialog canceled; exiting" );
482  return false;
483  }
484 
485  if( !path.DirExists() )
486  {
487  wxLogTrace( traceSettings, "Path didn't exist; creating it" );
488  path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
489  }
490 
491  if( m_migration_source.IsEmpty() )
492  {
493  wxLogTrace( traceSettings, "No migration source given; starting with defaults" );
494  return true;
495  }
496 
498  wxDir source_dir( m_migration_source );
499 
500  source_dir.Traverse( traverser );
501 
502  if( !traverser.GetErrors().empty() )
503  DisplayErrorMessage( nullptr, traverser.GetErrors() );
504 
505  return true;
506 }
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:265
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 854 of file settings_manager.cpp.

855 {
856  // No MDI yet: First project in the list is the active project
857  return *m_projects.begin()->second;
858 }
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.

References m_projects.

Referenced by BackupProject(), PCB_EDIT_FRAME::Files_io_from_id(), GetPathForSettingsFile(), GetProjectBackupsPath(), 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()

void SETTINGS_MANAGER::registerColorSettings ( const wxString &  aFilename)
private

Definition at line 254 of file settings_manager.cpp.

255 {
256  if( m_color_settings.count( aFilename ) )
257  return;
258 
259  m_color_settings[aFilename] = static_cast<COLOR_SETTINGS*>(
260  RegisterSettings( new COLOR_SETTINGS( aFilename ) ) );
261 }
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *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(), GetMigratedColorSettings(), and loadAllColorSettings().

◆ RegisterSettings()

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

Takes ownership of the pointer passed in.

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

Definition at line 85 of file settings_manager.cpp.

86 {
87  std::unique_ptr<JSON_SETTINGS> ptr( aSettings );
88 
89  ptr->SetManager( this );
90 
91  wxLogTrace( traceSettings, "Registered new settings object <%s>", ptr->GetFullFilename() );
92 
93  if( aLoadNow )
94  ptr->LoadFromFile( GetPathForSettingsFile( ptr.get() ) );
95 
96  m_settings.push_back( std::move( ptr ) );
97  return m_settings.back().get();
98 }
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 GetAppSettings(), loadAllColorSettings(), loadColorSettingsByName(), LoadProject(), loadProjectFile(), PCBCALC::IFACE::OnKifaceStart(), PGE::IFACE::OnKifaceStart(), CV::IFACE::OnKifaceStart(), GERBV::IFACE::OnKifaceStart(), PCB::IFACE::OnKifaceStart(), SCH::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 311 of file settings_manager.cpp.

312 {
313  m_color_settings.clear();
315 }
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 124 of file settings_manager.cpp.

125 {
126  for( auto&& settings : m_settings )
127  {
128  // Never automatically save color settings, caller should use SaveColorSettings
129  if( dynamic_cast<COLOR_SETTINGS*>( settings.get() ) )
130  continue;
131 
132  settings->SaveToFile( GetPathForSettingsFile( settings.get() ) );
133  }
134 }
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 137 of file settings_manager.cpp.

138 {
139  auto it = std::find_if( m_settings.begin(), m_settings.end(),
140  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
141  {
142  return aPtr.get() == aSettings;
143  } );
144 
145  if( it != m_settings.end() )
146  {
147  wxLogTrace( traceSettings, "Saving %s", ( *it )->GetFullFilename() );
148  ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
149  }
150 }
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 preform 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 318 of file settings_manager.cpp.

319 {
320  // The passed settings should already be managed
321  wxASSERT( std::find_if( m_color_settings.begin(), m_color_settings.end(),
322  [aSettings] ( const std::pair<wxString, COLOR_SETTINGS*>& el )
323  {
324  return el.second->GetFilename() == aSettings->GetFilename();
325  }
326  ) != m_color_settings.end() );
327 
328  nlohmann::json::json_pointer ptr = JSON_SETTINGS::PointerFromString( aNamespace );
329 
330  if( !aSettings->Store() )
331  {
332  wxLogTrace( traceSettings, "Color scheme %s not modified; skipping save",
333  aSettings->GetFilename(), aNamespace );
334  return;
335  }
336 
337  wxASSERT( aSettings->contains( ptr ) );
338 
339  wxLogTrace( traceSettings, "Saving color scheme %s, preserving %s", aSettings->GetFilename(),
340  aNamespace );
341 
342  nlohmann::json backup = aSettings->at( ptr );
343  wxString path = GetColorSettingsPath();
344 
345  aSettings->LoadFromFile( path );
346 
347  ( *aSettings )[ptr].update( backup );
348  aSettings->Load();
349 
350  aSettings->SaveToFile( path, true );
351 }
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
wxString GetFilename() const
Definition: json_settings.h:66
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
nlohmann::json json
Definition: gerbview.cpp:41
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
const wxChar *const traceSettings
Flag to enable debug output of settings operations and management.
static nlohmann::json::json_pointer PointerFromString(std::string aPath)
Builds a JSON pointer based on a given string.
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.

References GetColorSettingsPath(), JSON_SETTINGS::GetFilename(), JSON_SETTINGS::Load(), JSON_SETTINGS::LoadFromFile(), m_color_settings, path, JSON_SETTINGS::PointerFromString(), 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 887 of file settings_manager.cpp.

888 {
889  wxString path = aFullPath;
890 
891  if( path.empty() )
893 
894  // TODO: refactor for MDI
895  if( Prj().IsReadOnly() )
896  return false;
897 
898  if( !m_project_files.count( path ) )
899  return false;
900 
902  wxString projectPath = GetPathForSettingsFile( project );
903 
904  project->SaveToFile( projectPath );
905  Prj().GetLocalSettings().SaveToFile( projectPath );
906 
907  return true;
908 }
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:117
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(), SaveBoard(), 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)

Parameters
aFullPathis the full filename to set for the project

Definition at line 911 of file settings_manager.cpp.

912 {
913  wxString oldName = Prj().GetProjectFullName();
914 
915  // Changing this will cause UnloadProject to not save over the "old" project when loading below
916  Prj().setProjectFullName( aFullPath );
917 
918  wxFileName fn( aFullPath );
919 
920  PROJECT_FILE* project = m_project_files.at( oldName );
921  project->SetFilename( fn.GetName() );
922  project->SaveToFile( fn.GetPath() );
923 
924  Prj().GetLocalSettings().SetFilename( fn.GetName() );
925  Prj().GetLocalSettings().SaveToFile( fn.GetPath() );
926 
927  m_project_files[fn.GetFullPath()] = project;
928  m_project_files.erase( oldName );
929 
930  m_projects[fn.GetFullPath()] = m_projects[oldName];
931  m_projects.erase( oldName );
932 }
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:117
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:85
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:70

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

Referenced by SCH_EDIT_FRAME::Save_File(), and PCB_EDIT_FRAME::SavePcbFile().

◆ SaveProjectCopy()

void SETTINGS_MANAGER::SaveProjectCopy ( const wxString &  aFullPath)

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

Definition at line 935 of file settings_manager.cpp.

936 {
937  PROJECT_FILE* project = m_project_files.at( Prj().GetProjectFullName() );
938  wxString oldName = project->GetFilename();
939  wxFileName fn( aFullPath );
940 
941  project->SetFilename( fn.GetName() );
942  project->SaveToFile( fn.GetPath() );
943  project->SetFilename( oldName );
944 
945  Prj().GetLocalSettings().SetFilename( fn.GetName() );
946  Prj().GetLocalSettings().SaveToFile( fn.GetPath() );
947  Prj().GetLocalSettings().SetFilename( oldName );
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
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:70

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

Referenced by PCB_EDIT_FRAME::SavePcbCopy().

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

54 { 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 210 of file settings_manager.h.

210 { 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 208 of file settings_manager.h.

208 { 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 1079 of file settings_manager.cpp.

1080 {
1082 
1083  if( !settings.enabled )
1084  return true;
1085 
1086  wxString prefix = Prj().GetProjectName() + '-';
1087 
1088  auto modTime =
1089  [&prefix]( const wxString& aFile )
1090  {
1091  wxDateTime dt;
1092  wxString fn( wxFileName( aFile ).GetName() );
1093  fn.Replace( prefix, "" );
1094  dt.ParseFormat( fn, backupDateTimeFormat );
1095  return dt;
1096  };
1097 
1098  wxFileName projectPath( Prj().GetProjectPath() );
1099 
1100  // Skip backup if project path isn't valid or writeable
1101  if( !projectPath.IsOk() || !projectPath.Exists() || !projectPath.IsDirWritable() )
1102  return true;
1103 
1104  wxString backupPath = GetProjectBackupsPath();
1105 
1106  if( !wxDirExists( backupPath ) )
1107  {
1108  wxLogTrace( traceSettings, "Backup path %s doesn't exist, creating it", backupPath );
1109 
1110  if( !wxMkdir( backupPath ) )
1111  {
1112  wxLogTrace( traceSettings, "Could not create backups path! Skipping backup" );
1113  return false;
1114  }
1115  }
1116 
1117  wxDir dir( backupPath );
1118 
1119  if( !dir.IsOpened() )
1120  {
1121  wxLogTrace( traceSettings, "Could not open project backups path %s", dir.GetName() );
1122  return false;
1123  }
1124 
1125  std::vector<wxString> files;
1126 
1127  VECTOR_INSERT_TRAVERSER traverser( files,
1128  [&modTime]( const wxString& aFile )
1129  {
1130  return modTime( aFile ).IsValid();
1131  } );
1132 
1133  dir.Traverse( traverser, wxT( "*.zip" ) );
1134 
1135  // Sort newest-first
1136  std::sort( files.begin(), files.end(),
1137  [&]( const wxString& aFirst, const wxString& aSecond ) -> bool
1138  {
1139  wxDateTime first = modTime( aFirst );
1140  wxDateTime second = modTime( aSecond );
1141 
1142  return first.GetTicks() > second.GetTicks();
1143  } );
1144 
1145  // Do we even need to back up?
1146  if( !files.empty() )
1147  {
1148  wxDateTime lastTime = modTime( files[0] );
1149 
1150  if( lastTime.IsValid() )
1151  {
1152  wxTimeSpan delta = wxDateTime::Now() - modTime( files[0] );
1153 
1154  if( delta.IsShorterThan( wxTimeSpan::Seconds( settings.min_interval ) ) )
1155  return true;
1156  }
1157  }
1158 
1159  // Now that we know a backup is needed, apply the retention policy
1160 
1161  // Step 1: if we're over the total file limit, remove the oldest
1162  if( !files.empty() && settings.limit_total_files > 0 )
1163  {
1164  while( files.size() > static_cast<size_t>( settings.limit_total_files ) )
1165  {
1166  wxRemoveFile( files.back() );
1167  files.pop_back();
1168  }
1169  }
1170 
1171  // Step 2: Stay under the total size limit
1172  if( settings.limit_total_size > 0 )
1173  {
1174  wxULongLong totalSize = 0;
1175 
1176  for( const wxString& file : files )
1177  totalSize += wxFileName::GetSize( file );
1178 
1179  while( !files.empty() && totalSize > static_cast<wxULongLong>( settings.limit_total_size ) )
1180  {
1181  totalSize -= wxFileName::GetSize( files.back() );
1182  wxRemoveFile( files.back() );
1183  files.pop_back();
1184  }
1185  }
1186 
1187  // Step 3: Stay under the daily limit
1188  if( settings.limit_daily_files > 0 && files.size() > 1 )
1189  {
1190  wxDateTime day = modTime( files[0] );
1191  int num = 1;
1192 
1193  wxASSERT( day.IsValid() );
1194 
1195  std::vector<wxString> filesToDelete;
1196 
1197  for( size_t i = 1; i < files.size(); i++ )
1198  {
1199  wxDateTime dt = modTime( files[i] );
1200 
1201  if( dt.IsSameDate( day ) )
1202  {
1203  num++;
1204 
1205  if( num > settings.limit_daily_files )
1206  filesToDelete.emplace_back( files[i] );
1207  }
1208  else
1209  {
1210  day = dt;
1211  num = 1;
1212  }
1213  }
1214 
1215  for( const wxString& file : filesToDelete )
1216  wxRemoveFile( file );
1217  }
1218 
1219  return BackupProject( aReporter );
1220 }
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.
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:129
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(), 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 813 of file settings_manager.cpp.

814 {
815  if( !aProject || !m_projects.count( aProject->GetProjectFullName() ) )
816  return false;
817 
818  if( !unloadProjectFile( aProject, aSave ) )
819  return false;
820 
821  wxString projectPath = aProject->GetProjectFullName();
822  wxLogTrace( traceSettings, "Unload project %s", projectPath );
823 
824  PROJECT* toRemove = m_projects.at( projectPath );
825  auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
826  [&]( const std::unique_ptr<PROJECT>& ptr )
827  {
828  return ptr.get() == toRemove;
829  } );
830 
831  wxASSERT( it != m_projects_list.end() );
832  m_projects_list.erase( it );
833 
834  m_projects.erase( projectPath );
835 
836  // Immediately reload a null project; this is required until the rest of the application
837  // is refactored to not assume that Prj() always works
838  if( m_projects.empty() )
839  LoadProject( "" );
840 
841  // Remove the reference in the environment to the previous project
842  wxSetEnv( PROJECT_VAR_NAME, "" );
843 
844  // Release lock on the file, in case we had one
845  m_project_lock = nullptr;
846 
847  if( m_kiway )
849 
850  return true;
851 }
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:550
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:117
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 970 of file settings_manager.cpp.

971 {
972  if( !aProject )
973  return false;
974 
975  wxString name = aProject->GetProjectFullName();
976 
977  if( !m_project_files.count( name ) )
978  return false;
979 
981 
982  auto it = std::find_if( m_settings.begin(), m_settings.end(),
983  [&file]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
984  {
985  return aPtr.get() == file;
986  } );
987 
988  if( it != m_settings.end() )
989  {
990  wxString projectPath = GetPathForSettingsFile( it->get() );
991 
992  FlushAndRelease( &aProject->GetLocalSettings(), aSave );
993 
994  if( aSave )
995  ( *it )->SaveToFile( projectPath );
996 
997  m_settings.erase( it );
998  }
999 
1000  m_project_files.erase( name );
1001 
1002  return true;
1003 }
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:117
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
const char * name
Definition: DXF_plotter.cpp:59
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 437 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 412 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 415 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 402 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 405 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 420 of file settings_manager.h.

Referenced by MigrateIfNeeded(), and SetMigrateLibraryTables().

◆ m_migration_source

wxString SETTINGS_MANAGER::m_migration_source
private

Definition at line 417 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 423 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 432 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 435 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 429 of file settings_manager.h.

Referenced by GetOpenProjects(), GetProject(), IsProjectOpen(), LoadProject(), Prj(), 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 426 of file settings_manager.h.

Referenced by LoadProject(), 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: