KiCad PCB EDA Suite
SETTINGS_MANAGER Class Reference

#include <settings_manager.h>

Public Member Functions

 SETTINGS_MANAGER (bool aHeadless=false)
 
 ~SETTINGS_MANAGER ()
 
bool IsOK ()
 
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...
 
std::string 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...
 
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...
 
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 std::string GetColorSettingsPath ()
 Returns the path where color scheme files are stored (normally . More...
 
static std::string 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 std::string 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...
 
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 34 of file settings_manager.h.

Constructor & Destructor Documentation

◆ SETTINGS_MANAGER()

SETTINGS_MANAGER::SETTINGS_MANAGER ( bool  aHeadless = false)

Definition at line 54 of file settings_manager.cpp.

54  :
55  m_headless( aHeadless ),
56  m_common_settings( nullptr ),
58 {
59  // Check if the settings directory already exists, and if not, perform a migration if possible
60  if( !MigrateIfNeeded() )
61  {
62  m_ok = false;
63  return;
64  }
65 
66  m_ok = true;
67 
68  // create the common settings shared by all applications. Not loaded immediately
70  static_cast<COMMON_SETTINGS*>( RegisterSettings( new COMMON_SETTINGS, false ) );
71 
73 }
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 75 of file settings_manager.cpp.

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

259 {
260  wxString filename = aFilename;
261 
262  if( filename.EndsWith( wxT( ".json" ) ) )
263  filename = filename.BeforeLast( '.' );
264 
265  registerColorSettings( filename );
266  return m_color_settings[filename];
267 }
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 838 of file settings_manager.cpp.

839 {
840  wxDateTime timestamp = wxDateTime::Now();
841 
842  wxString fileName = wxString::Format( wxT( "%s-%s" ), Prj().GetProjectName(),
843  timestamp.Format( backupDateTimeFormat ) );
844 
845  wxFileName target;
846  target.SetPath( GetProjectBackupsPath() );
847  target.SetName( fileName );
848  target.SetExt( ArchiveFileExtension );
849 
850  wxDir dir( target.GetPath() );
851 
852  if( !target.DirExists() && !wxMkdir( target.GetPath() ) )
853  {
854  wxLogTrace( traceSettings, "Could not create project backup path %s", target.GetPath() );
855  return false;
856  }
857 
858  if( !target.IsDirWritable() )
859  {
860  wxLogTrace( traceSettings, "Backup directory %s is not writeable", target.GetPath() );
861  return false;
862  }
863 
864  wxLogTrace( traceSettings, "Backing up project to %s", target.GetPath() );
865 
866  PROJECT_ARCHIVER archiver;
867 
868  return archiver.Archive( Prj().GetProjectPath(), target.GetFullPath(), aReporter );
869 }
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:205
const char * traceSettings
Flag to enable settings tracing.
const std::string ArchiveFileExtension

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

Referenced by TriggerBackupIfNeeded().

◆ calculateUserSettingsPath()

std::string 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 570 of file settings_manager.cpp.

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

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

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

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

152 {
153  auto it = std::find_if( m_settings.begin(), m_settings.end(),
154  [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
155  {
156  return aPtr.get() == aSettings;
157  } );
158 
159  if( it != m_settings.end() )
160  {
161  wxLogTrace( traceSettings, "Flush and release %s", ( *it )->GetFullFilename() );
162 
163  if( aSave )
164  ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
165 
166  m_settings.erase( it );
167  }
168 }
std::string GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
const char * traceSettings
Flag to enable settings tracing.

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

79  {
80  AppSettings* ret = nullptr;
81 
82  auto it = std::find_if( m_settings.begin(), m_settings.end(),
83  []( const std::unique_ptr<JSON_SETTINGS>& aSettings ) {
84  return dynamic_cast<AppSettings*>( aSettings.get() );
85  } );
86 
87  if( it != m_settings.end() )
88  ret = dynamic_cast<AppSettings*>( it->get() );
89  else
90  ret = static_cast<AppSettings*>( RegisterSettings( new AppSettings, aLoadNow ) );
91 
92  return ret;
93  }
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

References m_settings, and RegisterSettings().

Referenced by 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(), DIALOG_PLOT::Plot(), PANEL_PL_EDITOR_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_LIBEDIT_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_PCBNEW_COLOR_SETTINGS::TransferDataFromWindow(), PANEL_MODEDIT_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 171 of file settings_manager.cpp.

172 {
173  if( m_color_settings.count( aName ) )
174  return m_color_settings.at( aName );
175 
176  COLOR_SETTINGS* ret = nullptr;
177 
178  if( !aName.empty() )
179  ret = loadColorSettingsByName( aName );
180 
181  // This had better work
182  if( !ret )
183  ret = m_color_settings.at( "user" );
184 
185  return ret;
186 }
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 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(), 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 104 of file settings_manager.h.

105  {
106  std::vector<COLOR_SETTINGS*> ret;
107 
108  for( const auto& el : m_color_settings )
109  ret.push_back( el.second );
110 
111  std::sort( ret.begin(), ret.end(), []( COLOR_SETTINGS* a, COLOR_SETTINGS* b ) {
112  return a->GetName() < b->GetName();
113  } );
114 
115  return ret;
116  }
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()

std::string SETTINGS_MANAGER::GetColorSettingsPath ( )
static

Returns the path where color scheme files are stored (normally .

/colors/ under the user settings path)

Definition at line 548 of file settings_manager.cpp.

549 {
550  wxFileName path;
551 
552  path.AssignDir( GetUserSettingsPath() );
553  path.AppendDir( "colors" );
554 
555  return path.GetPath().ToStdString();
556 }
static std::string 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 140 of file settings_manager.h.

140 { return m_common_settings; }
COMMON_SETTINGS * m_common_settings

References m_common_settings.

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

◆ GetPathForSettingsFile()

std::string 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 331 of file settings_manager.cpp.

332 {
333  wxASSERT( aSettings );
334 
335  switch( aSettings->GetLocation() )
336  {
337  case SETTINGS_LOC::USER:
338  return GetUserSettingsPath();
339 
341  return std::string( Prj().GetProjectPath().ToUTF8() );
342 
344  return GetColorSettingsPath();
345 
346  case SETTINGS_LOC::NONE:
347  return "";
348 
349  default:
350  wxASSERT_MSG( false, "Unknown settings location!" );
351  }
352 
353  return "";
354 }
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
static std::string GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
The color scheme directory (e.g. ~/.config/kicad/colors/)
The settings directory inside a project folder.
SETTINGS_LOC GetLocation() const
Definition: json_settings.h:60
static std::string GetColorSettingsPath()
Returns the path where color scheme files are stored (normally .
No directory prepended, full path in filename (used for PROJECT_FILE)
The main config directory (e.g. ~/.config/kicad/)

References COLORS, GetColorSettingsPath(), JSON_SETTINGS::GetLocation(), 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 471 of file settings_manager.cpp.

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

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

746 {
747  if( m_projects.count( aFullPath ) )
748  return m_projects.at( aFullPath ).get();
749 
750  return nullptr;
751 }
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 829 of file settings_manager.cpp.

830 {
832 }
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:122
VTBL_ENTRY const wxString GetProjectName() const
Function GetProjectName returns the short name of the project.
Definition: project.cpp:128

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

Referenced by BackupProject(), and TriggerBackupIfNeeded().

◆ GetSettingsVersion()

std::string SETTINGS_MANAGER::GetSettingsVersion ( )
static

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

Returns
a string such as "5.1"

Definition at line 611 of file settings_manager.cpp.

612 {
613  // CMake computes the major.minor string for us.
614  return GetMajorMinorVersion().ToStdString();
615 }
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()

std::string 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 559 of file settings_manager.cpp.

560 {
561  static std::string user_settings_path;
562 
563  if( user_settings_path.empty() )
564  user_settings_path = calculateUserSettingsPath();
565 
566  return user_settings_path;
567 }
static std::string 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 44 of file settings_manager.h.

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

References m_ok.

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

542 {
543  wxFileName test( aPath, "kicad_common" );
544  return test.Exists();
545 }

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

◆ Load() [1/2]

void SETTINGS_MANAGER::Load ( )

Definition at line 99 of file settings_manager.cpp.

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

References GetPathForSettingsFile(), and m_settings.

Referenced by PGM_BASE::InitPgm().

◆ Load() [2/2]

void SETTINGS_MANAGER::Load ( JSON_SETTINGS aSettings)

Definition at line 109 of file settings_manager.cpp.

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

References GetPathForSettingsFile(), and m_settings.

◆ loadAllColorSettings()

void SETTINGS_MANAGER::loadAllColorSettings ( )
private

Definition at line 270 of file settings_manager.cpp.

271 {
272  // Create the default color settings
273  registerColorSettings( "user" );
274 
275  // Search for and load any other settings
276  COLOR_SETTINGS_LOADER loader( [&]( const wxString& aFilename )
277  {
278  registerColorSettings( aFilename );
279  } );
280 
281  wxDir colors_dir( GetColorSettingsPath() );
282 
283  if( colors_dir.IsOpened() )
284  colors_dir.Traverse( loader );
285 }
void registerColorSettings(const wxString &aFilename)
static std::string 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 189 of file settings_manager.cpp.

190 {
191  wxLogTrace( traceSettings, "Attempting to load color theme %s", aName );
192 
193  wxFileName fn( GetColorSettingsPath(), aName, "json" );
194 
195  if( !fn.IsOk() || !fn.Exists() )
196  {
197  wxLogTrace( traceSettings, "Theme file %s.json not found, falling back to user", aName );
198  return nullptr;
199  }
200 
201  auto cs = static_cast<COLOR_SETTINGS*>(
202  RegisterSettings( new COLOR_SETTINGS( aName.ToStdString() ) ) );
203 
204  if( cs->GetFilename() != aName.ToStdString() )
205  {
206  wxLogTrace( traceSettings, "Warning: stored filename is actually %s, ", cs->GetFilename() );
207  }
208 
209  m_color_settings[aName] = cs;
210 
211  return cs;
212 }
static std::string 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 char * traceSettings
Flag to enable settings tracing.

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

682 {
683  // Normalize path to new format even if migrating from a legacy file
684  wxFileName path( aFullPath );
685 
686  if( path.GetExt() == LegacyProjectFileExtension )
687  path.SetExt( ProjectFileExtension );
688 
689  wxString fullPath = path.GetFullPath();
690 
691  // If already loaded, we are all set. This might be called more than once over a project's
692  // lifetime in case the project is first loaded by the KiCad manager and then eeschema or
693  // pcbnew try to load it again when they are launched.
694  if( m_projects.count( fullPath ) )
695  return true;
696 
697  // No MDI yet
698  if( aSetActive && !m_projects.empty() && !UnloadProject( m_projects.begin()->second.get() ) )
699  return false;
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  std::string fn( path.GetName().ToUTF8() );
711 
712  PROJECT_LOCAL_SETTINGS* settings = static_cast<PROJECT_LOCAL_SETTINGS*>(
714 
715  m_projects[fullPath]->setLocalSettings( settings );
716  settings->SetProject( m_projects[fullPath].get() );
717 
718  return success;
719 }
const std::string ProjectFileExtension
The project local settings are things that are attached to a particular project, but also might be pa...
std::map< wxString, std::unique_ptr< PROJECT > > m_projects
Loaded projects, mapped according to project full name.
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.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Saves, unloads and unregisters the given PROJECT.
const char * traceSettings
Flag to enable settings tracing.

References LegacyProjectFileExtension, loadProjectFile(), m_projects, ProjectFileExtension, RegisterSettings(), traceSettings, and UnloadProject().

Referenced by KICAD_MANAGER_FRAME::CreateNewProject(), PCB_EDIT_FRAME::Files_io_from_id(), GetDefaultProject(), PGM_BASE::InitPgm(), LoadBoard(), 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::SavePcbFile(), and TEST_NETLIST_EXPORTER_PSPICE_SIM::TEST_NETLIST_EXPORTER_PSPICE_SIM().

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

775 {
776  wxFileName fullFn( aProject.GetProjectFullName() );
777  std::string fn( fullFn.GetName().ToUTF8() );
778 
779  PROJECT_FILE* file =
780  static_cast<PROJECT_FILE*>( RegisterSettings( new PROJECT_FILE( fn ), false ) );
781 
782  m_project_files[aProject.GetProjectFullName()] = file;
783 
784  aProject.setProjectFile( file );
785  file->SetProject( &aProject );
786 
787  std::string path( fullFn.GetPath().ToUTF8() );
788 
789  return file->LoadFromFile( path );
790 }
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:305
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:116
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 414 of file settings_manager.cpp.

415 {
416  wxFileName path( GetUserSettingsPath(), "" );
417  wxLogTrace( traceSettings, "Using settings path %s", path.GetFullPath() );
418 
419  if( path.DirExists() )
420  {
421  wxFileName common = path;
422  common.SetName( "kicad_common" );
423  common.SetExt( "json" );
424 
425  if( common.Exists() )
426  {
427  wxLogTrace( traceSettings, "Path exists and has a kicad_common, continuing!" );
428  return true;
429  }
430  }
431 
432  if( m_headless )
433  {
434  wxLogTrace( traceSettings, "Manual settings migration required but running headless!" );
435  return false;
436  }
437 
438  // Now we have an empty path, let's figure out what to put in it
439  DIALOG_MIGRATE_SETTINGS dlg( this );
440 
441  if( dlg.ShowModal() != wxID_OK )
442  {
443  wxLogTrace( traceSettings, "Migration dialog canceled; exiting" );
444  return false;
445  }
446 
447  if( !path.DirExists() )
448  {
449  wxLogTrace( traceSettings, "Path didn't exist; creating it" );
450  path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
451  }
452 
453  if( m_migration_source.IsEmpty() )
454  {
455  wxLogTrace( traceSettings, "No migration source given; starting with defaults" );
456  return true;
457  }
458 
459  MIGRATION_TRAVERSER traverser( m_migration_source, path.GetFullPath() );
460  wxDir source_dir( m_migration_source );
461 
462  source_dir.Traverse( traverser );
463 
464  if( !traverser.GetErrors().empty() )
465  DisplayErrorMessage( nullptr, traverser.GetErrors() );
466 
467  return true;
468 }
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:252
static std::string GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
wxString m_migration_source
bool m_headless
True if running outside a UI context.
const char * traceSettings
Flag to enable settings tracing.

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

739 {
740  // No MDI yet: First project in the list is the active project
741  return *m_projects.begin()->second;
742 }
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(), TEST_NETLISTS_FIXTURE::loadSchematic(), PCB_EDIT_FRAME::OpenProjectFiles(), SaveProject(), TEST_NETLIST_EXPORTER_PSPICE_SIM::TEST_NETLIST_EXPORTER_PSPICE_SIM(), and TriggerBackupIfNeeded().

◆ registerColorSettings()

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

Definition at line 248 of file settings_manager.cpp.

249 {
250  if( m_color_settings.count( aFilename ) )
251  return;
252 
253  m_color_settings[aFilename] = static_cast<COLOR_SETTINGS*>(
254  RegisterSettings( new COLOR_SETTINGS( aFilename.ToStdString() ) ) );
255 }
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 83 of file settings_manager.cpp.

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

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

289 {
290  m_color_settings.clear();
292 }
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 122 of file settings_manager.cpp.

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

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

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

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

296 {
297  // The passed settings should already be managed
298  wxASSERT( std::find_if( m_color_settings.begin(), m_color_settings.end(),
299  [aSettings] ( const std::pair<wxString, COLOR_SETTINGS*>& el )
300  {
301  return el.second->GetFilename() == aSettings->GetFilename();
302  }
303  ) != m_color_settings.end() );
304 
305  nlohmann::json::json_pointer ptr = JSON_SETTINGS::PointerFromString( aNamespace );
306 
307  if( !aSettings->Store() )
308  {
309  wxLogTrace( traceSettings, "Color scheme %s not modified; skipping save",
310  aSettings->GetFilename(), aNamespace );
311  return;
312  }
313 
314  wxASSERT( aSettings->contains( ptr ) );
315 
316  wxLogTrace( traceSettings, "Saving color scheme %s, preserving %s", aSettings->GetFilename(),
317  aNamespace );
318 
319  nlohmann::json backup = aSettings->at( ptr );
320  std::string path = GetColorSettingsPath();
321 
322  aSettings->LoadFromFile( path );
323 
324  ( *aSettings )[ptr].update( backup );
325  aSettings->Load();
326 
327  aSettings->SaveToFile( path, true );
328 }
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
virtual bool SaveToFile(const std::string &aDirectory="", bool aForce=false)
virtual bool LoadFromFile(const std::string &aDirectory="")
Loads the backing file from disk and then calls Load()
nlohmann::json json
Definition: gerbview.cpp:40
static std::string GetColorSettingsPath()
Returns the path where color scheme files are stored (normally .
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
std::string GetFilename() const
Definition: json_settings.h:56
const char * traceSettings
Flag to enable settings tracing.
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(), PANEL_PCBNEW_COLOR_SETTINGS::PANEL_PCBNEW_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 754 of file settings_manager.cpp.

755 {
756  wxString path = aFullPath;
757 
758  if( path.empty() )
759  path = Prj().GetProjectFullName();
760 
761  if( !m_project_files.count( path ) )
762  return false;
763 
764  PROJECT_FILE* project = m_project_files.at( path );
765  std::string projectPath = GetPathForSettingsFile( project );
766 
767  project->SaveToFile( projectPath );
768  Prj().GetLocalSettings().SaveToFile( projectPath );
769 
770  return true;
771 }
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:135
bool SaveToFile(const std::string &aDirectory="", bool aForce=false) override
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
std::string GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.
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:116
bool SaveToFile(const std::string &aDirectory="", bool aForce=false) override

References PROJECT::GetLocalSettings(), GetPathForSettingsFile(), PROJECT::GetProjectFullName(), m_project_files, Prj(), PROJECT_LOCAL_SETTINGS::SaveToFile(), and PROJECT_FILE::SaveToFile().

Referenced by KICAD_MANAGER_FRAME::CreateNewProject(), PCB_EDIT_FRAME::Files_io_from_id(), KICAD_MANAGER_FRAME::LoadProject(), SCH_EDIT_FRAME::OnCloseWindow(), SCH_EDIT_FRAME::OnImportProject(), SCH_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), SaveBoard(), PCB_EDIT_FRAME::SavePcbFile(), SCH_EDIT_FRAME::SaveProjectSettings(), and PCB_EDIT_FRAME::SaveProjectSettings().

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

168 { 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 902 of file settings_manager.cpp.

903 {
905 
906  if( !settings.enabled )
907  return true;
908 
909  wxString prefix = Prj().GetProjectName() + '-';
910 
911  auto modTime =
912  [&prefix]( const wxString& aFile )
913  {
914  wxDateTime dt;
915  wxString fn( wxFileName( aFile ).GetName() );
916  fn.Replace( prefix, "" );
917  dt.ParseFormat( fn, backupDateTimeFormat );
918  return dt;
919  };
920 
921  // Project not saved yet
922  if( Prj().GetProjectPath().empty() )
923  return true;
924 
925  wxString backupPath = GetProjectBackupsPath();
926 
927  if( !wxDirExists( backupPath ) )
928  {
929  wxLogTrace( traceSettings, "Backup path %s doesn't exist, creating it", backupPath );
930 
931  if( !wxMkdir( backupPath ) )
932  {
933  wxLogTrace( traceSettings, "Could not create backups path! Skipping backup" );
934  return false;
935  }
936  }
937 
938  wxDir dir( backupPath );
939 
940  if( !dir.IsOpened() )
941  {
942  wxLogTrace( traceSettings, "Could not open project backups path %s", dir.GetName() );
943  return false;
944  }
945 
946  std::vector<wxString> files;
947 
948  VECTOR_INSERT_TRAVERSER traverser( files,
949  [&modTime]( const wxString& aFile )
950  {
951  return modTime( aFile ).IsValid();
952  } );
953 
954  dir.Traverse( traverser, wxT( "*.zip" ) );
955 
956  // Sort newest-first
957  std::sort( files.begin(), files.end(),
958  [&]( const wxString& aFirst, const wxString& aSecond ) -> bool
959  {
960  wxDateTime first = modTime( aFirst );
961  wxDateTime second = modTime( aSecond );
962 
963  return first.GetTicks() > second.GetTicks();
964  } );
965 
966  // Do we even need to back up?
967  if( !files.empty() )
968  {
969  wxDateTime lastTime = modTime( files[0] );
970 
971  if( lastTime.IsValid() )
972  {
973  wxTimeSpan delta = wxDateTime::Now() - modTime( files[0] );
974 
975  if( delta.IsShorterThan( wxTimeSpan::Seconds( settings.min_interval ) ) )
976  return true;
977  }
978  }
979 
980  // Now that we know a backup is needed, apply the retention policy
981 
982  // Step 1: if we're over the total file limit, remove the oldest
983  if( !files.empty() && settings.limit_total_files > 0 )
984  {
985  while( files.size() > static_cast<size_t>( settings.limit_total_files ) )
986  {
987  wxRemoveFile( files.back() );
988  files.pop_back();
989  }
990  }
991 
992  // Step 2: Stay under the total size limit
993  if( settings.limit_total_size > 0 )
994  {
995  wxULongLong totalSize = 0;
996 
997  for( const wxString& file : files )
998  totalSize += wxFileName::GetSize( file );
999 
1000  while( !files.empty() && totalSize > static_cast<wxULongLong>( settings.limit_total_size ) )
1001  {
1002  totalSize -= wxFileName::GetSize( files.back() );
1003  wxRemoveFile( files.back() );
1004  files.pop_back();
1005  }
1006  }
1007 
1008  // Step 3: Stay under the daily limit
1009  if( settings.limit_daily_files > 0 && files.size() > 1 )
1010  {
1011  wxDateTime day = modTime( files[0] );
1012  int num = 1;
1013 
1014  wxASSERT( day.IsValid() );
1015 
1016  std::vector<wxString> filesToDelete;
1017 
1018  for( size_t i = 1; i < files.size(); i++ )
1019  {
1020  wxDateTime dt = modTime( files[i] );
1021 
1022  if( dt.IsSameDate( day ) )
1023  {
1024  num++;
1025 
1026  if( num > settings.limit_daily_files )
1027  filesToDelete.emplace_back( files[i] );
1028  }
1029  else
1030  {
1031  day = dt;
1032  num = 1;
1033  }
1034  }
1035 
1036  for( const wxString& file : filesToDelete )
1037  wxRemoveFile( file );
1038  }
1039 
1040  return BackupProject( aReporter );
1041 }
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:128
int limit_daily_files
Maximum files to keep per day, 0 for unlimited.
const char * traceSettings
Flag to enable settings tracing.
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 SCH_EDIT_FRAME::doAutoSave(), PCB_EDIT_FRAME::doAutoSave(), and KICAD_MANAGER_FRAME::LoadProject().

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

723 {
724  if( !aProject || !m_projects.count( aProject->GetProjectFullName() ) )
725  return false;
726 
727  if( !unloadProjectFile( aProject, aSave ) )
728  return false;
729 
730  wxLogTrace( traceSettings, "Unload project %s", aProject->GetProjectFullName() );
731 
732  m_projects.erase( aProject->GetProjectFullName() );
733 
734  return true;
735 }
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 const wxString GetProjectFullName() const
Function GetProjectFullName returns the full path and name of the project.
Definition: project.cpp:116
const char * traceSettings
Flag to enable settings tracing.

References PROJECT::GetProjectFullName(), m_projects, traceSettings, and unloadProjectFile().

Referenced by PCB_EDIT_FRAME::Files_io_from_id(), KICAD_MANAGER_FRAME::LoadProject(), LoadProject(), DIALOG_SCHEMATIC_SETUP::OnAuxiliaryAction(), DIALOG_BOARD_SETUP::OnAuxiliaryAction(), SCH_EDIT_FRAME::OnImportProject(), KICAD_MANAGER_FRAME::OnUnarchiveFiles(), SCH_EDIT_FRAME::OpenProjectFiles(), PCB_EDIT_FRAME::OpenProjectFiles(), and PCB_EDIT_FRAME::SavePcbFile().

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

794 {
795  if( !aProject )
796  return false;
797 
798  wxString name = aProject->GetProjectFullName();
799 
800  if( !m_project_files.count( name ) )
801  return false;
802 
804 
805  auto it = std::find_if( m_settings.begin(), m_settings.end(),
806  [&file]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
807  {
808  return aPtr.get() == file;
809  } );
810 
811  if( it != m_settings.end() )
812  {
813  std::string projectPath = GetPathForSettingsFile( it->get() );
814 
815  FlushAndRelease( &aProject->GetLocalSettings(), aSave );
816 
817  if( aSave )
818  ( *it )->SaveToFile( projectPath );
819 
820  m_settings.erase( it );
821  }
822 
823  m_project_files.erase( name );
824 
825  return true;
826 }
VTBL_ENTRY PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:135
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
std::string GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Returns the path a given settings file should be loaded from / stored to.
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:116
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.

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

Referenced by UnloadProject().

Member Data Documentation

◆ backupDateTimeFormat

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

Definition at line 357 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 344 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 337 of file settings_manager.h.

Referenced by MigrateIfNeeded().

◆ m_migration_source

wxString SETTINGS_MANAGER::m_migration_source
private

Definition at line 346 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 349 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 355 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 352 of file settings_manager.h.

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