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...
 
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...
 
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...
 
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 (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
 
COMMON_SETTINGSm_common_settings
 
wxString m_migration_source
 
bool m_ok
 True if settings loaded successfully at construction. More...
 
std::map< wxString, std::unique_ptr< 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...
 

Static Private Attributes

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

Detailed Description

Definition at line 35 of file settings_manager.h.

Constructor & Destructor Documentation

◆ SETTINGS_MANAGER()

SETTINGS_MANAGER::SETTINGS_MANAGER ( bool  aHeadless = false)

Definition at line 49 of file settings_manager.cpp.

49  :
50  m_headless( aHeadless ),
51  m_kiway( nullptr ),
52  m_common_settings( nullptr ),
54 {
55  // Check if the settings directory already exists, and if not, perform a migration if possible
56  if( !MigrateIfNeeded() )
57  {
58  m_ok = false;
59  return;
60  }
61 
62  m_ok = true;
63 
64  // create the common settings shared by all applications. Not loaded immediately
66  static_cast<COMMON_SETTINGS*>( RegisterSettings( new COMMON_SETTINGS, false ) );
67 
69 }
KIWAY * m_kiway
The kiway this settings manager interacts with.
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.
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.
COMMON_SETTINGS * m_common_settings

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

◆ ~SETTINGS_MANAGER()

SETTINGS_MANAGER::~SETTINGS_MANAGER ( )

Definition at line 71 of file settings_manager.cpp.

72 {
73  m_settings.clear();
74  m_color_settings.clear();
75  m_projects.clear();
76 }
std::map< wxString, std::unique_ptr< 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 254 of file settings_manager.cpp.

255 {
256  wxString filename = aFilename;
257 
258  if( filename.EndsWith( wxT( ".json" ) ) )
259  filename = filename.BeforeLast( '.' );
260 
261  registerColorSettings( filename );
262  return m_color_settings[filename];
263 }
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 872 of file settings_manager.cpp.

873 {
874  wxDateTime timestamp = wxDateTime::Now();
875 
876  wxString fileName = wxString::Format( wxT( "%s-%s" ), Prj().GetProjectName(),
877  timestamp.Format( backupDateTimeFormat ) );
878 
879  wxFileName target;
880  target.SetPath( GetProjectBackupsPath() );
881  target.SetName( fileName );
882  target.SetExt( ArchiveFileExtension );
883 
884  wxDir dir( target.GetPath() );
885 
886  if( !target.DirExists() && !wxMkdir( target.GetPath() ) )
887  {
888  wxLogTrace( traceSettings, "Could not create project backup path %s", target.GetPath() );
889  return false;
890  }
891 
892  if( !target.IsDirWritable() )
893  {
894  wxLogTrace( traceSettings, "Backup directory %s is not writeable", target.GetPath() );
895  return false;
896  }
897 
898  wxLogTrace( traceSettings, "Backing up project to %s", target.GetPath() );
899 
900  PROJECT_ARCHIVER archiver;
901 
902  return archiver.Archive( Prj().GetProjectPath(), target.GetFullPath(), aReporter );
903 }
static wxString backupDateTimeFormat
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
bool Archive(const wxString &aSrcDir, const wxString &aDestFile, REPORTER &aReporter, bool aVerbose=true)
Creates an archive of the project.
wxString GetProjectBackupsPath() const
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, CPTREE &aTree)
Function Format outputs a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:201
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 566 of file settings_manager.cpp.

567 {
568  wxFileName cfgpath;
569 
570  // http://docs.wxwidgets.org/3.0/classwx_standard_paths.html#a7c7cf595d94d29147360d031647476b0
571  cfgpath.AssignDir( wxStandardPaths::Get().GetUserConfigDir() );
572 
573  // GetUserConfigDir() does not default to ~/.config which is the current standard
574  // configuration file location on Linux. This has been fixed in later versions of wxWidgets.
575 #if !defined( __WXMSW__ ) && !defined( __WXMAC__ )
576  wxArrayString dirs = cfgpath.GetDirs();
577 
578  if( dirs.Last() != ".config" )
579  cfgpath.AppendDir( ".config" );
580 #endif
581 
582  wxString envstr;
583 
584  // This shouldn't cause any issues on Windows or MacOS.
585  if( wxGetEnv( wxT( "XDG_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
586  {
587  // Override the assignment above with XDG_CONFIG_HOME
588  cfgpath.AssignDir( envstr );
589  }
590 
591  cfgpath.AppendDir( TO_STR( KICAD_CONFIG_DIR ) );
592 
593  // Use KICAD_CONFIG_HOME to allow the user to force a specific configuration path.
594  if( aUseEnv && wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), &envstr ) && !envstr.IsEmpty() )
595  {
596  // Override the assignment above with KICAD_CONFIG_HOME
597  cfgpath.AssignDir( envstr );
598  }
599 
600  if( aIncludeVer )
601  cfgpath.AppendDir( GetSettingsVersion() );
602 
603  return cfgpath.GetPath();
604 }
#define TO_STR(x)
Definition: macros.h:108
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(), 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 614 of file settings_manager.cpp.

615 {
616  int a_maj = 0;
617  int a_min = 0;
618  int b_maj = 0;
619  int b_min = 0;
620 
621  if( !extractVersion( aFirst, &a_maj, &a_min ) || !extractVersion( aSecond, &b_maj, &b_min ) )
622  {
623  wxLogTrace( traceSettings, "compareSettingsVersions: bad input (%s, %s)", aFirst, aSecond );
624  return -1;
625  }
626 
627  if( a_maj < b_maj )
628  {
629  return -1;
630  }
631  else if( a_maj > b_maj )
632  {
633  return 1;
634  }
635  else
636  {
637  if( a_min < b_min )
638  {
639  return -1;
640  }
641  else if( a_min > b_min )
642  {
643  return 1;
644  }
645  else
646  {
647  return 0;
648  }
649  }
650 }
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 653 of file settings_manager.cpp.

654 {
655  std::regex re_version( "(\\d+)\\.(\\d+)" );
656  std::smatch match;
657 
658  if( std::regex_match( aVersionString, match, re_version ) )
659  {
660  try
661  {
662  *aMajor = std::stoi( match[1].str() );
663  *aMinor = std::stoi( match[2].str() );
664  }
665  catch( ... )
666  {
667  return false;
668  }
669 
670  return true;
671  }
672 
673  return false;
674 }

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

148 {
149  auto it = std::find_if( m_settings.begin(), m_settings.end(),
150  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
151  {
152  return aPtr.get() == aSettings;
153  } );
154 
155  if( it != m_settings.end() )
156  {
157  wxLogTrace( traceSettings, "Flush and release %s", ( *it )->GetFullFilename() );
158 
159  if( aSave )
160  ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
161 
162  m_settings.erase( it );
163  }
164 }
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 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 86 of file settings_manager.h.

87  {
88  AppSettings* ret = nullptr;
89 
90  auto it = std::find_if( m_settings.begin(), m_settings.end(),
91  []( const std::unique_ptr<JSON_SETTINGS>& aSettings )
92  {
93  return dynamic_cast<AppSettings*>( aSettings.get() );
94  } );
95 
96  if( it != m_settings.end() )
97  {
98  ret = dynamic_cast<AppSettings*>( it->get() );
99  }
100  else
101  {
102  try
103  {
104  ret = static_cast<AppSettings*>( RegisterSettings( new AppSettings, aLoadNow ) );
105  }
106  catch( ... )
107  {
108  wxLogTrace( traceSettings, "Unable to create application settings object" );
109  }
110 
111  }
112 
113  return ret;
114  }
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_settings, RegisterSettings(), and traceSettings.

Referenced by PL_EDITOR_FRAME::CommonSettingsChanged(), DIALOG_EXPORT_SVG::CreateSVGFile(), LIB_EDIT_FRAME::GetColorSettings(), LIB_PIN::LIB_PIN(), PANEL_EESCHEMA_COLOR_SETTINGS::PANEL_EESCHEMA_COLOR_SETTINGS(), PANEL_MODEDIT_COLOR_SETTINGS::PANEL_MODEDIT_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_LIBEDIT_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_MODEDIT_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 167 of file settings_manager.cpp.

168 {
169  if( m_color_settings.count( aName ) )
170  return m_color_settings.at( aName );
171 
172  COLOR_SETTINGS* ret = nullptr;
173 
174  if( !aName.empty() )
175  ret = loadColorSettingsByName( aName );
176 
177  // This had better work
178  if( !ret )
179  ret = m_color_settings.at( "user" );
180 
181  return ret;
182 }
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(), LIB_EDIT_FRAME::GetColorSettings(), PANEL_EESCHEMA_COLOR_SETTINGS::PANEL_EESCHEMA_COLOR_SETTINGS(), PANEL_MODEDIT_COLOR_SETTINGS::PANEL_MODEDIT_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_LIBEDIT_COLOR_SETTINGS::TransferDataFromWindow().

◆ GetColorSettingsList()

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

Definition at line 125 of file settings_manager.h.

126  {
127  std::vector<COLOR_SETTINGS*> ret;
128 
129  for( const std::pair<const wxString, COLOR_SETTINGS*>& entry : m_color_settings )
130  ret.push_back( entry.second );
131 
132  std::sort( ret.begin(), ret.end(), []( COLOR_SETTINGS* a, COLOR_SETTINGS* b )
133  {
134  return a->GetName() < b->GetName();
135  } );
136 
137  return ret;
138  }
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 (normally .

/colors/ under the user settings path)

Definition at line 544 of file settings_manager.cpp.

545 {
546  wxFileName path;
547 
548  path.AssignDir( GetUserSettingsPath() );
549  path.AppendDir( "colors" );
550 
551  return path.GetPath();
552 }
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.

References GetUserSettingsPath().

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

162 { return m_common_settings; }
COMMON_SETTINGS * m_common_settings

References m_common_settings.

Referenced by SCH_EDIT_FRAME::doAutoSave(), PGM_BASE::GetCommonSettings(), and TriggerBackupIfNeeded().

◆ GetOpenProjects()

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

Definition at line 773 of file settings_manager.cpp.

774 {
775  std::vector<wxString> ret;
776 
777  for( const std::pair<const wxString, std::unique_ptr<PROJECT>>& pair : m_projects )
778  ret.emplace_back( pair.first );
779 
780  return ret;
781 }
std::map< wxString, std::unique_ptr< 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 327 of file settings_manager.cpp.

328 {
329  wxASSERT( aSettings );
330 
331  switch( aSettings->GetLocation() )
332  {
333  case SETTINGS_LOC::USER:
334  return GetUserSettingsPath();
335 
337  return Prj().GetProjectPath();
338 
340  return GetColorSettingsPath();
341 
342  case SETTINGS_LOC::NONE:
343  return "";
344 
345  default:
346  wxASSERT_MSG( false, "Unknown settings location!" );
347  }
348 
349  return "";
350 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
VTBL_ENTRY const wxString GetProjectPath() const
Function GetProjectPath returns the full path of the project.
Definition: project.cpp:124
The color scheme directory (e.g. ~/.config/kicad/colors/)
The settings directory inside a project folder.
SETTINGS_LOC GetLocation() const
Definition: json_settings.h:68
No directory prepended, full path in filename (used for PROJECT_FILE)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored (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 467 of file settings_manager.cpp.

468 {
469  wxASSERT( aPaths );
470 
471  aPaths->clear();
472 
473  wxDir dir;
474  std::vector<wxFileName> base_paths;
475 
476  base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false ), "" ) );
477 
478  // If the env override is set, also check the default paths
479  if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), nullptr ) )
480  base_paths.emplace_back( wxFileName( calculateUserSettingsPath( false, false ), "" ) );
481 
482  wxString subdir;
483  std::string mine = GetSettingsVersion();
484 
485  auto check_dir = [&] ( const wxString& aSubDir )
486  {
487  // Only older versions are valid for migration
488  if( compareVersions( aSubDir.ToStdString(), mine ) <= 0 )
489  {
490  wxString sub_path = dir.GetNameWithSep() + aSubDir;
491 
492  if( IsSettingsPathValid( sub_path ) )
493  {
494  aPaths->push_back( sub_path );
495  wxLogTrace( traceSettings, "GetPreviousVersionName: %s is valid", sub_path );
496  }
497  }
498  };
499 
500  for( auto base_path : base_paths )
501  {
502  if( !dir.Open( base_path.GetFullPath() ) )
503  {
504  wxLogTrace( traceSettings, "GetPreviousVersionName: could not open base path %s",
505  base_path.GetFullPath() );
506  continue;
507  }
508 
509  wxLogTrace( traceSettings, "GetPreviousVersionName: checking base path %s",
510  base_path.GetFullPath() );
511 
512  if( dir.GetFirst( &subdir, wxEmptyString, wxDIR_DIRS ) )
513  {
514  if( subdir != mine )
515  check_dir( subdir );
516 
517  while( dir.GetNext( &subdir ) )
518  {
519  if( subdir != mine )
520  check_dir( subdir );
521  }
522  }
523 
524  // If we didn't find one yet, check for legacy settings without a version directory
525  if( IsSettingsPathValid( dir.GetNameWithSep() ) )
526  {
527  wxLogTrace( traceSettings,
528  "GetPreviousVersionName: root path %s is valid", dir.GetName() );
529  aPaths->push_back( dir.GetName() );
530  }
531  }
532 
533  return aPaths->size() > 0;
534 }
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 764 of file settings_manager.cpp.

765 {
766  if( m_projects.count( aFullPath ) )
767  return m_projects.at( aFullPath ).get();
768 
769  return nullptr;
770 }
std::map< wxString, std::unique_ptr< 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 863 of file settings_manager.cpp.

864 {
866 }
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.
VTBL_ENTRY const wxString GetProjectPath() const
Function GetProjectPath returns the full path of the project.
Definition: project.cpp:124
VTBL_ENTRY const wxString GetProjectName() const
Function GetProjectName returns the short name of the project.
Definition: project.cpp:130

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

608 {
609  // CMake computes the major.minor string for us.
610  return GetMajorMinorVersion().ToStdString();
611 }
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.

References GetMajorMinorVersion().

Referenced by calculateUserSettingsPath(), GetPreviousVersionPaths(), 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 555 of file settings_manager.cpp.

556 {
557  static wxString user_settings_path;
558 
559  if( user_settings_path.empty() )
560  user_settings_path = calculateUserSettingsPath();
561 
562  return user_settings_path;
563 }
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(), PyScriptingPath(), ReadHotKeyConfig(), ReadLegacyHotkeyConfigFile(), and WriteHotKeyConfig().

◆ IsOK()

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

Definition at line 45 of file settings_manager.h.

45 { 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 758 of file settings_manager.cpp.

759 {
760  return !m_projects.empty();
761 }
std::map< wxString, std::unique_ptr< PROJECT > > m_projects
Loaded projects, mapped according to project full name.

References m_projects.

Referenced by PCB_BASE_EDIT_FRAME::doCloseWindow().

◆ IsSettingsPathValid()

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

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

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

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

Definition at line 537 of file settings_manager.cpp.

538 {
539  wxFileName test( aPath, "kicad_common" );
540  return test.Exists();
541 }

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

◆ Load() [1/2]

void SETTINGS_MANAGER::Load ( )

Definition at line 95 of file settings_manager.cpp.

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

106 {
107  auto it = std::find_if( m_settings.begin(), m_settings.end(),
108  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
109  {
110  return aPtr.get() == aSettings;
111  } );
112 
113  if( it != m_settings.end() )
114  ( *it )->LoadFromFile( GetPathForSettingsFile( it->get() ) );
115 }
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 266 of file settings_manager.cpp.

267 {
268  // Create the default color settings
269  registerColorSettings( "user" );
270 
271  // Search for and load any other settings
272  COLOR_SETTINGS_LOADER loader( [&]( const wxString& aFilename )
273  {
274  registerColorSettings( aFilename );
275  } );
276 
277  wxDir colors_dir( GetColorSettingsPath() );
278 
279  if( colors_dir.IsOpened() )
280  colors_dir.Traverse( loader );
281 }
void registerColorSettings(const wxString &aFilename)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored (normally .

References GetColorSettingsPath(), and registerColorSettings().

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

186 {
187  wxLogTrace( traceSettings, "Attempting to load color theme %s", aName );
188 
189  wxFileName fn( GetColorSettingsPath(), aName, "json" );
190 
191  if( !fn.IsOk() || !fn.Exists() )
192  {
193  wxLogTrace( traceSettings, "Theme file %s.json not found, falling back to user", aName );
194  return nullptr;
195  }
196 
197  auto cs = static_cast<COLOR_SETTINGS*>(
198  RegisterSettings( new COLOR_SETTINGS( aName.ToStdString() ) ) );
199 
200  if( cs->GetFilename() != aName.ToStdString() )
201  {
202  wxLogTrace( traceSettings, "Warning: stored filename is actually %s, ", cs->GetFilename() );
203  }
204 
205  m_color_settings[aName] = cs;
206 
207  return cs;
208 }
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored (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 677 of file settings_manager.cpp.

678 {
679  // Normalize path to new format even if migrating from a legacy file
680  wxFileName path( aFullPath );
681 
682  if( path.GetExt() == LegacyProjectFileExtension )
683  path.SetExt( ProjectFileExtension );
684 
685  wxString fullPath = path.GetFullPath();
686 
687  // If already loaded, we are all set. This might be called more than once over a project's
688  // lifetime in case the project is first loaded by the KiCad manager and then eeschema or
689  // pcbnew try to load it again when they are launched.
690  if( m_projects.count( fullPath ) )
691  return true;
692 
693  // No MDI yet
694  if( aSetActive && !m_projects.empty() )
695  {
696  PROJECT* oldProject = m_projects.begin()->second.get();
697  unloadProjectFile( oldProject, true );
698  m_projects.erase( m_projects.begin() );
699  }
700 
701  wxLogTrace( traceSettings, "Load project %s", fullPath );
702 
703  std::unique_ptr<PROJECT> project = std::make_unique<PROJECT>();
704  project->setProjectFullName( fullPath );
705 
706  bool success = loadProjectFile( *project );
707 
708  m_projects[fullPath].reset( project.release() );
709 
710  wxString fn( path.GetName() );
711 
712  PROJECT_LOCAL_SETTINGS* settings = static_cast<PROJECT_LOCAL_SETTINGS*>(
713  RegisterSettings( new PROJECT_LOCAL_SETTINGS( m_projects[fullPath].get(), fn ) ) );
714 
715  m_projects[fullPath]->setLocalSettings( settings );
716 
717  if( m_kiway )
719 
720  return success;
721 }
PROJECT holds project specific data.
Definition: project.h:61
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.
std::map< wxString, std::unique_ptr< PROJECT > > m_projects
Loaded projects, mapped according to project full name.
VTBL_ENTRY void ProjectChanged()
Calls ProjectChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:536
const std::string LegacyProjectFileExtension
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.

References LegacyProjectFileExtension, loadProjectFile(), m_kiway, m_projects, KIWAY::ProjectChanged(), ProjectFileExtension, RegisterSettings(), traceSettings, and unloadProjectFile().

Referenced by KICAD_MANAGER_FRAME::CreateNewProject(), GetDefaultProject(), PGM_BASE::InitPgm(), LoadBoard(), loadKicadProject(), TEST_NETLISTS_FIXTURE::loadSchematic(), DIALOG_SCHEMATIC_SETUP::OnAuxiliaryAction(), DIALOG_BOARD_SETUP::OnAuxiliaryAction(), SCH_EDIT_FRAME::OnImportProject(), KICAD_MANAGER_FRAME::OnUnarchiveFiles(), SCH_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::SavePcbCopy(), PCB_EDIT_FRAME::SavePcbFile(), 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 808 of file settings_manager.cpp.

809 {
810  wxFileName fullFn( aProject.GetProjectFullName() );
811  wxString fn( fullFn.GetName() );
812 
813  PROJECT_FILE* file =
814  static_cast<PROJECT_FILE*>( RegisterSettings( new PROJECT_FILE( fn ), false ) );
815 
816  m_project_files[aProject.GetProjectFullName()] = file;
817 
818  aProject.setProjectFile( file );
819  file->SetProject( &aProject );
820 
821  wxString path( fullFn.GetPath() );
822 
823  return file->LoadFromFile( path );
824 }
VTBL_ENTRY void setProjectFile(PROJECT_FILE *aFile)
Sets the backing store file for this project Should only be called by SETTINGS_MANGER on load.
Definition: project.h:317
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
PROJECT_FILE is the backing store for a PROJECT, in JSON format.
Definition: project_file.h:62
VTBL_ENTRY const wxString GetProjectFullName() const
Function GetProjectFullName returns the full path and name of the project.
Definition: project.cpp:118
JSON_SETTINGS * RegisterSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
Takes ownership of the pointer passed in.

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

411 {
412  if( m_headless )
413  {
414  wxLogTrace( traceSettings, "Settings migration not checked; running headless" );
415  return false;
416  }
417 
418  wxFileName path( GetUserSettingsPath(), "" );
419  wxLogTrace( traceSettings, "Using settings path %s", path.GetFullPath() );
420 
421  if( path.DirExists() )
422  {
423  wxFileName common = path;
424  common.SetName( "kicad_common" );
425  common.SetExt( "json" );
426 
427  if( common.Exists() )
428  {
429  wxLogTrace( traceSettings, "Path exists and has a kicad_common, continuing!" );
430  return true;
431  }
432  }
433 
434  // Now we have an empty path, let's figure out what to put in it
435  DIALOG_MIGRATE_SETTINGS dlg( this );
436 
437  if( dlg.ShowModal() != wxID_OK )
438  {
439  wxLogTrace( traceSettings, "Migration dialog canceled; exiting" );
440  return false;
441  }
442 
443  if( !path.DirExists() )
444  {
445  wxLogTrace( traceSettings, "Path didn't exist; creating it" );
446  path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
447  }
448 
449  if( m_migration_source.IsEmpty() )
450  {
451  wxLogTrace( traceSettings, "No migration source given; starting with defaults" );
452  return true;
453  }
454 
455  MIGRATION_TRAVERSER traverser( m_migration_source, path.GetFullPath() );
456  wxDir source_dir( m_migration_source );
457 
458  source_dir.Traverse( traverser );
459 
460  if( !traverser.GetErrors().empty() )
461  DisplayErrorMessage( nullptr, traverser.GetErrors() );
462 
463  return true;
464 }
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:252
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_migration_source, 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 751 of file settings_manager.cpp.

752 {
753  // No MDI yet: First project in the list is the active project
754  return *m_projects.begin()->second;
755 }
std::map< wxString, std::unique_ptr< 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(), loadKicadProject(), TEST_NETLISTS_FIXTURE::loadSchematic(), PCB_EDIT_FRAME::OpenProjectFiles(), SaveProject(), 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 244 of file settings_manager.cpp.

245 {
246  if( m_color_settings.count( aFilename ) )
247  return;
248 
249  m_color_settings[aFilename] = static_cast<COLOR_SETTINGS*>(
250  RegisterSettings( new COLOR_SETTINGS( aFilename ) ) );
251 }
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(), 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 79 of file settings_manager.cpp.

80 {
81  std::unique_ptr<JSON_SETTINGS> ptr( aSettings );
82 
83  ptr->SetManager( this );
84 
85  wxLogTrace( traceSettings, "Registered new settings object <%s>", ptr->GetFullFilename() );
86 
87  if( aLoadNow )
88  ptr->LoadFromFile( GetPathForSettingsFile( ptr.get() ) );
89 
90  m_settings.push_back( std::move( ptr ) );
91  return m_settings.back().get();
92 }
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(), loadColorSettingsByName(), LoadProject(), loadProjectFile(), CV::IFACE::OnKifaceStart(), PGE::IFACE::OnKifaceStart(), PCBCALC::IFACE::OnKifaceStart(), GERBV::IFACE::OnKifaceStart(), SCH::IFACE::OnKifaceStart(), PCB::IFACE::OnKifaceStart(), PGM_KICAD::OnPgmInit(), registerColorSettings(), and SETTINGS_MANAGER().

◆ ReloadColorSettings()

void SETTINGS_MANAGER::ReloadColorSettings ( )

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

Definition at line 284 of file settings_manager.cpp.

285 {
286  m_color_settings.clear();
288 }
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(), PANEL_MODEDIT_COLOR_SETTINGS::PANEL_MODEDIT_COLOR_SETTINGS(), and PANEL_PCBNEW_COLOR_SETTINGS::PANEL_PCBNEW_COLOR_SETTINGS().

◆ Save() [1/2]

void SETTINGS_MANAGER::Save ( )

Definition at line 118 of file settings_manager.cpp.

119 {
120  for( auto&& settings : m_settings )
121  {
122  // Never automatically save color settings, caller should use SaveColorSettings
123  if( dynamic_cast<COLOR_SETTINGS*>( settings.get() ) )
124  continue;
125 
126  settings->SaveToFile( GetPathForSettingsFile( settings.get() ) );
127  }
128 }
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 FOOTPRINT_EDITOR_SETTINGS::MigrateFromLegacy(), and COLOR_SETTINGS::migrateSchema0to1().

◆ Save() [2/2]

void SETTINGS_MANAGER::Save ( JSON_SETTINGS aSettings)

Definition at line 131 of file settings_manager.cpp.

132 {
133  auto it = std::find_if( m_settings.begin(), m_settings.end(),
134  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
135  {
136  return aPtr.get() == aSettings;
137  } );
138 
139  if( it != m_settings.end() )
140  {
141  wxLogTrace( traceSettings, "Saving %s", ( *it )->GetFullFilename() );
142  ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
143  }
144 }
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 291 of file settings_manager.cpp.

292 {
293  // The passed settings should already be managed
294  wxASSERT( std::find_if( m_color_settings.begin(), m_color_settings.end(),
295  [aSettings] ( const std::pair<wxString, COLOR_SETTINGS*>& el )
296  {
297  return el.second->GetFilename() == aSettings->GetFilename();
298  }
299  ) != m_color_settings.end() );
300 
301  nlohmann::json::json_pointer ptr = JSON_SETTINGS::PointerFromString( aNamespace );
302 
303  if( !aSettings->Store() )
304  {
305  wxLogTrace( traceSettings, "Color scheme %s not modified; skipping save",
306  aSettings->GetFilename(), aNamespace );
307  return;
308  }
309 
310  wxASSERT( aSettings->contains( ptr ) );
311 
312  wxLogTrace( traceSettings, "Saving color scheme %s, preserving %s", aSettings->GetFilename(),
313  aNamespace );
314 
315  nlohmann::json backup = aSettings->at( ptr );
316  wxString path = GetColorSettingsPath();
317 
318  aSettings->LoadFromFile( path );
319 
320  ( *aSettings )[ptr].update( backup );
321  aSettings->Load();
322 
323  aSettings->SaveToFile( path, true );
324 }
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:64
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
nlohmann::json json
Definition: gerbview.cpp:40
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
static wxString GetColorSettingsPath()
Returns the path where color scheme files are stored (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, JSON_SETTINGS::PointerFromString(), JSON_SETTINGS::SaveToFile(), JSON_SETTINGS::Store(), and traceSettings.

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

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

785 {
786  wxString path = aFullPath;
787 
788  if( path.empty() )
789  path = Prj().GetProjectFullName();
790 
791  // TODO: refactor for MDI
792  if( Prj().IsReadOnly() )
793  return false;
794 
795  if( !m_project_files.count( path ) )
796  return false;
797 
798  PROJECT_FILE* project = m_project_files.at( path );
799  wxString projectPath = GetPathForSettingsFile( project );
800 
801  project->SaveToFile( projectPath );
802  Prj().GetLocalSettings().SaveToFile( projectPath );
803 
804  return true;
805 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
VTBL_ENTRY PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:147
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
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.
PROJECT_FILE is the backing store for a PROJECT, in JSON format.
Definition: project_file.h:62
VTBL_ENTRY const wxString GetProjectFullName() const
Function GetProjectFullName returns the full path and name of the project.
Definition: project.cpp:118
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, Prj(), PROJECT_LOCAL_SETTINGS::SaveToFile(), and PROJECT_FILE::SaveToFile().

Referenced by KICAD_MANAGER_FRAME::CloseProject(), KICAD_MANAGER_FRAME::CreateNewProject(), SCH_EDIT_FRAME::doCloseWindow(), PCB_EDIT_FRAME::Files_io_from_id(), SCH_EDIT_FRAME::OnImportProject(), SCH_EDIT_FRAME::OpenProjectFiles(), SaveBoard(), PCB_EDIT_FRAME::SavePcbCopy(), PCB_EDIT_FRAME::SavePcbFile(), SCH_EDIT_FRAME::SaveProjectSettings(), and PCB_EDIT_FRAME::SaveProjectSettings().

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

52 { 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().

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

190 { 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 936 of file settings_manager.cpp.

937 {
939 
940  if( !settings.enabled )
941  return true;
942 
943  wxString prefix = Prj().GetProjectName() + '-';
944 
945  auto modTime =
946  [&prefix]( const wxString& aFile )
947  {
948  wxDateTime dt;
949  wxString fn( wxFileName( aFile ).GetName() );
950  fn.Replace( prefix, "" );
951  dt.ParseFormat( fn, backupDateTimeFormat );
952  return dt;
953  };
954 
955  // Project not saved yet
956  if( Prj().GetProjectPath().empty() )
957  return true;
958 
959  wxString backupPath = GetProjectBackupsPath();
960 
961  if( !wxDirExists( backupPath ) )
962  {
963  wxLogTrace( traceSettings, "Backup path %s doesn't exist, creating it", backupPath );
964 
965  if( !wxMkdir( backupPath ) )
966  {
967  wxLogTrace( traceSettings, "Could not create backups path! Skipping backup" );
968  return false;
969  }
970  }
971 
972  wxDir dir( backupPath );
973 
974  if( !dir.IsOpened() )
975  {
976  wxLogTrace( traceSettings, "Could not open project backups path %s", dir.GetName() );
977  return false;
978  }
979 
980  std::vector<wxString> files;
981 
982  VECTOR_INSERT_TRAVERSER traverser( files,
983  [&modTime]( const wxString& aFile )
984  {
985  return modTime( aFile ).IsValid();
986  } );
987 
988  dir.Traverse( traverser, wxT( "*.zip" ) );
989 
990  // Sort newest-first
991  std::sort( files.begin(), files.end(),
992  [&]( const wxString& aFirst, const wxString& aSecond ) -> bool
993  {
994  wxDateTime first = modTime( aFirst );
995  wxDateTime second = modTime( aSecond );
996 
997  return first.GetTicks() > second.GetTicks();
998  } );
999 
1000  // Do we even need to back up?
1001  if( !files.empty() )
1002  {
1003  wxDateTime lastTime = modTime( files[0] );
1004 
1005  if( lastTime.IsValid() )
1006  {
1007  wxTimeSpan delta = wxDateTime::Now() - modTime( files[0] );
1008 
1009  if( delta.IsShorterThan( wxTimeSpan::Seconds( settings.min_interval ) ) )
1010  return true;
1011  }
1012  }
1013 
1014  // Now that we know a backup is needed, apply the retention policy
1015 
1016  // Step 1: if we're over the total file limit, remove the oldest
1017  if( !files.empty() && settings.limit_total_files > 0 )
1018  {
1019  while( files.size() > static_cast<size_t>( settings.limit_total_files ) )
1020  {
1021  wxRemoveFile( files.back() );
1022  files.pop_back();
1023  }
1024  }
1025 
1026  // Step 2: Stay under the total size limit
1027  if( settings.limit_total_size > 0 )
1028  {
1029  wxULongLong totalSize = 0;
1030 
1031  for( const wxString& file : files )
1032  totalSize += wxFileName::GetSize( file );
1033 
1034  while( !files.empty() && totalSize > static_cast<wxULongLong>( settings.limit_total_size ) )
1035  {
1036  totalSize -= wxFileName::GetSize( files.back() );
1037  wxRemoveFile( files.back() );
1038  files.pop_back();
1039  }
1040  }
1041 
1042  // Step 3: Stay under the daily limit
1043  if( settings.limit_daily_files > 0 && files.size() > 1 )
1044  {
1045  wxDateTime day = modTime( files[0] );
1046  int num = 1;
1047 
1048  wxASSERT( day.IsValid() );
1049 
1050  std::vector<wxString> filesToDelete;
1051 
1052  for( size_t i = 1; i < files.size(); i++ )
1053  {
1054  wxDateTime dt = modTime( files[i] );
1055 
1056  if( dt.IsSameDate( day ) )
1057  {
1058  num++;
1059 
1060  if( num > settings.limit_daily_files )
1061  filesToDelete.emplace_back( files[i] );
1062  }
1063  else
1064  {
1065  day = dt;
1066  num = 1;
1067  }
1068  }
1069 
1070  for( const wxString& file : filesToDelete )
1071  wxRemoveFile( file );
1072  }
1073 
1074  return BackupProject( aReporter );
1075 }
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.
static bool empty(const wxTextEntryBase *aCtrl)
VTBL_ENTRY const wxString GetProjectName() const
Function GetProjectName returns the short name of the project.
Definition: project.cpp:130
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(), empty(), COMMON_SETTINGS::AUTO_BACKUP::enabled, GetCommonSettings(), GetProjectBackupsPath(), PROJECT::GetProjectName(), COMMON_SETTINGS::AUTO_BACKUP::limit_daily_files, COMMON_SETTINGS::AUTO_BACKUP::limit_total_files, COMMON_SETTINGS::AUTO_BACKUP::limit_total_size, COMMON_SETTINGS::m_Backup, COMMON_SETTINGS::AUTO_BACKUP::min_interval, Prj(), and traceSettings.

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

◆ UnloadProject()

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

Saves, unloads and unregisters the given PROJECT.

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

Definition at line 724 of file settings_manager.cpp.

725 {
726  if( !aProject || !m_projects.count( aProject->GetProjectFullName() ) )
727  return false;
728 
729  if( !unloadProjectFile( aProject, aSave ) )
730  return false;
731 
732  wxLogTrace( traceSettings, "Unload project %s", aProject->GetProjectFullName() );
733 
734  m_projects.erase( aProject->GetProjectFullName() );
735 
736  // Immediately reload a null project; this is required until the rest of the application
737  // is refactored to not assume that Prj() always works
738  if( m_projects.empty() )
739  LoadProject( "" );
740 
741  // Remove the reference in the environment to the previous project
742  wxSetEnv( PROJECT_VAR_NAME, "" );
743 
744  if( m_kiway )
746 
747  return true;
748 }
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.
std::map< wxString, std::unique_ptr< PROJECT > > m_projects
Loaded projects, mapped according to project full name.
VTBL_ENTRY void ProjectChanged()
Calls ProjectChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:536
VTBL_ENTRY const wxString GetProjectFullName() const
Function GetProjectFullName returns the full path and name of the project.
Definition: project.cpp:118
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.

References PROJECT::GetProjectFullName(), LoadProject(), m_kiway, m_projects, 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(), SCH_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::SavePcbCopy(), PCB_EDIT_FRAME::SavePcbFile(), 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 827 of file settings_manager.cpp.

828 {
829  if( !aProject )
830  return false;
831 
832  wxString name = aProject->GetProjectFullName();
833 
834  if( !m_project_files.count( name ) )
835  return false;
836 
838 
839  auto it = std::find_if( m_settings.begin(), m_settings.end(),
840  [&file]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
841  {
842  return aPtr.get() == file;
843  } );
844 
845  if( it != m_settings.end() )
846  {
847  wxString projectPath = GetPathForSettingsFile( it->get() );
848 
849  FlushAndRelease( &aProject->GetLocalSettings(), aSave );
850 
851  if( aSave )
852  ( *it )->SaveToFile( projectPath );
853 
854  m_settings.erase( it );
855  }
856 
857  m_project_files.erase( name );
858 
859  return true;
860 }
VTBL_ENTRY PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:147
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
PROJECT_FILE is the backing store for a PROJECT, in JSON format.
Definition: project_file.h:62
VTBL_ENTRY const wxString GetProjectFullName() const
Function GetProjectFullName returns the full path and name of the project.
Definition: project.cpp:118
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
const char * name
Definition: DXF_plotter.cpp:60
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 394 of file settings_manager.h.

Referenced by BackupProject(), and TriggerBackupIfNeeded().

◆ m_color_settings

std::unordered_map<wxString, COLOR_SETTINGS*> SETTINGS_MANAGER::m_color_settings
private

◆ m_common_settings

COMMON_SETTINGS* SETTINGS_MANAGER::m_common_settings
private

Definition at line 381 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 371 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 374 of file settings_manager.h.

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

◆ m_migration_source

wxString SETTINGS_MANAGER::m_migration_source
private

Definition at line 383 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 386 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 392 of file settings_manager.h.

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

◆ m_projects

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

Loaded projects, mapped according to project full name.

Definition at line 389 of file settings_manager.h.

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

◆ m_settings

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

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