KiCad PCB EDA Suite
Loading...
Searching...
No Matches
settings_manager.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2020 Jon Evans <[email protected]>
5 * Copyright The 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
22#include <regex>
23#include <wx/debug.h>
24#include <wx/dir.h>
25#include <wx/filename.h>
26#include <wx/snglinst.h>
27#include <wx/stdpaths.h>
28#include <wx/utils.h>
29
30#include <build_version.h>
31#include <confirm.h>
33#include <gestfich.h>
35#include <kiplatform/io.h>
36#include <kiway.h>
37#include <lockfile.h>
38#include <macros.h>
39#include <pgm_base.h>
40#include <paths.h>
41#include <project.h>
50#include <env_vars.h>
51
52
54 m_headless( aHeadless ),
55 m_kiway( nullptr ),
56 m_common_settings( nullptr ),
57 m_migration_source(),
58 m_migrateLibraryTables( true )
59{
60 // Check if the settings directory already exists, and if not, perform a migration if possible
61 if( !MigrateIfNeeded() )
62 {
63 m_ok = false;
64 return;
65 }
66
67 m_ok = true;
68
69 // create the common settings shared by all applications. Not loaded immediately
71
72 // Create the built-in color settings
73 // Here to allow the Python API to access the built-in colors
75
76 wxFileName commonSettings( GetPathForSettingsFile( m_common_settings ),
78
79 if( !wxFileExists( commonSettings.GetFullPath() ) )
80 {
83 }
84}
85
86
88{
89 for( std::unique_ptr<PROJECT>& project : m_projects_list )
90 project.reset();
91
92 m_projects.clear();
93
94 for( std::unique_ptr<JSON_SETTINGS>& settings : m_settings )
95 settings.reset();
96
97 m_settings.clear();
98
99 m_color_settings.clear();
100}
101
102
104{
105 std::unique_ptr<JSON_SETTINGS> ptr( aSettings );
106
107 ptr->SetManager( this );
108
109 wxLogTrace( traceSettings, wxT( "Registered new settings object <%s>" ),
110 ptr->GetFullFilename() );
111
112 if( aLoadNow )
113 ptr->LoadFromFile( GetPathForSettingsFile( ptr.get() ) );
114
115 m_settings.push_back( std::move( ptr ) );
116 return m_settings.back().get();
117}
118
119
121{
122 // TODO(JE) We should check for dirty settings here and write them if so, because
123 // Load() could be called late in the application lifecycle
124 std::vector<JSON_SETTINGS*> toLoad;
125
126 // Cache a copy of raw pointers; m_settings may be modified during the load loop
127 std::transform( m_settings.begin(), m_settings.end(), std::back_inserter( toLoad ),
128 []( std::unique_ptr<JSON_SETTINGS>& aSettings )
129 {
130 return aSettings.get();
131 } );
132
133 for( JSON_SETTINGS* settings : toLoad )
134 settings->LoadFromFile( GetPathForSettingsFile( settings ) );
135}
136
137
139{
140 auto it = std::find_if( m_settings.begin(), m_settings.end(),
141 [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
142 {
143 return aPtr.get() == aSettings;
144 } );
145
146 if( it != m_settings.end() )
147 ( *it )->LoadFromFile( GetPathForSettingsFile( it->get() ) );
148}
149
150
152{
153 for( auto&& settings : m_settings )
154 {
155 // Never automatically save color settings, caller should use SaveColorSettings
156 if( dynamic_cast<COLOR_SETTINGS*>( settings.get() ) )
157 continue;
158
159 settings->SaveToFile( GetPathForSettingsFile( settings.get() ) );
160 }
161}
162
163
165{
166 auto it = std::find_if( m_settings.begin(), m_settings.end(),
167 [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
168 {
169 return aPtr.get() == aSettings;
170 } );
171
172 if( it != m_settings.end() )
173 {
174 wxLogTrace( traceSettings, wxT( "Saving %s" ), ( *it )->GetFullFilename() );
175 ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
176 }
177}
178
179
181{
182 auto it = std::find_if( m_settings.begin(), m_settings.end(),
183 [&aSettings]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
184 {
185 return aPtr.get() == aSettings;
186 } );
187
188 if( it != m_settings.end() )
189 {
190 wxLogTrace( traceSettings, wxT( "Flush and release %s" ), ( *it )->GetFullFilename() );
191
192 if( aSave )
193 ( *it )->SaveToFile( GetPathForSettingsFile( it->get() ) );
194
195 JSON_SETTINGS* tmp = it->get(); // We use a temporary to suppress a Clang warning
196 size_t typeHash = typeid( *tmp ).hash_code();
197
198 if( m_app_settings_cache.count( typeHash ) )
199 m_app_settings_cache.erase( typeHash );
200
201 m_settings.erase( it );
202 }
203}
204
205
207{
208 // Find settings the fast way
209 if( m_color_settings.count( aName ) )
210 return m_color_settings.at( aName );
211
212 // Maybe it's the display name (cli is one method of invoke)
213 auto it = std::find_if( m_color_settings.begin(), m_color_settings.end(),
214 [&aName]( const std::pair<wxString, COLOR_SETTINGS*>& p )
215 {
216 return p.second->GetName().Lower() == aName.Lower();
217 } );
218
219 if( it != m_color_settings.end() )
220 {
221 return it->second;
222 }
223
224 // No match? See if we can load it
225 if( !aName.empty() )
226 {
228
229 if( !ret )
230 {
231 ret = registerColorSettings( aName );
233 ret->SetFilename( wxT( "user" ) );
234 ret->SetReadOnly( false );
235 }
236
237 return ret;
238 }
239
240 // This had better work
242}
243
244
246{
247 wxLogTrace( traceSettings, wxT( "Attempting to load color theme %s" ), aName );
248
249 wxFileName fn( GetColorSettingsPath(), aName, wxS( "json" ) );
250
251 if( !fn.IsOk() || !fn.Exists() )
252 {
253 wxLogTrace( traceSettings, wxT( "Theme file %s.json not found, falling back to user" ),
254 aName );
255 return nullptr;
256 }
257
258 COLOR_SETTINGS* settings = RegisterSettings( new COLOR_SETTINGS( aName ) );
259
260 if( settings->GetFilename() != aName.ToStdString() )
261 {
262 wxLogTrace( traceSettings, wxT( "Warning: stored filename is actually %s, " ),
263 settings->GetFilename() );
264 }
265
266 m_color_settings[aName] = settings;
267
268 return settings;
269}
270
271
272class JSON_DIR_TRAVERSER : public wxDirTraverser
273{
274private:
275 std::function<void( const wxFileName& )> m_action;
276
277public:
278 explicit JSON_DIR_TRAVERSER( std::function<void( const wxFileName& )> aAction )
279 : m_action( std::move( aAction ) )
280 {
281 }
282
283 wxDirTraverseResult OnFile( const wxString& aFilePath ) override
284 {
285 wxFileName file( aFilePath );
286
287 if( file.GetExt() == wxS( "json" ) )
288 m_action( file );
289
290 return wxDIR_CONTINUE;
291 }
292
293 wxDirTraverseResult OnDir( const wxString& dirPath ) override
294 {
295 return wxDIR_CONTINUE;
296 }
297};
298
299
300COLOR_SETTINGS* SETTINGS_MANAGER::registerColorSettings( const wxString& aName, bool aAbsolutePath )
301{
302 if( !m_color_settings.count( aName ) )
303 {
304 COLOR_SETTINGS* colorSettings = RegisterSettings( new COLOR_SETTINGS( aName,
305 aAbsolutePath ) );
306 m_color_settings[aName] = colorSettings;
307 }
308
309 return m_color_settings.at( aName );
310}
311
312
314{
315 if( aName.EndsWith( wxT( ".json" ) ) )
316 return registerColorSettings( aName.BeforeLast( '.' ) );
317 else
318 return registerColorSettings( aName );
319}
320
321
323{
324 if( !m_color_settings.count( "user" ) )
325 {
326 COLOR_SETTINGS* settings = registerColorSettings( wxT( "user" ) );
327 settings->SetName( wxT( "User" ) );
328 Save( settings );
329 }
330
331 return m_color_settings.at( "user" );
332}
333
334
336{
338 m_color_settings[settings->GetFilename()] = RegisterSettings( settings, false );
339}
340
341
343{
344 // Create the built-in color settings
346
347 wxFileName third_party_path;
348 const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
349 auto it = env.find( ENV_VAR::GetVersionedEnvVarName( wxS( "3RD_PARTY" ) ) );
350
351 if( it != env.end() && !it->second.GetValue().IsEmpty() )
352 third_party_path.SetPath( it->second.GetValue() );
353 else
354 third_party_path.SetPath( PATHS::GetDefault3rdPartyPath() );
355
356 third_party_path.AppendDir( wxS( "colors" ) );
357
358 // PCM-managed themes
359 wxDir third_party_colors_dir( third_party_path.GetFullPath() );
360
361 // System-installed themes
362 wxDir system_colors_dir( PATHS::GetStockDataPath( false ) + "/colors" );
363
364 // User-created themes
365 wxDir colors_dir( GetColorSettingsPath() );
366
367 // Search for and load any other settings
368 JSON_DIR_TRAVERSER loader( [&]( const wxFileName& aFilename )
369 {
370 registerColorSettings( aFilename.GetName() );
371 } );
372
373 JSON_DIR_TRAVERSER readOnlyLoader(
374 [&]( const wxFileName& aFilename )
375 {
376 COLOR_SETTINGS* settings = registerColorSettings( aFilename.GetFullPath(), true );
377 settings->SetReadOnly( true );
378 } );
379
380 if( system_colors_dir.IsOpened() )
381 system_colors_dir.Traverse( readOnlyLoader );
382
383 if( third_party_colors_dir.IsOpened() )
384 third_party_colors_dir.Traverse( readOnlyLoader );
385
386 if( colors_dir.IsOpened() )
387 colors_dir.Traverse( loader );
388}
389
390
392{
393 m_color_settings.clear();
395}
396
397
398void SETTINGS_MANAGER::SaveColorSettings( COLOR_SETTINGS* aSettings, const std::string& aNamespace )
399{
400 // The passed settings should already be managed
401 wxASSERT( std::find_if( m_color_settings.begin(), m_color_settings.end(),
402 [aSettings] ( const std::pair<wxString, COLOR_SETTINGS*>& el )
403 {
404 return el.second->GetFilename() == aSettings->GetFilename();
405 }
406 ) != m_color_settings.end() );
407
408 if( aSettings->IsReadOnly() )
409 return;
410
411 if( !aSettings->Store() )
412 {
413 wxLogTrace( traceSettings, wxT( "Color scheme %s not modified; skipping save" ),
414 aNamespace );
415 return;
416 }
417
418 wxASSERT( aSettings->Contains( aNamespace ) );
419
420 wxLogTrace( traceSettings, wxT( "Saving color scheme %s, preserving %s" ),
421 aSettings->GetFilename(),
422 aNamespace );
423
424 std::optional<nlohmann::json> backup = aSettings->GetJson( aNamespace );
425 wxString path = GetColorSettingsPath();
426
427 aSettings->LoadFromFile( path );
428
429 if( backup )
430 ( *aSettings->Internals() )[aNamespace].update( *backup );
431
432 aSettings->Load();
433
434 aSettings->SaveToFile( path, true );
435}
436
437
439{
440 wxASSERT( aSettings );
441
442 switch( aSettings->GetLocation() )
443 {
444 case SETTINGS_LOC::USER:
446
447 case SETTINGS_LOC::PROJECT:
448 // TODO: MDI support
449 return Prj().GetProjectPath();
450
451 case SETTINGS_LOC::COLORS:
452 return GetColorSettingsPath();
453
454 case SETTINGS_LOC::NONE:
455 return "";
456
457 default:
458 wxASSERT_MSG( false, wxT( "Unknown settings location!" ) );
459 }
460
461 return "";
462}
463
464
465class MIGRATION_TRAVERSER : public wxDirTraverser
466{
467private:
468 wxString m_src;
469 wxString m_dest;
470 wxString m_errors;
472
473public:
474 MIGRATION_TRAVERSER( const wxString& aSrcDir, const wxString& aDestDir, bool aMigrateTables ) :
475 m_src( aSrcDir ),
476 m_dest( aDestDir ),
477 m_migrateTables( aMigrateTables )
478 {
479 }
480
481 wxString GetErrors() { return m_errors; }
482
483 wxDirTraverseResult OnFile( const wxString& aSrcFilePath ) override
484 {
485 wxFileName file( aSrcFilePath );
486
487 if( !m_migrateTables && ( file.GetName() == FILEEXT::SymbolLibraryTableFileName ||
488 file.GetName() == FILEEXT::FootprintLibraryTableFileName ) )
489 {
490 return wxDIR_CONTINUE;
491 }
492
493 // Skip migrating PCM installed packages as packages themselves are not moved
494 if( file.GetFullName() == wxT( "installed_packages.json" ) )
495 return wxDIR_CONTINUE;
496
497 // Don't migrate hotkeys config files; we don't have a reasonable migration handler for them
498 // and so there is no way to resolve conflicts at the moment
499 if( file.GetExt() == wxT( "hotkeys" ) )
500 return wxDIR_CONTINUE;
501
502 wxString path = file.GetPath();
503
504 path.Replace( m_src, m_dest, false );
505 file.SetPath( path );
506
507 wxLogTrace( traceSettings, wxT( "Copying %s to %s" ), aSrcFilePath, file.GetFullPath() );
508
509 // For now, just copy everything
510 KiCopyFile( aSrcFilePath, file.GetFullPath(), m_errors );
511
512 return wxDIR_CONTINUE;
513 }
514
515 wxDirTraverseResult OnDir( const wxString& dirPath ) override
516 {
517 wxFileName dir( dirPath );
518
519 // Whitelist of directories to migrate
520 if( dir.GetName() == wxS( "colors" ) ||
521 dir.GetName() == wxS( "3d" ) )
522 {
523
524 wxString path = dir.GetPath();
525
526 path.Replace( m_src, m_dest, false );
527 dir.SetPath( path );
528
529 wxMkdir( dir.GetFullPath() );
530
531 return wxDIR_CONTINUE;
532 }
533 else
534 {
535 return wxDIR_IGNORE;
536 }
537 }
538};
539
540
542{
543 wxFileName path( PATHS::GetUserSettingsPath(), wxS( "" ) );
544 wxLogTrace( traceSettings, wxT( "Using settings path %s" ), path.GetFullPath() );
545
546 if( m_headless )
547 {
548 // Special case namely for cli
549 // Ensure the settings directory at least exists to prevent additional loading errors
550 // from subdirectories.
551 // TODO review headless (unit tests) vs cli needs, this should be fine for unit tests though
552 if( !path.DirExists() )
553 {
554 wxLogTrace( traceSettings, wxT( "Path didn't exist; creating it" ) );
555 path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
556 }
557
558 wxLogTrace( traceSettings, wxT( "Settings migration not checked; running headless" ) );
559 return true;
560 }
561
562 if( path.DirExists() )
563 {
564 wxFileName common = path;
565 common.SetName( wxS( "kicad_common" ) );
566 common.SetExt( wxS( "json" ) );
567
568 if( common.Exists() )
569 {
570 wxLogTrace( traceSettings, wxT( "Path exists and has a kicad_common, continuing!" ) );
571 return true;
572 }
573 }
574
575 // Now we have an empty path, let's figure out what to put in it
576 DIALOG_MIGRATE_SETTINGS dlg( this );
577
578 if( dlg.ShowModal() != wxID_OK )
579 {
580 wxLogTrace( traceSettings, wxT( "Migration dialog canceled; exiting" ) );
581 return false;
582 }
583
584 if( !path.DirExists() )
585 {
586 wxLogTrace( traceSettings, wxT( "Path didn't exist; creating it" ) );
587 path.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
588 }
589
590 if( m_migration_source.IsEmpty() )
591 {
592 wxLogTrace( traceSettings, wxT( "No migration source given; starting with defaults" ) );
593 return true;
594 }
595
596 wxLogTrace( traceSettings, wxT( "Migrating from path %s" ), m_migration_source );
597
599 wxDir source_dir( m_migration_source );
600
601 source_dir.Traverse( traverser );
602
603 if( !traverser.GetErrors().empty() )
604 DisplayErrorMessage( nullptr, traverser.GetErrors() );
605
606 // Remove any library configuration if we didn't choose to import
608 {
609 COMMON_SETTINGS common;
610 wxString commonPath = GetPathForSettingsFile( &common );
611 common.LoadFromFile( commonPath );
612
613 const std::vector<wxString> libKeys = {
614 wxT( "KICAD6_SYMBOL_DIR" ),
615 wxT( "KICAD6_3DMODEL_DIR" ),
616 wxT( "KICAD6_FOOTPRINT_DIR" ),
617 wxT( "KICAD6_TEMPLATE_DIR" ), // Stores the default library table to be copied
618 wxT( "KICAD7_SYMBOL_DIR" ),
619 wxT( "KICAD7_3DMODEL_DIR" ),
620 wxT( "KICAD7_FOOTPRINT_DIR" ),
621 wxT( "KICAD7_TEMPLATE_DIR" ),
622 wxT( "KICAD8_SYMBOL_DIR" ),
623 wxT( "KICAD8_3DMODEL_DIR" ),
624 wxT( "KICAD8_FOOTPRINT_DIR" ),
625 wxT( "KICAD8_TEMPLATE_DIR" ),
626
627 // Deprecated keys
628 wxT( "KICAD_PTEMPLATES" ),
629 wxT( "KISYS3DMOD" ),
630 wxT( "KISYSMOD" ),
631 wxT( "KICAD_SYMBOL_DIR" ),
632 };
633
634 for( const wxString& key : libKeys )
635 common.m_Env.vars.erase( key );
636
637 common.SaveToFile( commonPath );
638 }
639
640 return true;
641}
642
643
644bool SETTINGS_MANAGER::GetPreviousVersionPaths( std::vector<wxString>* aPaths )
645{
646 wxASSERT( aPaths );
647
648 aPaths->clear();
649
650 wxDir dir;
651 std::vector<wxFileName> base_paths;
652
653 base_paths.emplace_back( wxFileName( PATHS::CalculateUserSettingsPath( false ), wxS( "" ) ) );
654
655 // If the env override is set, also check the default paths
656 if( wxGetEnv( wxT( "KICAD_CONFIG_HOME" ), nullptr ) )
657 base_paths.emplace_back( wxFileName( PATHS::CalculateUserSettingsPath( false, false ),
658 wxS( "" ) ) );
659
660#ifdef __WXGTK__
661 // When running inside FlatPak, KIPLATFORM::ENV::GetUserConfigPath() will return a sandboxed
662 // path. In case the user wants to move from non-FlatPak KiCad to FlatPak KiCad, let's add our
663 // best guess as to the non-FlatPak config path. Unfortunately FlatPak also hides the host
664 // XDG_CONFIG_HOME, so if the user customizes their config path, they will have to browse
665 // for it.
666 {
667 wxFileName wxGtkPath;
668 wxGtkPath.AssignDir( wxS( "~/.config/kicad" ) );
669 wxGtkPath.MakeAbsolute();
670 base_paths.emplace_back( wxGtkPath );
671
672 // We also want to pick up regular flatpak if we are nightly
673 wxGtkPath.AssignDir( wxS( "~/.var/app/org.kicad.KiCad/config/kicad" ) );
674 wxGtkPath.MakeAbsolute();
675 base_paths.emplace_back( wxGtkPath );
676 }
677#endif
678
679 wxString subdir;
680 std::string mine = GetSettingsVersion();
681
682 auto check_dir = [&] ( const wxString& aSubDir )
683 {
684 // Only older versions are valid for migration
685 if( compareVersions( aSubDir.ToStdString(), mine ) <= 0 )
686 {
687 wxString sub_path = dir.GetNameWithSep() + aSubDir;
688
689 if( IsSettingsPathValid( sub_path ) )
690 {
691 aPaths->push_back( sub_path );
692 wxLogTrace( traceSettings, wxT( "GetPreviousVersionName: %s is valid" ), sub_path );
693 }
694 }
695 };
696
697 std::set<wxString> checkedPaths;
698
699 for( const wxFileName& base_path : base_paths )
700 {
701 if( checkedPaths.count( base_path.GetFullPath() ) )
702 continue;
703
704 checkedPaths.insert( base_path.GetFullPath() );
705
706 if( !dir.Open( base_path.GetFullPath() ) )
707 {
708 wxLogTrace( traceSettings, wxT( "GetPreviousVersionName: could not open base path %s" ),
709 base_path.GetFullPath() );
710 continue;
711 }
712
713 wxLogTrace( traceSettings, wxT( "GetPreviousVersionName: checking base path %s" ),
714 base_path.GetFullPath() );
715
716 if( dir.GetFirst( &subdir, wxEmptyString, wxDIR_DIRS ) )
717 {
718 if( subdir != mine )
719 check_dir( subdir );
720
721 while( dir.GetNext( &subdir ) )
722 {
723 if( subdir != mine )
724 check_dir( subdir );
725 }
726 }
727
728 // If we didn't find one yet, check for legacy settings without a version directory
729 if( IsSettingsPathValid( dir.GetNameWithSep() ) )
730 {
731 wxLogTrace( traceSettings,
732 wxT( "GetPreviousVersionName: root path %s is valid" ), dir.GetName() );
733 aPaths->push_back( dir.GetName() );
734 }
735 }
736
737 alg::delete_if( *aPaths, []( const wxString& aPath ) -> bool
738 {
739 wxFileName fulldir = wxFileName::DirName( aPath );
740 const wxArrayString& dirs = fulldir.GetDirs();
741
742 if( dirs.empty() || !fulldir.IsDirReadable() )
743 return true;
744
745 std::string ver = dirs.back().ToStdString();
746
747 if( !extractVersion( ver ) )
748 return true;
749
750 return false;
751 } );
752
753 std::sort( aPaths->begin(), aPaths->end(),
754 [&]( const wxString& a, const wxString& b ) -> bool
755 {
756 wxFileName aPath = wxFileName::DirName( a );
757 wxFileName bPath = wxFileName::DirName( b );
758
759 const wxArrayString& aDirs = aPath.GetDirs();
760 const wxArrayString& bDirs = bPath.GetDirs();
761
762 if( aDirs.empty() )
763 return false;
764
765 if( bDirs.empty() )
766 return true;
767
768 std::string verA = aDirs.back().ToStdString();
769 std::string verB = bDirs.back().ToStdString();
770
771 if( !extractVersion( verA ) )
772 return false;
773
774 if( !extractVersion( verB ) )
775 return true;
776
777 return compareVersions( verA, verB ) >= 0;
778 } );
779
780 return aPaths->size() > 0;
781}
782
783
784bool SETTINGS_MANAGER::IsSettingsPathValid( const wxString& aPath )
785{
786 wxFileName test( aPath, wxS( "kicad_common" ) );
787
788 if( test.Exists() )
789 return true;
790
791 test.SetExt( "json" );
792
793 return test.Exists();
794}
795
796
798{
799 wxFileName path;
800
801 path.AssignDir( PATHS::GetUserSettingsPath() );
802 path.AppendDir( wxS( "colors" ) );
803
804 if( !path.DirExists() )
805 {
806 if( !wxMkdir( path.GetPath() ) )
807 {
808 wxLogTrace( traceSettings,
809 wxT( "GetColorSettingsPath(): Path %s missing and could not be created!" ),
810 path.GetPath() );
811 }
812 }
813
814 return path.GetPath();
815}
816
817
819{
820 // CMake computes the major.minor string for us.
821 return GetMajorMinorVersion().ToStdString();
822}
823
824
825int SETTINGS_MANAGER::compareVersions( const std::string& aFirst, const std::string& aSecond )
826{
827 int a_maj = 0;
828 int a_min = 0;
829 int b_maj = 0;
830 int b_min = 0;
831
832 if( !extractVersion( aFirst, &a_maj, &a_min ) || !extractVersion( aSecond, &b_maj, &b_min ) )
833 {
834 wxLogTrace( traceSettings, wxT( "compareSettingsVersions: bad input (%s, %s)" ),
835 aFirst, aSecond );
836 return -1;
837 }
838
839 if( a_maj < b_maj )
840 {
841 return -1;
842 }
843 else if( a_maj > b_maj )
844 {
845 return 1;
846 }
847 else
848 {
849 if( a_min < b_min )
850 {
851 return -1;
852 }
853 else if( a_min > b_min )
854 {
855 return 1;
856 }
857 else
858 {
859 return 0;
860 }
861 }
862}
863
864
865bool SETTINGS_MANAGER::extractVersion( const std::string& aVersionString, int* aMajor, int* aMinor )
866{
867 std::regex re_version( "(\\d+)\\.(\\d+)" );
868 std::smatch match;
869
870 if( std::regex_match( aVersionString, match, re_version ) )
871 {
872 try
873 {
874 int major = std::stoi( match[1].str() );
875 int minor = std::stoi( match[2].str() );
876
877 if( aMajor )
878 *aMajor = major;
879
880 if( aMinor )
881 *aMinor = minor;
882 }
883 catch( ... )
884 {
885 return false;
886 }
887
888 return true;
889 }
890
891 return false;
892}
893
894
895bool SETTINGS_MANAGER::LoadProject( const wxString& aFullPath, bool aSetActive )
896{
897 // Normalize path to new format even if migrating from a legacy file
898 wxFileName path( aFullPath );
899
902
903 wxString fullPath = path.GetFullPath();
904
905 // If already loaded, we are all set. This might be called more than once over a project's
906 // lifetime in case the project is first loaded by the KiCad manager and then Eeschema or
907 // Pcbnew try to load it again when they are launched.
908 if( m_projects.count( fullPath ) )
909 return true;
910
911 bool readOnly = false;
912 LOCKFILE lockFile( fullPath );
913
914 if( !lockFile.Valid() )
915 {
916 wxLogTrace( traceSettings, wxT( "Project %s is locked; opening read-only" ), fullPath );
917 readOnly = true;
918 }
919
920 // No MDI yet
921 if( aSetActive && !m_projects.empty() )
922 {
923 PROJECT* oldProject = m_projects.begin()->second;
924 unloadProjectFile( oldProject, false );
925 m_projects.erase( m_projects.begin() );
926
927 auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
928 [&]( const std::unique_ptr<PROJECT>& ptr )
929 {
930 return ptr.get() == oldProject;
931 } );
932
933 wxASSERT( it != m_projects_list.end() );
934 m_projects_list.erase( it );
935 }
936
937 wxLogTrace( traceSettings, wxT( "Load project %s" ), fullPath );
938
939 std::unique_ptr<PROJECT> project = std::make_unique<PROJECT>();
940 project->setProjectFullName( fullPath );
941
942 if( aSetActive )
943 {
944 // until multiple projects are in play, set an environment variable for the
945 // the project pointer.
946 wxFileName projectPath( fullPath );
947 wxSetEnv( PROJECT_VAR_NAME, projectPath.GetPath() );
948
949 // set the cwd but don't impact kicad-cli
950 if( !projectPath.GetPath().IsEmpty() && wxTheApp && wxTheApp->IsGUI() )
951 wxSetWorkingDirectory( projectPath.GetPath() );
952 }
953
954 bool success = loadProjectFile( *project );
955
956 if( success )
957 {
958 project->SetReadOnly( readOnly || project->GetProjectFile().IsReadOnly() );
959
960 if( lockFile && aSetActive )
961 m_project_lock.reset( new LOCKFILE( std::move( lockFile ) ) );
962 }
963
964 m_projects_list.push_back( std::move( project ) );
965 m_projects[fullPath] = m_projects_list.back().get();
966
967 wxString fn( path.GetName() );
968
969 PROJECT_LOCAL_SETTINGS* settings = new PROJECT_LOCAL_SETTINGS( m_projects[fullPath], fn );
970
971 if( aSetActive )
972 settings = RegisterSettings( settings );
973 else
974 settings->LoadFromFile( path.GetPath() );
975
976 m_projects[fullPath]->setLocalSettings( settings );
977
978 if( aSetActive && m_kiway )
980
981 return success;
982}
983
984
985bool SETTINGS_MANAGER::UnloadProject( PROJECT* aProject, bool aSave )
986{
987 if( !aProject || !m_projects.count( aProject->GetProjectFullName() ) )
988 return false;
989
990 if( !unloadProjectFile( aProject, aSave ) )
991 return false;
992
993 wxString projectPath = aProject->GetProjectFullName();
994 wxLogTrace( traceSettings, wxT( "Unload project %s" ), projectPath );
995
996 PROJECT* toRemove = m_projects.at( projectPath );
997 bool wasActiveProject = m_projects_list.begin()->get() == toRemove;
998
999 auto it = std::find_if( m_projects_list.begin(), m_projects_list.end(),
1000 [&]( const std::unique_ptr<PROJECT>& ptr )
1001 {
1002 return ptr.get() == toRemove;
1003 } );
1004
1005 wxASSERT( it != m_projects_list.end() );
1006 m_projects_list.erase( it );
1007
1008 m_projects.erase( projectPath );
1009
1010 if( wasActiveProject )
1011 {
1012 // Immediately reload a null project; this is required until the rest of the application
1013 // is refactored to not assume that Prj() always works
1014 if( m_projects_list.empty() )
1015 LoadProject( "" );
1016
1017 // Remove the reference in the environment to the previous project
1018 wxSetEnv( PROJECT_VAR_NAME, wxS( "" ) );
1019
1020 // Release lock on the file, in case we had one
1021 m_project_lock = nullptr;
1022
1023 if( m_kiway )
1025 }
1026
1027 return true;
1028}
1029
1030
1032{
1033 // No MDI yet: First project in the list is the active project
1034 wxASSERT_MSG( m_projects_list.size(), wxT( "no project in list" ) );
1035 return *m_projects_list.begin()->get();
1036}
1037
1038
1040{
1041 return !m_projects.empty();
1042}
1043
1044
1046{
1047 return m_projects.size() > 1 || ( m_projects.size() == 1
1048 && !m_projects.begin()->second->GetProjectFullName().IsEmpty() );
1049}
1050
1051
1052PROJECT* SETTINGS_MANAGER::GetProject( const wxString& aFullPath ) const
1053{
1054 if( m_projects.count( aFullPath ) )
1055 return m_projects.at( aFullPath );
1056
1057 return nullptr;
1058}
1059
1060
1061std::vector<wxString> SETTINGS_MANAGER::GetOpenProjects() const
1062{
1063 std::vector<wxString> ret;
1064
1065 for( const std::pair<const wxString, PROJECT*>& pair : m_projects )
1066 {
1067 // Don't save empty projects (these are the default project settings)
1068 if( !pair.first.IsEmpty() )
1069 ret.emplace_back( pair.first );
1070 }
1071
1072 return ret;
1073}
1074
1075
1076bool SETTINGS_MANAGER::SaveProject( const wxString& aFullPath, PROJECT* aProject )
1077{
1078 if( !aProject )
1079 aProject = &Prj();
1080
1081 wxString path = aFullPath;
1082
1083 if( path.empty() )
1084 path = aProject->GetProjectFullName();
1085
1086 // TODO: refactor for MDI
1087 if( aProject->IsReadOnly() )
1088 return false;
1089
1090 if( !m_project_files.count( path ) )
1091 return false;
1092
1094 wxString projectPath = aProject->GetProjectPath();
1095
1096 project->SaveToFile( projectPath );
1097 aProject->GetLocalSettings().SaveToFile( projectPath );
1098
1099 return true;
1100}
1101
1102
1103void SETTINGS_MANAGER::SaveProjectAs( const wxString& aFullPath, PROJECT* aProject )
1104{
1105 if( !aProject )
1106 aProject = &Prj();
1107
1108 wxString oldName = aProject->GetProjectFullName();
1109
1110 if( aFullPath.IsSameAs( oldName ) )
1111 {
1112 SaveProject( aFullPath, aProject );
1113 return;
1114 }
1115
1116 // Changing this will cause UnloadProject to not save over the "old" project when loading below
1117 aProject->setProjectFullName( aFullPath );
1118
1119 wxFileName fn( aFullPath );
1120
1121 PROJECT_FILE* project = m_project_files.at( oldName );
1122
1123 // Ensure read-only flags are copied; this allows doing a "Save As" on a standalone board/sch
1124 // without creating project files if the checkbox is turned off
1125 project->SetReadOnly( aProject->IsReadOnly() );
1126 aProject->GetLocalSettings().SetReadOnly( aProject->IsReadOnly() );
1127
1128 project->SetFilename( fn.GetName() );
1129 project->SaveToFile( fn.GetPath() );
1130
1131 aProject->GetLocalSettings().SetFilename( fn.GetName() );
1132 aProject->GetLocalSettings().SaveToFile( fn.GetPath() );
1133
1134 m_project_files[fn.GetFullPath()] = project;
1135 m_project_files.erase( oldName );
1136
1137 m_projects[fn.GetFullPath()] = m_projects[oldName];
1138 m_projects.erase( oldName );
1139}
1140
1141
1142void SETTINGS_MANAGER::SaveProjectCopy( const wxString& aFullPath, PROJECT* aProject )
1143{
1144 if( !aProject )
1145 aProject = &Prj();
1146
1148 wxString oldName = project->GetFilename();
1149 wxFileName fn( aFullPath );
1150
1151 bool readOnly = project->IsReadOnly();
1152 project->SetReadOnly( false );
1153
1154 project->SetFilename( fn.GetName() );
1155 project->SaveToFile( fn.GetPath() );
1156 project->SetFilename( oldName );
1157
1158 PROJECT_LOCAL_SETTINGS& localSettings = aProject->GetLocalSettings();
1159
1160 localSettings.SetFilename( fn.GetName() );
1161 localSettings.SaveToFile( fn.GetPath() );
1162 localSettings.SetFilename( oldName );
1163
1164 project->SetReadOnly( readOnly );
1165}
1166
1167
1169{
1170 wxFileName fullFn( aProject.GetProjectFullName() );
1171 wxString fn( fullFn.GetName() );
1172
1173 PROJECT_FILE* file = RegisterSettings( new PROJECT_FILE( fn ), false );
1174
1175 m_project_files[aProject.GetProjectFullName()] = file;
1176
1177 aProject.setProjectFile( file );
1178 file->SetProject( &aProject );
1179
1180 wxString path( fullFn.GetPath() );
1181
1182 return file->LoadFromFile( path );
1183}
1184
1185
1187{
1188 if( !aProject )
1189 return false;
1190
1191 wxString name = aProject->GetProjectFullName();
1192
1193 if( !m_project_files.count( name ) )
1194 return false;
1195
1197
1198 auto it = std::find_if( m_settings.begin(), m_settings.end(),
1199 [&file]( const std::unique_ptr<JSON_SETTINGS>& aPtr )
1200 {
1201 return aPtr.get() == file;
1202 } );
1203
1204 if( it != m_settings.end() )
1205 {
1206 wxString projectPath = GetPathForSettingsFile( it->get() );
1207
1208 FlushAndRelease( &aProject->GetLocalSettings(), aSave );
1209
1210 if( aSave )
1211 ( *it )->SaveToFile( projectPath );
1212
1213 m_settings.erase( it );
1214 }
1215
1216 m_project_files.erase( name );
1217
1218 return true;
1219}
1220
1221
1223{
1225}
1226
1227
1228wxString SETTINGS_MANAGER::backupDateTimeFormat = wxT( "%Y-%m-%d_%H%M%S" );
1229
1230
1231bool SETTINGS_MANAGER::BackupProject( REPORTER& aReporter, wxFileName& aTarget ) const
1232{
1233 wxDateTime timestamp = wxDateTime::Now();
1234
1235 wxString fileName = wxString::Format( wxT( "%s-%s" ), Prj().GetProjectName(),
1236 timestamp.Format( backupDateTimeFormat ) );
1237
1238 if( !aTarget.IsOk() )
1239 {
1240 aTarget.SetPath( GetProjectBackupsPath() );
1241 aTarget.SetName( fileName );
1242 aTarget.SetExt( FILEEXT::ArchiveFileExtension );
1243 }
1244
1246
1247 wxString test = aTarget.GetPath();
1248
1249 if( !aTarget.DirExists() && !wxMkdir( aTarget.GetPath() ) )
1250 {
1251 wxLogTrace( traceSettings, wxT( "Could not create project backup path %s" ),
1252 aTarget.GetPath() );
1253 return false;
1254 }
1255
1256 if( !aTarget.IsDirWritable() )
1257 {
1258 wxLogTrace( traceSettings, wxT( "Backup directory %s is not writable" ),
1259 aTarget.GetPath() );
1260 return false;
1261 }
1262
1263 wxLogTrace( traceSettings, wxT( "Backing up project to %s" ), aTarget.GetPath() );
1264
1265 return PROJECT_ARCHIVER::Archive( Prj().GetProjectPath(), aTarget.GetFullPath(), aReporter );
1266}
1267
1268
1269class VECTOR_INSERT_TRAVERSER : public wxDirTraverser
1270{
1271public:
1272 VECTOR_INSERT_TRAVERSER( std::vector<wxString>& aVec,
1273 std::function<bool( const wxString& )> aCond ) :
1274 m_files( aVec ),
1275 m_condition( aCond )
1276 {
1277 }
1278
1279 wxDirTraverseResult OnFile( const wxString& aFile ) override
1280 {
1281 if( m_condition( aFile ) )
1282 m_files.emplace_back( aFile );
1283
1284 return wxDIR_CONTINUE;
1285 }
1286
1287 wxDirTraverseResult OnDir( const wxString& aDirName ) override
1288 {
1289 return wxDIR_CONTINUE;
1290 }
1291
1292private:
1293 std::vector<wxString>& m_files;
1294
1295 std::function<bool( const wxString& )> m_condition;
1296};
1297
1298
1300{
1302
1303 if( !settings.enabled )
1304 return true;
1305
1306 wxString prefix = Prj().GetProjectName() + '-';
1307
1308 auto modTime =
1309 [&prefix]( const wxString& aFile )
1310 {
1311 wxDateTime dt;
1312 wxString fn( wxFileName( aFile ).GetName() );
1313 fn.Replace( prefix, wxS( "" ) );
1314 dt.ParseFormat( fn, backupDateTimeFormat );
1315 return dt;
1316 };
1317
1318 wxFileName projectPath( Prj().GetProjectPath() );
1319
1320 // Skip backup if project path isn't valid or writable
1321 if( !projectPath.IsOk() || !projectPath.Exists() || !projectPath.IsDirWritable() )
1322 return true;
1323
1324 wxString backupPath = GetProjectBackupsPath();
1325
1326 if( !wxDirExists( backupPath ) )
1327 {
1328 wxLogTrace( traceSettings, wxT( "Backup path %s doesn't exist, creating it" ), backupPath );
1329
1330 if( !wxMkdir( backupPath ) )
1331 {
1332 wxLogTrace( traceSettings, wxT( "Could not create backups path! Skipping backup" ) );
1333 return false;
1334 }
1335 }
1336
1337 wxDir dir( backupPath );
1338
1339 if( !dir.IsOpened() )
1340 {
1341 wxLogTrace( traceSettings, wxT( "Could not open project backups path %s" ), dir.GetName() );
1342 return false;
1343 }
1344
1345 std::vector<wxString> files;
1346
1347 VECTOR_INSERT_TRAVERSER traverser( files,
1348 [&modTime]( const wxString& aFile )
1349 {
1350 return modTime( aFile ).IsValid();
1351 } );
1352
1353 dir.Traverse( traverser, wxT( "*.zip" ) );
1354
1355 // Sort newest-first
1356 std::sort( files.begin(), files.end(),
1357 [&]( const wxString& aFirst, const wxString& aSecond ) -> bool
1358 {
1359 wxDateTime first = modTime( aFirst );
1360 wxDateTime second = modTime( aSecond );
1361
1362 return first.GetTicks() > second.GetTicks();
1363 } );
1364
1365 // Do we even need to back up?
1366 if( !files.empty() )
1367 {
1368 wxDateTime lastTime = modTime( files[0] );
1369
1370 if( lastTime.IsValid() )
1371 {
1372 wxTimeSpan delta = wxDateTime::Now() - modTime( files[0] );
1373
1374 if( delta.IsShorterThan( wxTimeSpan::Seconds( settings.min_interval ) ) )
1375 return true;
1376 }
1377 }
1378
1379 // Backup
1380 wxFileName target;
1381 bool backupSuccessful = BackupProject( aReporter, target );
1382
1383 if( !backupSuccessful )
1384 return false;
1385
1386 // Update the file list
1387 files.insert( files.begin(), target.GetFullPath() );
1388
1389 // Are there any changes since the last backup?
1390 if( files.size() >= 2
1391 && PROJECT_ARCHIVER::AreZipArchivesIdentical( files[0], files[1], aReporter ) )
1392 {
1393 wxRemoveFile( files[0] );
1394 return true;
1395 }
1396
1397 // Now that we know a backup is needed, apply the retention policy
1398
1399 // Step 1: if we're over the total file limit, remove the oldest
1400 if( !files.empty() && settings.limit_total_files > 0 )
1401 {
1402 while( files.size() > static_cast<size_t>( settings.limit_total_files ) )
1403 {
1404 wxRemoveFile( files.back() );
1405 files.pop_back();
1406 }
1407 }
1408
1409 // Step 2: Stay under the total size limit
1410 if( settings.limit_total_size > 0 )
1411 {
1412 wxULongLong totalSize = 0;
1413
1414 for( const wxString& file : files )
1415 totalSize += wxFileName::GetSize( file );
1416
1417 while( !files.empty() && totalSize > static_cast<wxULongLong>( settings.limit_total_size ) )
1418 {
1419 totalSize -= wxFileName::GetSize( files.back() );
1420 wxRemoveFile( files.back() );
1421 files.pop_back();
1422 }
1423 }
1424
1425 // Step 3: Stay under the daily limit
1426 if( settings.limit_daily_files > 0 && files.size() > 1 )
1427 {
1428 wxDateTime day = modTime( files[0] );
1429 int num = 1;
1430
1431 wxASSERT( day.IsValid() );
1432
1433 std::vector<wxString> filesToDelete;
1434
1435 for( size_t i = 1; i < files.size(); i++ )
1436 {
1437 wxDateTime dt = modTime( files[i] );
1438
1439 if( dt.IsSameDate( day ) )
1440 {
1441 num++;
1442
1443 if( num > settings.limit_daily_files )
1444 filesToDelete.emplace_back( files[i] );
1445 }
1446 else
1447 {
1448 day = dt;
1449 num = 1;
1450 }
1451 }
1452
1453 for( const wxString& file : filesToDelete )
1454 wxRemoveFile( file );
1455 }
1456
1457 return true;
1458}
1459
1460
1462{
1464}
const char * name
Definition: DXF_plotter.cpp:59
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
Color settings are a bit different than most of the settings objects in that there can be more than o...
void SetName(const wxString &aName)
static std::vector< COLOR_SETTINGS * > CreateBuiltinColorSettings()
Constructs and returns a list of color settings objects based on the built-in color themes.
static const wxString COLOR_BUILTIN_DEFAULT
AUTO_BACKUP m_Backup
ENVIRONMENT m_Env
int ShowModal() override
std::function< void(const wxFileName &)> m_action
JSON_DIR_TRAVERSER(std::function< void(const wxFileName &)> aAction)
wxDirTraverseResult OnDir(const wxString &dirPath) override
wxDirTraverseResult OnFile(const wxString &aFilePath) override
std::optional< nlohmann::json > GetJson(const std::string &aPath) const
Fetches a JSON object that is a subset of this JSON_SETTINGS object, using a path of the form "key1....
bool Contains(const std::string &aPath) const
SETTINGS_LOC GetLocation() const
Definition: json_settings.h:87
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.
bool IsReadOnly() const
Definition: json_settings.h:91
void SetReadOnly(bool aReadOnly)
Definition: json_settings.h:92
wxString GetFullFilename() const
JSON_SETTINGS_INTERNALS * Internals()
void SetFilename(const wxString &aFilename)
Definition: json_settings.h:84
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
Calls Store() and then writes the contents of the JSON document to a file.
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:80
virtual void ProjectChanged()
Calls ProjectChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:640
bool Valid() const
Definition: lockfile.h:240
wxDirTraverseResult OnDir(const wxString &dirPath) override
MIGRATION_TRAVERSER(const wxString &aSrcDir, const wxString &aDestDir, bool aMigrateTables)
wxDirTraverseResult OnFile(const wxString &aSrcFilePath) override
static wxString CalculateUserSettingsPath(bool aIncludeVer=true, bool aUseEnv=true)
Determines the base path for user settings files.
Definition: paths.cpp:593
static wxString GetDefault3rdPartyPath()
Gets the default path for PCM packages.
Definition: paths.cpp:132
static wxString GetStockDataPath(bool aRespectRunFromBuildDir=true)
Gets the stock (install) data path, which is the base path for things like scripting,...
Definition: paths.cpp:196
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
Definition: paths.cpp:582
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition: pgm_base.cpp:935
static bool Archive(const wxString &aSrcDir, const wxString &aDestFile, REPORTER &aReporter, bool aVerbose=true, bool aIncludeExtraFiles=false)
Create an archive of the project.
static bool AreZipArchivesIdentical(const wxString &aZipFileA, const wxString &aZipFileB, REPORTER &aReporter)
Compare the CRCs of all the files in zip archive to determine whether the archives are identical.
The backing store for a PROJECT, in JSON format.
Definition: project_file.h:72
void SetProject(PROJECT *aProject)
Definition: project_file.h:88
The project local settings are things that are attached to a particular project, but also might be pa...
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
Calls Store() and then writes the contents of the JSON document to a file.
Container for project specific data.
Definition: project.h:64
virtual void setProjectFile(PROJECT_FILE *aFile)
Set the backing store file for this project.
Definition: project.h:322
virtual bool IsReadOnly() const
Definition: project.h:162
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:140
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition: project.cpp:146
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:158
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition: project.h:206
virtual void setProjectFullName(const wxString &aFullPathAndName)
Set the full directory, basename, and extension of the project.
Definition: project.cpp:116
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:72
static int compareVersions(const std::string &aFirst, const std::string &aSecond)
Compare two settings versions, like "5.99" and "6.0".
std::unique_ptr< LOCKFILE > m_project_lock
Lock for loaded project (expand to multiple once we support MDI).
wxString GetPathForSettingsFile(JSON_SETTINGS *aSettings)
Return the path a given settings file should be loaded from / stored to.
static std::string GetSettingsVersion()
Parse the current KiCad build version and extracts the major and minor revision to use as the name of...
void SaveProjectAs(const wxString &aFullPath, PROJECT *aProject=nullptr)
Set the currently loaded project path and saves it (pointers remain valid).
JSON_SETTINGS * registerSettings(JSON_SETTINGS *aSettings, bool aLoadNow=true)
static wxString GetUserSettingsPath()
A proxy for PATHS::GetUserSettingsPath() rather than fighting swig.
COLOR_SETTINGS * GetColorSettings(const wxString &aName="user")
Retrieve a color settings object that applications can read colors from.
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Take ownership of the pointer passed in.
void SaveProjectCopy(const wxString &aFullPath, PROJECT *aProject=nullptr)
Save a copy of the current project under the given path.
bool MigrateIfNeeded()
Handle the initialization of the user settings directory and migration from previous KiCad versions a...
wxString m_migration_source
void SaveColorSettings(COLOR_SETTINGS *aSettings, const std::string &aNamespace="")
Safely save a COLOR_SETTINGS to disk, preserving any changes outside the given namespace.
std::map< wxString, PROJECT * > m_projects
Loaded projects, mapped according to project full name.
static bool extractVersion(const std::string &aVersionString, int *aMajor=nullptr, int *aMinor=nullptr)
Extract the numeric version from a given settings string.
COLOR_SETTINGS * registerColorSettings(const wxString &aFilename, bool aAbsolutePath=false)
bool m_headless
True if running outside a UI context.
SETTINGS_MANAGER(bool aHeadless=false)
static wxString GetColorSettingsPath()
Return the path where color scheme files are stored; creating it if missing (normally .
COMMON_SETTINGS * GetCommonSettings() const
Retrieve the common settings shared by all applications.
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
wxString GetProjectBackupsPath() const
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Load a project or sets up a new project with a specified path.
std::map< wxString, PROJECT_FILE * > m_project_files
Loaded project files, mapped according to project full name.
std::unordered_map< wxString, COLOR_SETTINGS * > m_color_settings
COLOR_SETTINGS * loadColorSettingsByName(const wxString &aName)
Attempt to load a color theme by name (the color theme directory and .json ext are assumed).
bool IsProjectOpen() const
Helper for checking if we have a project open.
bool GetPreviousVersionPaths(std::vector< wxString > *aName=nullptr)
Retrieve the name of the most recent previous KiCad version that can be found in the user settings di...
static bool IsSettingsPathValid(const wxString &aPath)
Check if a given path is probably a valid KiCad configuration directory.
bool BackupProject(REPORTER &aReporter, wxFileName &aTarget) const
Create a backup archive of the current project.
std::vector< std::unique_ptr< PROJECT > > m_projects_list
Loaded projects (ownership here).
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
std::vector< wxString > GetOpenProjects() const
std::vector< std::unique_ptr< JSON_SETTINGS > > m_settings
bool TriggerBackupIfNeeded(REPORTER &aReporter) const
Call BackupProject() if a new backup is needed according to the current backup policy.
bool m_migrateLibraryTables
If true, the symbol and footprint library tables will be migrated from the previous version.
bool unloadProjectFile(PROJECT *aProject, bool aSave)
Optionally save, unload and unregister the given PROJECT_FILE.
COLOR_SETTINGS * GetMigratedColorSettings()
Return a color theme for storing colors migrated from legacy (5.x and earlier) settings,...
std::unordered_map< size_t, JSON_SETTINGS * > m_app_settings_cache
Cache for app settings.
COLOR_SETTINGS * AddNewColorSettings(const wxString &aFilename)
Register a new color settings object with the given filename.
bool m_ok
True if settings loaded successfully at construction.
void registerBuiltinColorSettings()
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
bool loadProjectFile(PROJECT &aProject)
Register a PROJECT_FILE and attempt to load it from disk.
bool IsProjectOpenNotDummy() const
Helper for checking if we have a project open that is not a dummy project.
static wxString backupDateTimeFormat
void ReloadColorSettings()
Re-scan the color themes directory, reloading any changes it finds.
COMMON_SETTINGS * m_common_settings
KIWAY * m_kiway
The kiway this settings manager interacts with.
void FlushAndRelease(JSON_SETTINGS *aSettings, bool aSave=true)
If the given settings object is registered, save it to disk and unregister it.
wxDirTraverseResult OnFile(const wxString &aFile) override
wxDirTraverseResult OnDir(const wxString &aDirName) override
std::vector< wxString > & m_files
VECTOR_INSERT_TRAVERSER(std::vector< wxString > &aVec, std::function< bool(const wxString &)> aCond)
std::function< bool(const wxString &)> m_condition
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:195
This file is part of the common library.
Functions related to environment variables, including help functions.
void KiCopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
Definition: gestfich.cpp:290
static const std::string SymbolLibraryTableFileName
static const std::string ProjectFileExtension
static const std::string LegacyProjectFileExtension
static const std::string FootprintLibraryTableFileName
static const std::string ArchiveFileExtension
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
#define traceSettings
Definition: json_settings.h:52
File locking utilities.
This file contains miscellaneous commonly used macros and functions.
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition: env_vars.cpp:74
void LongPathAdjustment(wxFileName &aFilename)
Adjusts a filename to be a long path compatible.
Definition: unix/io.cpp:78
void delete_if(_Container &__c, _Function &&__f)
Deletes all values from __c for which __f returns true.
Definition: kicad_algo.h:174
STL namespace.
PGM_BASE & Pgm()
The global program "get" accessor.
Definition: pgm_base.cpp:1073
see class PGM_BASE
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition: project.h:40
#define PROJECT_BACKUPS_DIR_SUFFIX
Project settings path will be <projectname> + this.
int min_interval
Minimum time, in seconds, between subsequent backups.
unsigned long long limit_total_size
Maximum total size of backups (bytes), 0 for unlimited.
int limit_total_files
Maximum number of backup archives to retain.
int limit_daily_files
Maximum files to keep per day, 0 for unlimited.
bool enabled
Automatically back up the project when files are saved.
constexpr int delta
Definition of file extensions used in Kicad.