Debian Codegraph @

src/Gui/PreferencePackManager.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2021 Chris Hennes <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <memory>
25 #include <string_view>
26 #include <mutex>
27
28
29 #include <filesystem>
30 #include <boost/algorithm/string.hpp>
31 #include <QDir>
32
33 #include "PreferencePackManager.h"
34 #include "App/Metadata.h"
35 #include "Base/Parameter.h"
36 #include "Base/Interpreter.h"
37 #include "Base/Console.h"
38 #include "DockWindowManager.h"
39 #include "ToolBarManager.h"
40
41 #include <Application.h>
42 #include <App/Application.h>
43
44 #include <ctime> // For generating a timestamped filename
45 #include <Base/ServiceProvider.h>
46 #include <Dialogs/DlgThemeEditor.h>
47
48
49 using namespace Gui;
50 using namespace xercesc;
51 namespace fs = std::filesystem;
52
53 static std::filesystem::path getSavedPrefPacksPath()
54 {
55 return fs::path(Base::FileInfo::stringToPath(App::Application::getUserAppDataDir()))
56 / "SavedPreferencePacks";
57 }
58
59 static std::filesystem::path getResourcePrefPacksPath()
60 {
61 return fs::path(Base::FileInfo::stringToPath(App::Application::getResourceDir())) / "Gui"
62 / "PreferencePacks";
63 }
64
65 PreferencePack::PreferencePack(const fs::path& path, const App::Metadata& metadata)
66 : _path(path)
67 , _metadata(metadata)
68 {
69 if (!fs::exists(_path)) {
70 throw std::runtime_error {"Cannot access " + path.string()};
71 }
72
73 auto qssPaths = QDir::searchPaths(QStringLiteral("qss"));
74 auto cssPaths = QDir::searchPaths(QStringLiteral("css"));
75 auto overlayPaths = QDir::searchPaths(QStringLiteral("overlay"));
76
77 qssPaths.append(QString::fromStdString(Base::FileInfo::pathToString(_path)));
78 cssPaths.append(QString::fromStdString(Base::FileInfo::pathToString(_path)));
79 overlayPaths.append(QString::fromStdString(Base::FileInfo::pathToString(_path) + "/overlay"));
80
81 QDir::setSearchPaths(QStringLiteral("qss"), qssPaths);
82 QDir::setSearchPaths(QStringLiteral("css"), cssPaths);
83 QDir::setSearchPaths(QStringLiteral("overlay"), overlayPaths);
84 }
85
86 std::string PreferencePack::name() const
87 {
88 return _metadata.name();
89 }
90
91 bool PreferencePack::apply() const
92 {
93 // Run the pre.FCMacro, if it exists: if it raises an exception, abort the process
94 auto preMacroPath = _path / "pre.FCMacro";
95 if (fs::exists(preMacroPath)) {
96 try {
97 Base::Interpreter().runFile(Base::FileInfo::pathToString(preMacroPath).c_str(), false);
98 }
99 catch (...) {
100 Base::Console().message(
101 "PreferencePack application aborted by the preferencePack's pre.FCMacro"
102 );
103 return false;
104 }
105 }
106
107 // Back up the old config file
108 auto savedPreferencePacksDirectory = getSavedPrefPacksPath();
109 auto backupFile = savedPreferencePacksDirectory / "user.cfg.backup";
110 try {
111 fs::remove(backupFile);
112 }
113 catch (...) {
114 }
115 App::GetApplication().GetUserParameter().SaveDocument(
116 Base::FileInfo::pathToString(backupFile).c_str()
117 );
118
119 // Apply the config settings
120 applyConfigChanges();
121
122 // Run the Post.FCMacro, if it exists
123 auto postMacroPath = _path / "post.FCMacro";
124 if (fs::exists(postMacroPath)) {
125 try {
126 Base::Interpreter().runFile(Base::FileInfo::pathToString(postMacroPath).c_str(), false);
127 }
128 catch (...) {
129 Base::Console().message(
130 "PreferencePack application reverted by the preferencePack's post.FCMacro"
131 );
132 App::GetApplication().GetUserParameter().LoadDocument(
133 Base::FileInfo::pathToString(backupFile).c_str()
134 );
135 return false;
136 }
137 }
138
139 return true;
140 }
141
142
143 App::Metadata Gui::PreferencePack::metadata() const
144 {
145 return _metadata;
146 }
147
148 void PreferencePack::applyConfigChanges() const
149 {
150 auto configFile = _path / (_metadata.name() + ".cfg");
151 if (fs::exists(configFile)) {
152 auto newParameters = ParameterManager::Create();
153 newParameters->LoadDocument(Base::FileInfo::pathToString(configFile).c_str());
154 auto baseAppGroup = App::GetApplication().GetUserParameter().GetGroup("BaseApp");
155 newParameters->GetGroup("BaseApp")->insertTo(baseAppGroup);
156 }
157 }
158
159 PreferencePackManager::PreferencePackManager()
160 : _preferencePackPaths(modPaths())
161 {
162 auto savedPath = getSavedPreferencePacksPath();
163 auto resourcePath = getResourcePreferencePacksPath();
164 _preferencePackPaths.insert(_preferencePackPaths.begin(), resourcePath);
165 _preferencePackPaths.push_back(savedPath);
166 rescan();
167
168 // Housekeeping:
169 DeleteOldBackups();
170 }
171
172 void PreferencePackManager::rescan()
173 {
174 std::lock_guard<std::mutex> lock(_mutex);
175 _preferencePacks.clear();
176 for (const auto& path : _preferencePackPaths) {
177 if (fs::exists(path) && fs::is_directory(path)) {
178 FindPreferencePacksInPackage(path);
179 for (const auto& mod : fs::directory_iterator(path)) {
180 if (fs::is_directory(mod)) {
181 FindPreferencePacksInPackage(mod);
182 }
183 }
184 }
185 }
186 }
187
188 void Gui::PreferencePackManager::AddPackToMetadata(const std::string& packName) const
189 {
190 std::lock_guard<std::mutex> lock(_mutex);
191 auto savedPreferencePacksDirectory = getSavedPreferencePacksPath();
192 fs::path preferencePackDirectory(savedPreferencePacksDirectory / packName);
193 if (fs::exists(preferencePackDirectory) && !fs::is_directory(preferencePackDirectory)) {
194 throw std::runtime_error(
195 "Cannot create " + savedPreferencePacksDirectory.string()
196 + ": file with that name exists already"
197 );
198 }
199
200 if (!fs::exists(preferencePackDirectory)) {
201 fs::create_directories(preferencePackDirectory);
202 }
203
204 // Create or update the saved user preferencePacks package.xml metadata file
205 std::unique_ptr<App::Metadata> metadata;
206 if (fs::exists(savedPreferencePacksDirectory / "package.xml")) {
207 metadata = std::make_unique<App::Metadata>(savedPreferencePacksDirectory / "package.xml");
208 }
209 else {
210 metadata = std::make_unique<App::Metadata>();
211 metadata->setName("User-Saved Preference Packs");
212 std::stringstream str;
213 str << "Generated automatically -- edits may be lost when saving new preference packs. To "
214 << "distribute one or more of these packs:\n"
215 << " 1) copy the entire SavedPreferencePacks directory to a convenient location,\n"
216 << " 2) rename the directory (usually to the name of the preference pack you are "
217 << "distributing),\n"
218 << " 3) delete any subfolders containing packs you don't want to distribute,\n"
219 << " 4) use git to initialize the directory as a git repository,\n"
220 << " 5) push it to a remote git host,\n"
221 << " 6) activate Developer Mode in the Addon Manager,\n"
222 << " 7) use Developer Tools in the Addon Manager to update the metadata file,\n"
223 << " 8) add, commit, and push the updated package.xml file,\n"
224 << " 9) add your remote host to the custom repositories list in the Addon Manager"
225 << " preferences,\n"
226 << " 10) use the Addon Manager to install your preference pack locally for testing.";
227 metadata->setDescription(str.str());
228 metadata->addLicense(App::Meta::License("All Rights Reserved", fs::path()));
229 }
230 for (const auto& item : metadata->content()) {
231 if (item.first == "preferencepack") {
232 if (item.second.name() == packName) {
233 // A pack with this name exists already, bail out
234 return;
235 }
236 }
237 }
238 App::Metadata newPreferencePackMetadata;
239 newPreferencePackMetadata.setName(packName);
240
241 metadata->addContentItem("preferencepack", newPreferencePackMetadata);
242 metadata->write(savedPreferencePacksDirectory / "package.xml");
243 }
244
245 void Gui::PreferencePackManager::importConfig(
246 const std::string& packName,
247 const std::filesystem::path& path
248 )
249 {
250 AddPackToMetadata(packName);
251
252 auto savedPreferencePacksDirectory = getSavedPreferencePacksPath();
253 auto cfgFilename = savedPreferencePacksDirectory / packName / (packName + ".cfg");
254 fs::copy_file(path, cfgFilename, fs::copy_options::overwrite_existing);
255 rescan();
256 }
257
258 // TODO(Shvedov): Is this suitable place for this method? It is more generic,
259 // and maybe more suitable place at Application?
260 std::vector<std::filesystem::path> Gui::PreferencePackManager::modPaths() const
261 {
262 auto userModPath = fs::path(Base::FileInfo::stringToPath(App::Application::getUserAppDataDir()))
263 / "Mod";
264
265 auto& config = App::Application::Config();
266 auto additionalModules = config.find("AdditionalModulePaths");
267 std::vector<std::filesystem::path> result;
268
269 if (additionalModules != config.end()) {
270 boost::split(result, additionalModules->second, boost::is_any_of(";"), boost::token_compress_on);
271 }
272 result.emplace_back(userModPath);
273 return result;
274 }
275
276 std::filesystem::path Gui::PreferencePackManager::getSavedPreferencePacksPath() const
277 {
278 return getSavedPrefPacksPath();
279 }
280
281 std::filesystem::path Gui::PreferencePackManager::getResourcePreferencePacksPath() const
282 {
283 return getResourcePrefPacksPath();
284 }
285
286 std::vector<std::string> Gui::PreferencePackManager::getPacksFromDirectory(const fs::path& path) const
287 {
288 std::vector<std::string> results;
289 auto packageMetadataFile = path / "package.xml";
290 if (fs::exists(packageMetadataFile) && fs::is_regular_file(packageMetadataFile)) {
291 try {
292 App::Metadata metadata(packageMetadataFile);
293 auto content = metadata.content();
294 for (const auto& item : content) {
295 if (item.first == "preferencepack") {
296 results.push_back(item.second.name());
297 }
298 }
299 }
300 catch (...) {
301 // Failed to read the metadata, or to create the preferencePack based on it...
302 Base::Console().error(("Failed to read " + packageMetadataFile.string()).c_str());
303 }
304 }
305 return results;
306 }
307
308 void Gui::PreferencePackManager::FindPreferencePacksInPackage(const fs::path& mod)
309 {
310 try {
311 TryFindPreferencePacksInPackage(mod);
312 }
313 catch (const std::exception& e) {
314 Base::Console().error("%s\n", e.what());
315 }
316 catch (...) {
317 // Failed to read the metadata, or to create the preferencePack based on it...
318 auto packageMetadataFile = mod / "package.xml";
319 Base::Console().error(
320 "Failed to read %s\n",
321 Base::FileInfo::pathToString(packageMetadataFile).c_str()
322 );
323 }
324 }
325
326 void PreferencePackManager::TryFindPreferencePacksInPackage(const std::filesystem::path& mod)
327 {
328 auto packageMetadataFile = mod / "package.xml";
329 static const auto modDirectory
330 = fs::path(Base::FileInfo::stringToPath(App::Application::getUserAppDataDir())) / "Mod"
331 / "SavedPreferencePacks";
332 static const auto resourcePath = getResourcePreferencePacksPath();
333
334 if (fs::exists(packageMetadataFile) && fs::is_regular_file(packageMetadataFile)) {
335 App::Metadata metadata(packageMetadataFile);
336 auto content = metadata.content();
337 auto basename = Base::FileInfo::pathToString(mod.filename());
338 if (mod == modDirectory) {
339 basename = "##USER_SAVED##";
340 }
341 else if (mod == resourcePath) {
342 basename = "##BUILT_IN##";
343 }
344 for (const auto& item : content) {
345 if (item.first == "preferencepack") {
346 if (isVisible(basename, item.second.name())) {
347 PreferencePack newPreferencePack(mod / item.second.name(), item.second);
348 _preferencePacks.insert(
349 std::make_pair(newPreferencePack.name(), newPreferencePack)
350 );
351 }
352 }
353 }
354 }
355 }
356
357 std::vector<std::string> PreferencePackManager::preferencePackNames() const
358 {
359 std::lock_guard<std::mutex> lock(_mutex);
360 std::vector<std::string> names;
361 for (const auto& preferencePack : _preferencePacks) {
362 names.push_back(preferencePack.first);
363 }
364 return names;
365 }
366
367 std::map<std::string, PreferencePack> Gui::PreferencePackManager::preferencePacks() const
368 {
369 return _preferencePacks;
370 }
371
372 bool PreferencePackManager::apply(const std::string& preferencePackName) const
373 {
374 std::lock_guard<std::mutex> lock(_mutex);
375 if (auto preferencePack = _preferencePacks.find(preferencePackName);
376 preferencePack != _preferencePacks.end()) {
377 BackupCurrentConfig();
378 bool wasApplied = preferencePack->second.apply();
379 if (wasApplied) {
380 // If the visibility state of the dock windows was changed we have to manually reload
381 // their state
382 Gui::DockWindowManager* pDockMgr = Gui::DockWindowManager::instance();
383 pDockMgr->loadState();
384
385 // Same goes for toolbars:
386 Gui::ToolBarManager* pToolbarMgr = Gui::ToolBarManager::getInstance();
387 pToolbarMgr->restoreState();
388
389 // TODO: Are there other things that have to be manually triggered?
390 }
391 return wasApplied;
392 }
393 else {
394 throw std::runtime_error("No such Preference Pack: " + preferencePackName);
395 }
396 }
397
398 static std::string findUnusedName(const std::string& basename, ParameterGrp::handle parent)
399 {
400 int i = 1;
401 while (true) {
402 std::ostringstream nameToTest;
403 nameToTest << basename << "_" << i;
404 if (!parent->HasGroup(nameToTest.str().c_str())) {
405 return nameToTest.str();
406 }
407 ++i;
408 }
409 }
410
411 bool PreferencePackManager::isVisible(
412 const std::string& addonName,
413 const std::string& preferencePackName
414 ) const
415 {
416 if (addonName.empty() || preferencePackName.empty()) {
417 return true;
418 }
419
420 auto pref = App::GetApplication().GetParameterGroupByPath(
421 "User parameter:BaseApp/Preferences/General/HiddenPreferencePacks"
422 );
423 auto hiddenPacks = pref->GetGroups();
424 auto hiddenPack = std::find_if(
425 hiddenPacks.begin(),
426 hiddenPacks.end(),
427 [addonName, preferencePackName](ParameterGrp::handle handle) {
428 return (handle->GetASCII("addonName", "") == addonName)
429 && (handle->GetASCII("preferencePackName", "") == preferencePackName);
430 }
431 );
432 if (hiddenPack == hiddenPacks.end()) {
433 return true;
434 }
435 else {
436 return false;
437 }
438 }
439
440 void PreferencePackManager::toggleVisibility(
441 const std::string& addonName,
442 const std::string& preferencePackName
443 )
444 {
445 if (preferencePackName.empty()) {
446 return;
447 }
448 auto pref = App::GetApplication().GetParameterGroupByPath(
449 "User parameter:BaseApp/Preferences/General/HiddenPreferencePacks"
450 );
451 auto hiddenPacks = pref->GetGroups();
452 auto hiddenPack = std::find_if(
453 hiddenPacks.begin(),
454 hiddenPacks.end(),
455 [addonName, preferencePackName](ParameterGrp::handle handle) {
456 return (handle->GetASCII("addonName", "") == addonName)
457 && (handle->GetASCII("preferencePackName", "") == preferencePackName);
458 }
459 );
460 if (hiddenPack == hiddenPacks.end()) {
461 auto name = findUnusedName("PreferencePack", pref);
462 auto group = pref->GetGroup(name.c_str());
463 group->SetASCII("addonName", addonName.c_str());
464 group->SetASCII("preferencePackName", preferencePackName.c_str());
465 }
466 else {
467 auto groupName = (*hiddenPack)->GetGroupName();
468 hiddenPacks.clear(); // To decrement the reference count of the group we are about the remove...
469 pref->RemoveGrp(groupName);
470 }
471 rescan();
472 }
473
474 void Gui::PreferencePackManager::deleteUserPack(const std::string& name)
475 {
476 if (name.empty()) {
477 return;
478 }
479 auto savedPreferencePacksDirectory = getSavedPreferencePacksPath();
480 auto savedPath = savedPreferencePacksDirectory / name;
481 std::unique_ptr<App::Metadata> metadata;
482 if (fs::exists(savedPreferencePacksDirectory / "package.xml")) {
483 metadata = std::make_unique<App::Metadata>(savedPreferencePacksDirectory / "package.xml");
484 }
485 else {
486 throw std::runtime_error("Lost the user-saved preference packs metadata file!");
487 }
488 metadata->removeContentItem("preferencepack", name);
489 metadata->write(savedPreferencePacksDirectory / "package.xml");
490 if (fs::exists(savedPath)) {
491 fs::remove_all(savedPath);
492 }
493 rescan();
494 }
495
496 static void copyTemplateParameters(
497 Base::Reference<ParameterGrp> templateGroup,
498 const std::string& path,
499 Base::Reference<ParameterGrp> outputGroup
500 )
501 {
502 auto userParameterHandle = App::GetApplication().GetParameterGroupByPath(path.c_str());
503
504 // Ensure that the DockWindowManager has saved its current state:
505 Gui::DockWindowManager* pDockMgr = Gui::DockWindowManager::instance();
506 pDockMgr->saveState();
507
508 // Do the same for ToolBars
509 Gui::ToolBarManager* pToolbarMgr = Gui::ToolBarManager::getInstance();
510 pToolbarMgr->saveState();
511
512 auto boolMap = templateGroup->GetBoolMap();
513 for (const auto& kv : boolMap) {
514 auto currentValue = userParameterHandle->GetBool(kv.first.c_str(), kv.second);
515 outputGroup->SetBool(kv.first.c_str(), currentValue);
516 }
517
518 auto intMap = templateGroup->GetIntMap();
519 for (const auto& kv : intMap) {
520 auto currentValue = userParameterHandle->GetInt(kv.first.c_str(), kv.second);
521 outputGroup->SetInt(kv.first.c_str(), currentValue);
522 }
523
524 auto uintMap = templateGroup->GetUnsignedMap();
525 for (const auto& kv : uintMap) {
526 auto currentValue = userParameterHandle->GetUnsigned(kv.first.c_str(), kv.second);
527 outputGroup->SetUnsigned(kv.first.c_str(), currentValue);
528 }
529
530 auto floatMap = templateGroup->GetFloatMap();
531 for (const auto& kv : floatMap) {
532 auto currentValue = userParameterHandle->GetFloat(kv.first.c_str(), kv.second);
533 outputGroup->SetFloat(kv.first.c_str(), currentValue);
534 }
535
536 auto asciiMap = templateGroup->GetASCIIMap();
537 for (const auto& kv : asciiMap) {
538 auto currentValue = userParameterHandle->GetASCII(kv.first.c_str(), kv.second.c_str());
539 outputGroup->SetASCII(kv.first.c_str(), currentValue.c_str());
540 }
541
542 // Recurse...
543 auto templateSubgroups = templateGroup->GetGroups();
544 for (auto& templateSubgroup : templateSubgroups) {
545 std::string sgName = templateSubgroup->GetGroupName();
546 auto outputSubgroupHandle = outputGroup->GetGroup(sgName.c_str());
547 copyTemplateParameters(templateSubgroup, path + "/" + sgName, outputSubgroupHandle);
548 }
549 }
550
551 static void copyTemplateParameters(/*const*/ ParameterManager& templateParameterManager,
552 ParameterManager& outputParameterManager)
553 {
554 auto groups = templateParameterManager.GetGroups();
555 for (auto& group : groups) {
556 std::string name = group->GetGroupName();
557 auto groupHandle = outputParameterManager.GetGroup(name.c_str());
558 copyTemplateParameters(group, "User parameter:" + name, groupHandle);
559 }
560 }
561
562 void PreferencePackManager::save(
563 const std::string& name,
564 const std::string& directory,
565 const std::vector<TemplateFile>& templates
566 )
567 {
568 if (templates.empty()) {
569 return;
570 }
571
572
573 // Create the config file
574 auto outputParameterManager = ParameterManager::Create();
575 outputParameterManager->CreateDocument();
576 for (const auto& t : templates) {
577 auto templateParameterManager = ParameterManager::Create();
578 templateParameterManager->LoadDocument(Base::FileInfo::pathToString(t.path).c_str());
579 copyTemplateParameters(*templateParameterManager, *outputParameterManager);
580 }
581
582 std::string cfgFilename;
583 if (directory.empty()) {
584 AddPackToMetadata(name);
585 auto savedPreferencePacksDirectory = getSavedPreferencePacksPath();
586 cfgFilename = Base::FileInfo::pathToString(
587 savedPreferencePacksDirectory / name / (name + ".cfg")
588 );
589 }
590 else {
591 cfgFilename = Base::FileInfo::pathToString(fs::path(directory) / (name + ".cfg"));
592 }
593 outputParameterManager->SaveDocument(cfgFilename.c_str());
594 }
595
596 static std::vector<fs::path> scanForTemplateFolders(const std::string& groupName, const fs::path& entry)
597 {
598 // From this location, find the folder(s) called "PreferencePackTemplates"
599 std::vector<fs::path> templateFolders;
600 if (fs::exists(entry)) {
601 if (fs::is_directory(entry)) {
602 if (entry.filename() == "PreferencePackTemplates"
603 || entry.filename() == "preference_pack_templates") {
604 templateFolders.push_back(entry);
605 }
606 else {
607 std::string subgroupName = groupName + "/"
608 + Base::FileInfo::pathToString(entry.filename());
609 for (const auto& subentry : fs::directory_iterator(entry)) {
610 auto contents = scanForTemplateFolders(subgroupName, subentry);
611 std::copy(contents.begin(), contents.end(), std::back_inserter(templateFolders));
612 }
613 }
614 }
615 }
616 return templateFolders;
617 }
618
619 static std::vector<PreferencePackManager::TemplateFile> scanForTemplateFiles(
620 const std::string& groupName,
621 const fs::path& entry
622 )
623 {
624 auto templateFolders = scanForTemplateFolders(groupName, entry);
625
626 std::vector<PreferencePackManager::TemplateFile> templateFiles;
627 for (const auto& templateDir : templateFolders) {
628 if (!fs::exists(templateDir) || !fs::is_directory(templateDir)) {
629 continue;
630 }
631 for (const auto& entry : fs::directory_iterator(templateDir)) {
632 if (entry.path().extension() == ".cfg") {
633 auto name = Base::FileInfo::pathToString(entry.path().filename().stem());
634 std::replace(name.begin(), name.end(), '_', ' ');
635 // Make sure we don't insert the same thing twice...
636 if (std::find_if(
637 templateFiles.begin(),
638 templateFiles.end(),
639 [groupName, name](const auto& rhs) -> bool {
640 return groupName == rhs.group && name == rhs.name;
641 }
642 )
643 != templateFiles.end()) {
644 continue;
645 }
646 templateFiles.push_back({groupName, name, entry});
647 }
648 }
649 }
650 return templateFiles;
651 }
652
653 std::vector<PreferencePackManager::TemplateFile> PreferencePackManager::templateFiles(bool rescan)
654 {
655 std::lock_guard<std::mutex> lock(_mutex);
656 if (!_templateFiles.empty() && !rescan) {
657 return _templateFiles;
658 }
659
660 // Locate all of the template files available on this system
661 // Template files end in ".cfg" -- They are located in:
662 // * $INSTALL_DIR/data/Gui/PreferencePackTemplates/(Appearance|Behavior)/*
663 // * $DATA_DIR/Mod/**/PreferencePackTemplates/(Appearance|Behavior)/*
664 // (alternate spellings are provided for packages using CamelCase and snake_case, and both major
665 // English dialects)
666
667 auto resourcePath = fs::path(Base::FileInfo::stringToPath(App::Application::getResourceDir()))
668 / "Gui";
669
670 std::string group = "Built-In";
671 if (fs::exists(resourcePath) && fs::is_directory(resourcePath)) {
672 const auto localFiles = scanForTemplateFiles(group, resourcePath);
673 std::copy(localFiles.begin(), localFiles.end(), std::back_inserter(_templateFiles));
674 }
675
676 for (const auto& modPath : modPaths()) {
677 if (fs::exists(modPath) && fs::is_directory(modPath)) {
678 for (const auto& mod : fs::directory_iterator(modPath)) {
679 group = Base::FileInfo::pathToString(mod.path().filename());
680 const auto localFiles = scanForTemplateFiles(group, mod);
681 std::copy(localFiles.begin(), localFiles.end(), std::back_inserter(_templateFiles));
682 }
683 }
684 }
685
686 return _templateFiles;
687 }
688
689 void Gui::PreferencePackManager::BackupCurrentConfig() const
690 {
691 auto backupDirectory = getSavedPreferencePacksPath() / "Backups";
692 fs::create_directories(backupDirectory);
693
694 // Create a timestamped filename:
695 auto time = std::time(nullptr);
696 std::ostringstream timestampStream;
697 timestampStream << "user." << time << ".cfg";
698 auto filename = backupDirectory / timestampStream.str();
699
700 // Save the current config:
701 App::GetApplication().GetUserParameter().SaveDocument(
702 Base::FileInfo::pathToString(filename).c_str()
703 );
704 }
705
706 // FIXME: Replace with more accurate C++20 solution once its usable: https://stackoverflow.com/a/68593141
707 template<typename TP>
708 static std::time_t to_time_t(TP tp)
709 {
710 using namespace std::chrono;
711 auto sctp = time_point_cast<system_clock::duration>(tp - TP::clock::now() + system_clock::now());
712 return system_clock::to_time_t(sctp);
713 }
714
715 void Gui::PreferencePackManager::DeleteOldBackups() const
716 {
717 constexpr auto oneWeek = 60.0 * 60.0 * 24.0 * 7.0;
718 const auto now = std::time(nullptr);
719 auto backupDirectory = getSavedPreferencePacksPath() / "Backups";
720 if (fs::exists(backupDirectory) && fs::is_directory(backupDirectory)) {
721 for (const auto& backup : fs::directory_iterator(backupDirectory)) {
722 if (std::difftime(now, to_time_t(fs::last_write_time(backup))) > oneWeek) {
723 try {
724 fs::remove(backup);
725 }
726 catch (...) {
727 }
728 }
729 }
730 }
731 }
732
733 // FIXME: Replace with more accurate C++20 solution once its usable: https://stackoverflow.com/a/68593141
734 std::vector<std::filesystem::path> Gui::PreferencePackManager::configBackups() const
735 {
736 std::vector<std::filesystem::path> results;
737 auto backupDirectory = getSavedPreferencePacksPath() / "Backups";
738 if (fs::exists(backupDirectory) && fs::is_directory(backupDirectory)) {
739 for (const auto& backup : fs::directory_iterator(backupDirectory)) {
740 results.push_back(backup);
741 }
742 }
743 return results;
744 }