You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

457 lines
16 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2020 Jon Evans <jon@craftyjon.com>
  5. * Copyright (C) 2020-2021 KiCad Developers, see AUTHORS.txt for contributors.
  6. *
  7. * This program is free software: you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the
  9. * Free Software Foundation, either version 3 of the License, or (at your
  10. * option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #ifndef _SETTINGS_MANAGER_H
  21. #define _SETTINGS_MANAGER_H
  22. #include <algorithm>
  23. #include <typeinfo>
  24. #include <core/wx_stl_compat.h> // for wxString hash
  25. #include <settings/color_settings.h>
  26. class COLOR_SETTINGS;
  27. class COMMON_SETTINGS;
  28. class KIWAY;
  29. class PROJECT;
  30. class PROJECT_FILE;
  31. class REPORTER;
  32. class wxSingleInstanceChecker;
  33. /// Project settings path will be <projectname> + this
  34. #define PROJECT_BACKUPS_DIR_SUFFIX wxT( "-backups" )
  35. class SETTINGS_MANAGER
  36. {
  37. public:
  38. SETTINGS_MANAGER( bool aHeadless = false );
  39. ~SETTINGS_MANAGER();
  40. /**
  41. * @return true if settings load was successful
  42. */
  43. bool IsOK() { return m_ok; }
  44. /**
  45. * Associate this setting manager with the given Kiway.
  46. *
  47. * @param aKiway is the kiway this settings manager should use
  48. */
  49. void SetKiway( KIWAY* aKiway ) { m_kiway = aKiway; }
  50. /**
  51. * Takes ownership of the pointer passed in
  52. * @param aSettings is a settings object to register
  53. * @return a handle to the owned pointer
  54. */
  55. template<typename T>
  56. T* RegisterSettings( T* aSettings, bool aLoadNow = true )
  57. {
  58. return static_cast<T*>( registerSettings( aSettings, aLoadNow ) );
  59. }
  60. void Load();
  61. void Load( JSON_SETTINGS* aSettings );
  62. void Save();
  63. void Save( JSON_SETTINGS* aSettings );
  64. /**
  65. * If the given settings object is registered, save it to disk and unregister it
  66. * @param aSettings is the object to release
  67. */
  68. void FlushAndRelease( JSON_SETTINGS* aSettings, bool aSave = true );
  69. /**
  70. * Returns a handle to the a given settings by type
  71. * If the settings have already been loaded, returns the existing pointer.
  72. * If the settings have not been loaded, creates a new object owned by the
  73. * settings manager and returns a pointer to it.
  74. *
  75. * @tparam T is a type derived from APP_SETTINGS_BASE
  76. * @param aLoadNow is true to load the registered file from disk immediately
  77. * @return a pointer to a loaded settings object
  78. */
  79. template<typename T>
  80. T* GetAppSettings( bool aLoadNow = true )
  81. {
  82. T* ret = nullptr;
  83. size_t typeHash = typeid( T ).hash_code();
  84. if( m_app_settings_cache.count( typeHash ) )
  85. ret = dynamic_cast<T*>( m_app_settings_cache.at( typeHash ) );
  86. if( ret )
  87. return ret;
  88. auto it = std::find_if( m_settings.begin(), m_settings.end(),
  89. []( const std::unique_ptr<JSON_SETTINGS>& aSettings )
  90. {
  91. return dynamic_cast<T*>( aSettings.get() );
  92. } );
  93. if( it != m_settings.end() )
  94. {
  95. ret = dynamic_cast<T*>( it->get() );
  96. }
  97. else
  98. {
  99. try
  100. {
  101. ret = static_cast<T*>( RegisterSettings( new T, aLoadNow ) );
  102. }
  103. catch( ... )
  104. {
  105. }
  106. }
  107. m_app_settings_cache[typeHash] = ret;
  108. return ret;
  109. }
  110. /**
  111. * Retrieves a color settings object that applications can read colors from.
  112. * If the given settings file cannot be found, returns the default settings.
  113. *
  114. * @param aName is the name of the color scheme to load
  115. * @return a loaded COLOR_SETTINGS object
  116. */
  117. COLOR_SETTINGS* GetColorSettings( const wxString& aName = "user" );
  118. std::vector<COLOR_SETTINGS*> GetColorSettingsList()
  119. {
  120. std::vector<COLOR_SETTINGS*> ret;
  121. for( const std::pair<const wxString, COLOR_SETTINGS*>& entry : m_color_settings )
  122. ret.push_back( entry.second );
  123. std::sort( ret.begin(), ret.end(), []( COLOR_SETTINGS* a, COLOR_SETTINGS* b )
  124. {
  125. return a->GetName() < b->GetName();
  126. } );
  127. return ret;
  128. }
  129. /**
  130. * Safely saves a COLOR_SETTINGS to disk, preserving any changes outside the given namespace.
  131. *
  132. * A color settings namespace is one of the top-level JSON objects like "board", etc.
  133. * This will perform a read-modify-write
  134. *
  135. * @param aSettings is a pointer to a valid COLOR_SETTINGS object managed by SETTINGS_MANAGER
  136. * @param aNamespace is the namespace of settings to save
  137. */
  138. void SaveColorSettings( COLOR_SETTINGS* aSettings, const std::string& aNamespace = "" );
  139. /**
  140. * Registers a new color settings object with the given filename
  141. * @param aFilename is the location to store the new settings object
  142. * @return a pointer to the new object
  143. */
  144. COLOR_SETTINGS* AddNewColorSettings( const wxString& aFilename );
  145. /**
  146. * Returns a color theme for storing colors migrated from legacy (5.x and earlier) settings,
  147. * creating the theme if necessary. This theme will be called "user.json" / "User".
  148. * @return the color settings to be used for migrating legacy settings
  149. */
  150. COLOR_SETTINGS* GetMigratedColorSettings();
  151. /**
  152. * Retrieves the common settings shared by all applications
  153. * @return a pointer to a loaded COMMON_SETTINGS
  154. */
  155. COMMON_SETTINGS* GetCommonSettings() const { return m_common_settings; }
  156. /**
  157. * Returns the path a given settings file should be loaded from / stored to.
  158. * @param aSettings is the settings object
  159. * @return a path based on aSettings->m_location
  160. */
  161. wxString GetPathForSettingsFile( JSON_SETTINGS* aSettings );
  162. /**
  163. * Handles the initialization of the user settings directory and migration from previous
  164. * KiCad versions as needed.
  165. *
  166. * This method will check for the existence of the user settings path for this KiCad version.
  167. * If it exists, settings load will proceed normally using that path.
  168. *
  169. * If that directory is empty or does not exist, the migration wizard will be launched, which
  170. * will give users the option to migrate settings from a previous KiCad version (if one is
  171. * found), manually specify a directory to migrate fromm, or start with default settings.
  172. *
  173. * @return true if migration was successful or not necessary, false otherwise
  174. */
  175. bool MigrateIfNeeded();
  176. /**
  177. * Helper for DIALOG_MIGRATE_SETTINGS to specify a source for migration
  178. * @param aSource is a directory containing settings files to migrate from (can be empty)
  179. */
  180. void SetMigrationSource( const wxString& aSource ) { m_migration_source = aSource; }
  181. void SetMigrateLibraryTables( bool aMigrate = true ) { m_migrateLibraryTables = aMigrate; }
  182. /**
  183. * Retrieves the name of the most recent previous KiCad version that can be found in the
  184. * user settings directory. For legacy versions (5.x, and 5.99 builds before this code was
  185. * written), this will return "5.x"
  186. *
  187. * @param aName is filled with the name of the previous version, if one exists
  188. * @return true if a previous version to migrate from exists
  189. */
  190. bool GetPreviousVersionPaths( std::vector<wxString>* aName = nullptr );
  191. /**
  192. * Re-scans the color themes directory, reloading any changes it finds.
  193. */
  194. void ReloadColorSettings();
  195. /**
  196. * Loads a project or sets up a new project with a specified path
  197. * @param aFullPath is the full path to the project
  198. * @param aSetActive if true will set the loaded project as the active project
  199. * @return true if the PROJECT_FILE was successfully loaded from disk
  200. */
  201. bool LoadProject( const wxString& aFullPath, bool aSetActive = true );
  202. /**
  203. * Saves, unloads and unregisters the given PROJECT
  204. * @param aProject is the project object to unload
  205. * @param aSave if true will save the project before unloading
  206. * @return true if the PROJECT file was successfully saved
  207. */
  208. bool UnloadProject( PROJECT* aProject, bool aSave = true );
  209. /**
  210. * Helper for checking if we have a project open
  211. * TODO: This should be deprecated along with Prj() once we support multiple projects fully
  212. * @return true if a call to Prj() will succeed
  213. */
  214. bool IsProjectOpen() const;
  215. /**
  216. * A helper while we are not MDI-capable -- return the one and only project
  217. * @return the loaded project
  218. */
  219. PROJECT& Prj() const;
  220. /**
  221. * Retrieves a loaded project by name
  222. * @param aFullPath is the full path including name and extension to the project file
  223. * @return a pointer to the project if loaded, or nullptr
  224. */
  225. PROJECT* GetProject( const wxString& aFullPath ) const;
  226. /**
  227. * @return a list of open projects
  228. */
  229. std::vector<wxString> GetOpenProjects() const;
  230. /**
  231. * Saves a loaded project.
  232. * @param aFullPath is the project name to save. If empty, will save the first loaded project.
  233. * @param aProject is the project to save, or nullptr to save the active project (Prj() return)
  234. * @return true if save was successful
  235. */
  236. bool SaveProject( const wxString& aFullPath = wxEmptyString, PROJECT* aProject = nullptr );
  237. /**
  238. * Sets the currently loaded project path and saves it (pointers remain valid)
  239. * Note that this will not modify the read-only state of the project, so it will have no effect
  240. * if the project is marked as read-only!
  241. * @param aFullPath is the full filename to set for the project
  242. * @param aProject is the project to save, or nullptr to save the active project (Prj() return)
  243. */
  244. void SaveProjectAs( const wxString& aFullPath, PROJECT* aProject = nullptr );
  245. /**
  246. * Saves a copy of the current project under the given path. Will save the copy even if the
  247. * current project is marked as read-only.
  248. * @param aFullPath is the full filename to set for the project
  249. * @param aProject is the project to save, or nullptr to save the active project (Prj() return)
  250. */
  251. void SaveProjectCopy( const wxString& aFullPath, PROJECT* aProject = nullptr );
  252. /**
  253. * @return the full path to where project backups should be stored
  254. */
  255. wxString GetProjectBackupsPath() const;
  256. /**
  257. * Creates a backup archive of the current project
  258. * @param aReporter is used for progress reporting
  259. * @return true if everything succeeded
  260. */
  261. bool BackupProject( REPORTER& aReporter ) const;
  262. /**
  263. * Calls BackupProject if a new backup is needed according to the current backup policy.
  264. * @param aReporter is used for progress reporting
  265. * @return if everything succeeded
  266. */
  267. bool TriggerBackupIfNeeded( REPORTER& aReporter ) const;
  268. /**
  269. * Checks if a given path is probably a valid KiCad configuration directory.
  270. * Actually it just checks if a file called "kicad_common" exists, because that's probably
  271. * good enough for now.
  272. *
  273. * @param aPath is the path to check
  274. * @return true if the path contains KiCad settings
  275. */
  276. static bool IsSettingsPathValid( const wxString& aPath );
  277. /**
  278. * Returns the path where color scheme files are stored; creating it if missing
  279. * (normally ./colors/ under the user settings path)
  280. */
  281. static wxString GetColorSettingsPath();
  282. /**
  283. * Return the user configuration path used to store KiCad's configuration files.
  284. *
  285. * @see calculateUserSettingsPath
  286. *
  287. * NOTE: The path is cached at startup, it will never change during program lifetime!
  288. *
  289. * @return A string containing the config path for Kicad
  290. */
  291. static wxString GetUserSettingsPath();
  292. /**
  293. * Parses the current KiCad build version and extracts the major and minor revision to use
  294. * as the name of the settings directory for this KiCad version.
  295. *
  296. * @return a string such as "5.1"
  297. */
  298. static std::string GetSettingsVersion();
  299. private:
  300. JSON_SETTINGS* registerSettings( JSON_SETTINGS* aSettings, bool aLoadNow = true );
  301. /**
  302. * Determines the base path for user settings files.
  303. *
  304. * The configuration path order of precedence is determined by the following criteria:
  305. *
  306. * - The value of the KICAD_CONFIG_HOME environment variable
  307. * - The value of the XDG_CONFIG_HOME environment variable.
  308. * - The result of the call to wxStandardPaths::GetUserConfigDir() with ".config" appended
  309. * as required on Linux builds.
  310. *
  311. * @param aIncludeVer will append the current KiCad version if true (default)
  312. * @param aUseEnv will prefer the base path found in the KICAD_CONFIG_DIR if found (default)
  313. * @return A string containing the config path for Kicad
  314. */
  315. static wxString calculateUserSettingsPath( bool aIncludeVer = true, bool aUseEnv = true );
  316. /**
  317. * Compares two settings versions, like "5.99" and "6.0"
  318. * @return -1 if aFirst is older than aSecond, 1 if aFirst is newer than aSecond, 0 otherwise
  319. */
  320. static int compareVersions( const std::string& aFirst, const std::string& aSecond );
  321. /**
  322. * Extracts the numeric version from a given settings string
  323. * @param aVersionString is the string to split at the "."
  324. * @param aMajor will store the first part
  325. * @param aMinor will store the second part
  326. * @return true if extraction succeeded
  327. */
  328. static bool extractVersion( const std::string& aVersionString, int* aMajor, int* aMinor );
  329. /**
  330. * Attempts to load a color theme by name (the color theme directory and .json ext are assumed)
  331. * @param aName is the filename of the color theme (without the extension or path)
  332. * @return the loaded settings, or nullptr if load failed
  333. */
  334. COLOR_SETTINGS* loadColorSettingsByName( const wxString& aName );
  335. COLOR_SETTINGS* registerColorSettings( const wxString& aFilename, bool aAbsolutePath = false );
  336. void loadAllColorSettings();
  337. /**
  338. * Registers a PROJECT_FILE and attempts to load it from disk
  339. * @param aProject is the project object to load the file for
  340. * @return true if the PROJECT_FILE was successfully loaded
  341. */
  342. bool loadProjectFile( PROJECT& aProject );
  343. /**
  344. * Optionally saves, and then unloads and unregisters the given PROJECT_FILE
  345. * @param aProject is the project object to unload the file for
  346. * @param aSave if true will save the project file before unloading
  347. * @return true if the PROJECT file was successfully saved
  348. */
  349. bool unloadProjectFile( PROJECT* aProject, bool aSave );
  350. private:
  351. /// True if running outside a UI context
  352. bool m_headless;
  353. /// The kiway this settings manager interacts with
  354. KIWAY* m_kiway;
  355. std::vector<std::unique_ptr<JSON_SETTINGS>> m_settings;
  356. std::unordered_map<wxString, COLOR_SETTINGS*> m_color_settings;
  357. /// Cache for app settings
  358. std::unordered_map<size_t, JSON_SETTINGS*> m_app_settings_cache;
  359. // Convenience shortcut
  360. COMMON_SETTINGS* m_common_settings;
  361. wxString m_migration_source;
  362. /// If true, the symbol and footprint library tables will be migrated from the previous version
  363. bool m_migrateLibraryTables;
  364. /// True if settings loaded successfully at construction
  365. bool m_ok;
  366. /// Loaded projects (ownership here)
  367. std::vector<std::unique_ptr<PROJECT>> m_projects_list;
  368. /// Loaded projects, mapped according to project full name
  369. std::map<wxString, PROJECT*> m_projects;
  370. /// Loaded project files, mapped according to project full name
  371. std::map<wxString, PROJECT_FILE*> m_project_files;
  372. /// Lock for loaded project (expand to multiple once we support MDI)
  373. std::unique_ptr<wxSingleInstanceChecker> m_project_lock;
  374. static wxString backupDateTimeFormat;
  375. };
  376. #endif