Debian Codegraph @

src/Gui/PreferencePages/DlgSettingsGeneral.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /****************************************************************************
4 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
5 * Copyright (c) 2023 FreeCAD Project Association *
6 * *
7 * This file is part of FreeCAD. *
8 * *
9 * FreeCAD is free software: you can redistribute it and/or modify it *
10 * under the terms of the GNU Lesser General Public License as *
11 * published by the Free Software Foundation, either version 2.1 of the *
12 * License, or (at your option) any later version. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, but *
15 * WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
17 * Lesser General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU Lesser General Public *
20 * License along with FreeCAD. If not, see *
21 * <https://www.gnu.org/licenses/>. *
22 * *
23 ***************************************************************************/
24
25
26 #include <cmath>
27 #include <limits>
28 #include <QApplication>
29 #include <QFileDialog>
30 #include <QLocale>
31 #include <QMessageBox>
32 #include <QString>
33 #include <algorithm>
34
35 #include <App/Document.h>
36 #include <Base/Parameter.h>
37 #include <Base/UnitsApi.h>
38
39 #include <Gui/Document.h>
40 #include <Gui/Command.h>
41
42 #include <Gui/Action.h>
43 #include <Gui/Application.h>
44 #include <Gui/Dialogs/DlgCreateNewPreferencePackImp.h>
45 #include <Gui/Dialogs/DlgPreferencesImp.h>
46 #include <Gui/Dialogs/DlgPreferencePackManagementImp.h>
47 #include <Gui/Dialogs/DlgRevertToBackupConfigImp.h>
48 #include <Gui/MainWindow.h>
49 #include <Gui/OverlayManager.h>
50 #include <Gui/ParamHandler.h>
51 #include <Gui/PreferencePackManager.h>
52 #include <Gui/View3DInventor.h>
53 #include <Gui/View3DInventorViewer.h>
54 #include <Gui/Language/Translator.h>
55
56 #include "DlgSettingsGeneral.h"
57 #include "ui_DlgSettingsGeneral.h"
58
59 using namespace Gui;
60 using namespace Gui::Dialog;
61 namespace fs = std::filesystem;
62 using Base::QuantityFormat;
63 using Base::UnitsApi;
64
65 /* TRANSLATOR Gui::Dialog::DlgSettingsGeneral */
66
67 /**
68 * Constructs a DlgSettingsGeneral which is a child of 'parent', with the
69 * name 'name' and widget flags set to 'f'
70 *
71 * The dialog will by default be modeless, unless you set 'modal' to
72 * true to construct a modal dialog.
73 */
74 DlgSettingsGeneral::DlgSettingsGeneral(QWidget* parent)
75 : PreferencePage(parent)
76 , localeIndex(0)
77 , themeChanged(false)
78 , ui(new Ui_DlgSettingsGeneral)
79 {
80 ui->setupUi(this);
81
82 recreatePreferencePackMenu();
83
84 for (const char* option : Translator::formattingOptions) {
85 ui->UseLocaleFormatting->addItem(QCoreApplication::translate("Gui::Translator", option));
86 }
87
88 ui->themesCombobox->setEnabled(true);
89 Gui::Document* doc = Gui::Application::Instance->activeDocument();
90 if (doc) {
91 Gui::View3DInventor* view = qobject_cast<Gui::View3DInventor*>(doc->getActiveView());
92 if (view) {
93 Gui::View3DInventorViewer* viewer = view->getViewer();
94 if (viewer->isEditing()) {
95 ui->ImportConfig->setEnabled(false);
96 ui->SaveNewPreferencePack->setEnabled(false);
97 ui->ManagePreferencePacks->setEnabled(false);
98 ui->themesCombobox->setEnabled(false);
99 ui->moreThemesLabel->setEnabled(false);
100 }
101 }
102 }
103 if (ui->themesCombobox->isEnabled()) {
104 connect(ui->ImportConfig, &QPushButton::clicked, this, &DlgSettingsGeneral::onImportConfigClicked);
105 connect(
106 ui->SaveNewPreferencePack,
107 &QPushButton::clicked,
108 this,
109 &DlgSettingsGeneral::saveAsNewPreferencePack
110 );
111 ui->ManagePreferencePacks->setToolTip(tr("Manage preference packs"));
112 connect(
113 ui->ManagePreferencePacks,
114 &QPushButton::clicked,
115 this,
116 &DlgSettingsGeneral::onManagePreferencePacksClicked
117 );
118 connect(
119 ui->themesCombobox,
120 qOverload<int>(&QComboBox::activated),
121 this,
122 &DlgSettingsGeneral::onThemeChanged
123 );
124 connect(ui->moreThemesLabel, &QLabel::linkActivated, this, &DlgSettingsGeneral::onLinkActivated);
125 }
126
127 // If there are any saved config file backs, show the revert button, otherwise hide it:
128 const auto& backups = Application::Instance->prefPackManager()->configBackups();
129 ui->RevertToSavedConfig->setEnabled(backups.empty());
130 connect(ui->RevertToSavedConfig, &QPushButton::clicked, this, &DlgSettingsGeneral::revertToSavedConfig);
131
132 connect(
133 ui->comboBox_UnitSystem,
134 qOverload<int>(&QComboBox::currentIndexChanged),
135 this,
136 &DlgSettingsGeneral::onUnitSystemIndexChanged
137 );
138 ui->spinBoxDecimals->setMaximum(std::numeric_limits<double>::digits10 + 1);
139
140 auto addItem = [&, index {0}](const std::string& item) mutable {
141 ui->comboBox_UnitSystem->addItem(QString::fromStdString(item), index++);
142 };
143 auto descriptions = UnitsApi::getDescriptions();
144 std::for_each(descriptions.begin(), descriptions.end(), addItem);
145
146 // Enable/disable the fractional inch option depending on system
147 const auto visible = UnitsApi::isMultiUnitLength();
148 ui->comboBox_FracInch->setVisible(visible);
149 ui->fractionalInchLabel->setVisible(visible);
150 ui->moreThemesLabel->setEnabled(
151 Application::Instance->commandManager().getCommandByName("Std_AddonMgr") != nullptr
152 );
153 }
154
155 /**
156 * Destroys the object and frees any allocated resources
157 */
158 DlgSettingsGeneral::~DlgSettingsGeneral() = default;
159
160 /** Sets the size of the recent file list from the user parameters.
161 * @see RecentFilesAction
162 * @see StdCmdRecentFiles
163 */
164 void DlgSettingsGeneral::setRecentFileSize()
165 {
166 auto recent = getMainWindow()->findChild<RecentFilesAction*>(QLatin1String("recentFiles"));
167 if (recent) {
168 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("RecentFiles");
169 recent->resizeList(hGrp->GetInt("RecentFiles", 4));
170 }
171 }
172
173 bool DlgSettingsGeneral::setLanguage()
174 {
175 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
176 QString lang = QLocale::languageToString(QLocale().language());
177 QByteArray language = hGrp->GetASCII("Language", (const char*)lang.toLatin1()).c_str();
178 QByteArray current = ui->Languages->itemData(ui->Languages->currentIndex()).toByteArray();
179 if (current != language) {
180 hGrp->SetASCII("Language", current.constData());
181 Translator::instance()->activateLanguage(current.constData());
182 return true;
183 }
184 return false;
185 }
186
187 void DlgSettingsGeneral::setNumberLocale(bool force /* = false*/)
188 {
189 int localeFormat = ui->UseLocaleFormatting->currentIndex();
190
191 // Only make the change if locale setting has changed or if forced
192 // Except if format is "OS" where we don't want to run setLocale
193 if (localeIndex == localeFormat && (!force || localeFormat == 0)) {
194 return;
195 }
196 localeIndex = localeFormat;
197 }
198
199 void DlgSettingsGeneral::saveUnitSystemSettings()
200 {
201 ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath(
202 "User parameter:BaseApp/Preferences/Units"
203 );
204 hGrpu->SetInt("UserSchema", ui->comboBox_UnitSystem->currentIndex());
205 hGrpu->SetInt("Decimals", ui->spinBoxDecimals->value());
206 hGrpu->SetBool("IgnoreProjectSchema", ui->checkBox_projectUnitSystemIgnore->isChecked());
207
208 // Set actual value
209 UnitsApi::setDecimals(ui->spinBoxDecimals->value());
210
211 // Convert the combobox index to the its integer denominator. Currently
212 // with 1/2, 1/4, through 1/128, this little equation directly computes the
213 // denominator given the combobox integer.
214 //
215 // The inverse conversion is done when loaded. That way only one thing (the
216 // numerical fractional inch value) needs to be stored.
217
218 // minimum fractional inch to display
219 int FracInch = std::pow(2, ui->comboBox_FracInch->currentIndex() + 1);
220 hGrpu->SetInt("FracInch", FracInch);
221
222 // Set the actual format value
223 UnitsApi::setDenominator(FracInch);
224
225 // Set and save the Unit System
226 if (ui->checkBox_projectUnitSystemIgnore->isChecked()) {
227 // currently selected View System (unit system)
228 int viewSystemIndex = ui->comboBox_UnitSystem->currentIndex();
229 UnitsApi::setSchema(viewSystemIndex);
230 }
231 else if (App::Document* doc = App::GetApplication().getActiveDocument()) {
232 UnitsApi::setSchema(doc->UnitSystem.getValue());
233 }
234 else {
235 // if there is no existing document then the unit must still be set
236 int viewSystemIndex = ui->comboBox_UnitSystem->currentIndex();
237 UnitsApi::setSchema(viewSystemIndex);
238 }
239
240 ui->SubstituteDecimal->onSave();
241 ui->UseLocaleFormatting->onSave();
242 }
243
244 void DlgSettingsGeneral::saveSettings()
245 {
246 saveUnitSystemSettings();
247
248 ui->RecentFiles->onSave();
249 ui->EnableCursorBlinking->onSave();
250 ui->SplashScreen->onSave();
251 ui->ActivateOverlay->onSave();
252 if (property("ActivateOverlay").toBool() != ui->ActivateOverlay->isChecked()) {
253 requireRestart();
254 }
255
256 setRecentFileSize();
257 bool force = setLanguage();
258 // In case type is "Selected language", we need to force locale change
259 setNumberLocale(force);
260
261 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
262 QVariant size = ui->toolbarIconSize->itemData(ui->toolbarIconSize->currentIndex());
263 int pixel = size.toInt();
264 hGrp->SetInt("ToolbarIconSize", pixel);
265 getMainWindow()->setIconSize(QSize(pixel, pixel));
266
267 int blinkTime {hGrp->GetBool("EnableCursorBlinking", true) ? -1 : 0};
268 qApp->setCursorFlashTime(blinkTime);
269
270 saveDockWindowVisibility();
271
272 hGrp = App::GetApplication().GetParameterGroupByPath(
273 "User parameter:BaseApp/Preferences/MainWindow"
274 );
275 hGrp->SetBool("TiledBackground", ui->tiledBackground->isChecked());
276
277 if (themeChanged) {
278 saveThemes();
279 }
280 }
281
282 void DlgSettingsGeneral::loadSettings()
283 {
284 int FracInch;
285 int cbIndex;
286
287 ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath(
288 "User parameter:BaseApp/Preferences/Units"
289 );
290 ui->comboBox_UnitSystem->setCurrentIndex(hGrpu->GetInt("UserSchema", 0));
291 ui->spinBoxDecimals->setValue(hGrpu->GetInt("Decimals", UnitsApi::getDecimals()));
292 ui->checkBox_projectUnitSystemIgnore->setChecked(hGrpu->GetBool("IgnoreProjectSchema", false));
293
294 // Get the current user setting for the minimum fractional inch
295 FracInch = hGrpu->GetInt("FracInch", UnitsApi::getDenominator());
296
297 // Convert fractional inch to the corresponding combobox index using this
298 // handy little equation.
299 cbIndex = std::log2(FracInch) - 1;
300 ui->comboBox_FracInch->setCurrentIndex(cbIndex);
301 ui->SubstituteDecimal->onRestore();
302 ui->UseLocaleFormatting->onRestore();
303 ui->RecentFiles->onRestore();
304 ui->EnableCursorBlinking->onRestore();
305 ui->SplashScreen->onRestore();
306 ui->ActivateOverlay->onRestore();
307 setProperty("ActivateOverlay", ui->ActivateOverlay->isChecked());
308
309 // search for the language files
310 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
311 auto langToStr = Translator::instance()->activeLanguage();
312 QByteArray language = hGrp->GetASCII("Language", langToStr.c_str()).c_str();
313
314 localeIndex = ui->UseLocaleFormatting->currentIndex();
315
316 int index = 1;
317 TStringMap list = Translator::instance()->supportedLocales();
318 ui->Languages->clear();
319 ui->Languages->addItem(QStringLiteral("English"), QByteArray("English"));
320 for (auto it = list.begin(); it != list.end(); ++it, index++) {
321 QByteArray lang = it->first.c_str();
322 QString langname = QString::fromLatin1(lang.constData());
323
324 if (it->second == "sr-CS") {
325 // Qt does not treat sr-CS (Serbian, Latin) as a Latin-script variant by default: this
326 // forces it to do so.
327 it->second = "sr_Latn";
328 }
329
330 QLocale locale(QString::fromLatin1(it->second.c_str()));
331 QString native = locale.nativeLanguageName();
332 if (!native.isEmpty()) {
333 if (native[0].isLetter()) {
334 native[0] = native[0].toUpper();
335 }
336 langname = native;
337 }
338
339 ui->Languages->addItem(langname, lang);
340 if (language == lang) {
341 ui->Languages->setCurrentIndex(index);
342 }
343 }
344
345 QAbstractItemModel* model = ui->Languages->model();
346 if (model) {
347 model->sort(0);
348 }
349
350 addIconSizes(getCurrentIconSize());
351
352 // TreeMode combobox setup.
353 loadDockWindowVisibility();
354
355 hGrp = App::GetApplication().GetParameterGroupByPath(
356 "User parameter:BaseApp/Preferences/MainWindow"
357 );
358 ui->tiledBackground->setChecked(hGrp->GetBool("TiledBackground", false));
359
360 loadThemes();
361 }
362
363 void DlgSettingsGeneral::resetSettingsToDefaults()
364 {
365 ParameterGrp::handle hGrp;
366 hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units");
367 // reset "UserSchema" parameter
368 hGrp->RemoveInt("UserSchema");
369 // reset "Decimals" parameter
370 hGrp->RemoveInt("Decimals");
371 // reset "IgnoreProjectSchema" parameter
372 hGrp->RemoveBool("IgnoreProjectSchema");
373 // reset "FracInch" parameter
374 hGrp->RemoveInt("FracInch");
375
376 hGrp = App::GetApplication().GetParameterGroupByPath(
377 "User parameter:BaseApp/Preferences/MainWindow"
378 );
379 // reset "Theme" parameter
380 hGrp->RemoveASCII("Theme");
381 // reset "TiledBackground" parameter
382 hGrp->RemoveBool("TiledBackground");
383
384
385 hGrp = App::GetApplication().GetParameterGroupByPath(
386 "User parameter:BaseApp/Preferences/DockWindows"
387 );
388 // reset "ComboView" parameters
389 hGrp->GetGroup("ComboView")->RemoveBool("Enabled");
390 // reset "TreeView" parameters
391 hGrp->GetGroup("TreeView")->RemoveBool("Enabled");
392 // reset "PropertyView" parameters
393 hGrp->GetGroup("PropertyView")->RemoveBool("Enabled");
394
395 hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
396 // reset "Language" parameter
397 hGrp->RemoveASCII("Language");
398 // reset "ToolbarIconSize" parameter
399 hGrp->RemoveInt("ToolbarIconSize");
400
401 // finally reset all the parameters associated to Gui::Pref* widgets
402 PreferencePage::resetSettingsToDefaults();
403 }
404
405 void DlgSettingsGeneral::saveThemes()
406 {
407 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
408 "User parameter:BaseApp/Preferences/MainWindow"
409 );
410
411 // First we check if the theme has actually changed.
412 std::string previousTheme = hGrp->GetASCII("Theme", "").c_str();
413 std::string newTheme = ui->themesCombobox->currentText().toStdString();
414
415 if (previousTheme == newTheme) {
416 themeChanged = false;
417 return;
418 }
419
420 // Save the name of the theme
421 hGrp->SetASCII("Theme", newTheme);
422
423 // Then we apply the themepack.
424 Application::Instance->prefPackManager()->rescan();
425 auto packs = Application::Instance->prefPackManager()->preferencePacks();
426
427 for (const auto& pack : packs) {
428 if (pack.first == newTheme) {
429
430 if (Application::Instance->prefPackManager()->apply(pack.first)) {
431 auto parentDialog = qobject_cast<DlgPreferencesImp*>(this->window());
432 if (parentDialog) {
433 parentDialog->reload();
434 }
435 }
436 break;
437 }
438 }
439
440 themeChanged = false;
441 }
442
443 void DlgSettingsGeneral::loadThemes()
444 {
445 ui->themesCombobox->clear();
446
447 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
448 "User parameter:BaseApp/Preferences/MainWindow"
449 );
450
451 QString currentTheme = QString::fromLatin1(hGrp->GetASCII("Theme", "").c_str());
452
453 Application::Instance->prefPackManager()->rescan();
454 auto packs = Application::Instance->prefPackManager()->preferencePacks();
455 QString currentStyleSheet = QString::fromLatin1(hGrp->GetASCII("StyleSheet", "").c_str());
456 QFileInfo fi(currentStyleSheet);
457 currentStyleSheet = fi.baseName();
458 QString themeClassic = QStringLiteral("classic"); // handle the upcoming name change
459 QString similarTheme;
460 QString packName;
461 for (const auto& pack : packs) {
462 if (pack.second.metadata().type() == "Theme") {
463 packName = QString::fromStdString(pack.first);
464 if (packName.contains(themeClassic, Qt::CaseInsensitive)) {
465 themeClassic = QString::fromStdString(pack.first);
466 }
467 if (packName.contains(currentStyleSheet, Qt::CaseInsensitive)) {
468 similarTheme = QString::fromStdString(pack.first);
469 }
470 ui->themesCombobox->addItem(QString::fromStdString(pack.first));
471 }
472 }
473
474 if (currentTheme.isEmpty()) {
475 if (!currentStyleSheet.isEmpty() && !similarTheme.isEmpty()) { // a user upgrading from
476 // 0.21 or earlier
477 hGrp->SetASCII("Theme", similarTheme.toStdString());
478 currentTheme = QString::fromLatin1(hGrp->GetASCII("Theme", "").c_str());
479 }
480 else { // a brand new user
481 hGrp->SetASCII("Theme", themeClassic.toStdString());
482 currentTheme = QString::fromLatin1(hGrp->GetASCII("Theme", "").c_str());
483 }
484 }
485
486 int index = ui->themesCombobox->findText(currentTheme);
487 if (index >= 0 && index < ui->themesCombobox->count()) {
488 ui->themesCombobox->setCurrentIndex(index);
489 }
490 }
491
492 int DlgSettingsGeneral::getCurrentIconSize() const
493 {
494 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
495 int current = getMainWindow()->iconSize().width();
496 return hGrp->GetInt("ToolbarIconSize", current);
497 }
498
499 void DlgSettingsGeneral::addIconSizes(int current)
500 {
501 ui->toolbarIconSize->clear();
502
503 QList<int> sizes {16, 24, 32, 48};
504 if (!sizes.contains(current)) {
505 sizes.append(current);
506 }
507
508 for (int size : sizes) {
509 ui->toolbarIconSize->addItem(QString(), QVariant(size));
510 }
511
512 int index = ui->toolbarIconSize->findData(QVariant(current));
513 ui->toolbarIconSize->setCurrentIndex(index);
514 translateIconSizes();
515 }
516
517 void DlgSettingsGeneral::translateIconSizes()
518 {
519 auto getSize = [this](int index) {
520 return ui->toolbarIconSize->itemData(index).toInt();
521 };
522
523 QStringList sizes;
524 sizes << tr("Small (%1px)").arg(getSize(0));
525 sizes << tr("Medium (%1px)").arg(getSize(1));
526 sizes << tr("Large (%1px)").arg(getSize(2));
527 sizes << tr("Extra large (%1px)").arg(getSize(3));
528 if (ui->toolbarIconSize->count() > 4) {
529 sizes << tr("Custom (%1px)").arg(getSize(4));
530 }
531
532 for (int index = 0; index < sizes.size(); index++) {
533 ui->toolbarIconSize->setItemText(index, sizes[index]);
534 }
535 }
536
537 void DlgSettingsGeneral::retranslateUnits()
538 {
539 auto setItem = [&, index {0}](const std::string& item) mutable {
540 ui->comboBox_UnitSystem->setItemText(index++, QString::fromStdString(item));
541 };
542 const auto descriptions = UnitsApi::getDescriptions();
543 std::for_each(descriptions.begin(), descriptions.end(), setItem);
544 }
545
546 void DlgSettingsGeneral::changeEvent(QEvent* event)
547 {
548 if (event->type() == QEvent::LanguageChange) {
549 translateIconSizes();
550 retranslateUnits();
551 int index = ui->UseLocaleFormatting->currentIndex();
552 ui->retranslateUi(this);
553 ui->UseLocaleFormatting->setCurrentIndex(index);
554 }
555 else {
556 QWidget::changeEvent(event);
557 }
558 }
559
560 void DlgSettingsGeneral::saveDockWindowVisibility()
561 {
562 auto hGrp = App::GetApplication().GetParameterGroupByPath(
563 "User parameter:BaseApp/Preferences/DockWindows"
564 );
565 bool treeView = hGrp->GetGroup("TreeView")->GetBool("Enabled", false);
566 bool propertyView = hGrp->GetGroup("PropertyView")->GetBool("Enabled", false);
567 bool comboView = hGrp->GetGroup("ComboView")->GetBool("Enabled", true);
568
569 int index = -1;
570 if (propertyView || treeView) {
571 index = 1;
572 }
573 else if (comboView) {
574 index = 0;
575 }
576
577 if (index != ui->treeMode->currentIndex()) {
578 requireRestart();
579 }
580
581 switch (ui->treeMode->currentIndex()) {
582 case 0:
583 comboView = true;
584 treeView = propertyView = false;
585 break;
586 case 1:
587 treeView = propertyView = true;
588 comboView = false;
589 break;
590 }
591
592 hGrp->GetGroup("ComboView")->SetBool("Enabled", comboView);
593 hGrp->GetGroup("TreeView")->SetBool("Enabled", treeView);
594 hGrp->GetGroup("PropertyView")->SetBool("Enabled", propertyView);
595 }
596
597 void DlgSettingsGeneral::loadDockWindowVisibility()
598 {
599 ui->treeMode->clear();
600 ui->treeMode->addItem(tr("Combined"));
601 ui->treeMode->addItem(tr("Independent"));
602
603 auto hGrp = App::GetApplication().GetParameterGroupByPath(
604 "User parameter:BaseApp/Preferences/DockWindows"
605 );
606 bool propertyView = hGrp->GetGroup("PropertyView")->GetBool("Enabled", false);
607 bool treeView = hGrp->GetGroup("TreeView")->GetBool("Enabled", false);
608 bool comboView = hGrp->GetGroup("ComboView")->GetBool("Enabled", true);
609 int index = -1;
610 if (propertyView || treeView) {
611 index = 1;
612 }
613 else if (comboView) {
614 index = 0;
615 }
616 ui->treeMode->setCurrentIndex(index);
617 }
618
619 void DlgSettingsGeneral::recreatePreferencePackMenu()
620 {
621 ui->PreferencePacks->setRowCount(0); // Begin by clearing whatever is there
622 ui->PreferencePacks->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
623 ui->PreferencePacks->setColumnCount(3);
624 ui->PreferencePacks->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
625 ui->PreferencePacks->horizontalHeader()->setStretchLastSection(false);
626 ui->PreferencePacks->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch);
627 ui->PreferencePacks->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeMode::Stretch);
628 ui->PreferencePacks->horizontalHeader()->setSectionResizeMode(
629 2,
630 QHeaderView::ResizeMode::ResizeToContents
631 );
632 QStringList columnHeaders;
633 columnHeaders << tr("Preference Pack Name") << tr("Tags")
634 << QString(); // for the "Load" buttons
635 ui->PreferencePacks->setHorizontalHeaderLabels(columnHeaders);
636
637 // Populate the Preference Packs list
638 Application::Instance->prefPackManager()->rescan();
639 auto packs = Application::Instance->prefPackManager()->preferencePacks();
640
641 // Remove the Themes.
642 std::vector<std::string> packsToRemove;
643 for (const auto& pack : packs) {
644 if (pack.second.metadata().type() == "Theme") {
645 packsToRemove.push_back(pack.first); // Store the keys to remove later
646 }
647 }
648 for (const auto& key : packsToRemove) {
649 packs.erase(key); // Remove the elements from the map
650 }
651
652 ui->PreferencePacks->setRowCount(packs.size());
653
654 int row = 0;
655 QIcon icon = style()->standardIcon(QStyle::SP_DialogApplyButton);
656 for (const auto& pack : packs) {
657 auto name = new QTableWidgetItem(QString::fromStdString(pack.first));
658 name->setToolTip(QString::fromStdString(pack.second.metadata().description()));
659 ui->PreferencePacks->setItem(row, 0, name);
660 auto tags = pack.second.metadata().tag();
661 QString tagString;
662 for (const auto& tag : tags) {
663 if (tagString.isEmpty()) {
664 tagString.append(QString::fromStdString(tag));
665 }
666 else {
667 tagString.append(QStringLiteral(", ") + QString::fromStdString(tag));
668 }
669 }
670 auto kind = new QTableWidgetItem(tagString);
671 ui->PreferencePacks->setItem(row, 1, kind);
672 auto button = new QPushButton(icon, tr("Apply"));
673 button->setEnabled(true);
674 Gui::Document* doc = Gui::Application::Instance->activeDocument();
675 if (doc) {
676 Gui::View3DInventor* view = qobject_cast<Gui::View3DInventor*>(doc->getActiveView());
677 if (view) {
678 Gui::View3DInventorViewer* viewer = view->getViewer();
679 if (viewer->isEditing()) {
680 button->setEnabled(false);
681 }
682 }
683 }
684 if (button->isEnabled()) {
685 button->setToolTip(
686 tr("Applies the %1 preference pack").arg(QString::fromStdString(pack.first))
687 );
688 connect(button, &QPushButton::clicked, this, [this, pack]() {
689 onLoadPreferencePackClicked(pack.first);
690 });
691 }
692 ui->PreferencePacks->setCellWidget(row, 2, button);
693 ++row;
694 }
695 }
696
697 void DlgSettingsGeneral::saveAsNewPreferencePack()
698 {
699 // Create and run a modal New PreferencePack dialog box
700 auto packs = Application::Instance->prefPackManager()->preferencePackNames();
701 newPreferencePackDialog = std::make_unique<DlgCreateNewPreferencePackImp>(this);
702 newPreferencePackDialog->setPreferencePackTemplates(
703 Application::Instance->prefPackManager()->templateFiles()
704 );
705 newPreferencePackDialog->setPreferencePackNames(packs);
706 connect(
707 newPreferencePackDialog.get(),
708 &DlgCreateNewPreferencePackImp::accepted,
709 this,
710 &DlgSettingsGeneral::newPreferencePackDialogAccepted
711 );
712 newPreferencePackDialog->open();
713 }
714
715 void DlgSettingsGeneral::revertToSavedConfig()
716 {
717 revertToBackupConfigDialog = std::make_unique<DlgRevertToBackupConfigImp>(this);
718 connect(revertToBackupConfigDialog.get(), &DlgRevertToBackupConfigImp::accepted, this, [this]() {
719 auto parentDialog = qobject_cast<DlgPreferencesImp*>(this->window());
720 if (parentDialog) {
721 parentDialog->reload();
722 }
723 });
724 revertToBackupConfigDialog->open();
725 }
726
727 void DlgSettingsGeneral::newPreferencePackDialogAccepted()
728 {
729 auto preferencePackTemplates = Application::Instance->prefPackManager()->templateFiles();
730 auto selection = newPreferencePackDialog->selectedTemplates();
731 std::vector<PreferencePackManager::TemplateFile> selectedTemplates;
732 std::copy_if(
733 preferencePackTemplates.begin(),
734 preferencePackTemplates.end(),
735 std::back_inserter(selectedTemplates),
736 [selection](PreferencePackManager::TemplateFile& tf) {
737 for (const auto& item : selection) {
738 if (item.group == tf.group && item.name == tf.name) {
739 return true;
740 }
741 }
742 return false;
743 }
744 );
745 auto preferencePackName = newPreferencePackDialog->preferencePackName();
746 auto preferencePackDirectory = newPreferencePackDialog->preferencePackDirectory();
747 Application::Instance->prefPackManager()
748 ->save(preferencePackName, preferencePackDirectory, selectedTemplates);
749 recreatePreferencePackMenu();
750 }
751
752 void DlgSettingsGeneral::onManagePreferencePacksClicked()
753 {
754 if (!this->preferencePackManagementDialog) {
755 this->preferencePackManagementDialog = std::make_unique<DlgPreferencePackManagementImp>(this);
756 connect(
757 this->preferencePackManagementDialog.get(),
758 &DlgPreferencePackManagementImp::packVisibilityChanged,
759 this,
760 &DlgSettingsGeneral::recreatePreferencePackMenu
761 );
762 }
763 this->preferencePackManagementDialog->show();
764 }
765
766 void DlgSettingsGeneral::onImportConfigClicked()
767 {
768 auto path = fs::path(
769 QFileDialog::getOpenFileName(
770 this,
771 tr("Choose a FreeCAD config file to import"),
772 QString(),
773 QStringLiteral("*.cfg")
774 )
775 .toStdString()
776 );
777 if (!path.empty()) {
778 // Create a name from the filename:
779 auto packName = path.filename().stem().string();
780 std::replace(packName.begin(), packName.end(), '_', ' ');
781 auto existingPacks = Application::Instance->prefPackManager()->preferencePackNames();
782 if (std::ranges::find(existingPacks, packName) != existingPacks.end()) {
783 auto result = QMessageBox::question(
784 this,
785 tr("File exists"),
786 tr("A preference pack with that name already exists. Overwrite?")
787 );
788 if (result == QMessageBox::No) { // Maybe someday ask for a new name?
789 return;
790 }
791 }
792 Application::Instance->prefPackManager()->importConfig(packName, path);
793 recreatePreferencePackMenu();
794 }
795 }
796
797 void DlgSettingsGeneral::onLoadPreferencePackClicked(const std::string& packName)
798 {
799 if (Application::Instance->prefPackManager()->apply(packName)) {
800 auto parentDialog = qobject_cast<DlgPreferencesImp*>(this->window());
801 if (parentDialog) {
802 parentDialog->reload();
803 }
804 }
805 }
806
807 void DlgSettingsGeneral::onUnitSystemIndexChanged(const int index)
808 {
809 if (index < 0) {
810 return; // happens when clearing the combo box in retranslateUi()
811 }
812
813 // Enable/disable the fractional inch option depending on system
814 const auto schema = UnitsApi::createSchema(index);
815 const auto visible = schema->isMultiUnitLength();
816 ui->comboBox_FracInch->setVisible(visible);
817 ui->fractionalInchLabel->setVisible(visible);
818 }
819
820 void DlgSettingsGeneral::onThemeChanged(int index)
821 {
822 Q_UNUSED(index);
823 themeChanged = true;
824 }
825
826 void DlgSettingsGeneral::onLinkActivated(const QString& link)
827 {
828 auto const addonManagerLink = QStringLiteral("freecad:Std_AddonMgr");
829
830 if (link != addonManagerLink) {
831 return;
832 }
833
834 // Set the user preferences to include only preference packs.
835 // This is a quick and dirty way to open Addon Manager with only themes.
836 auto pref = App::GetApplication().GetParameterGroupByPath(
837 "User parameter:BaseApp/Preferences/Addons"
838 );
839 pref->SetInt("PackageTypeSelection", 3); // 3 stands for Preference Packs
840 pref->SetInt("StatusSelection", 0); // 0 stands for any installation status
841
842 Gui::Application::Instance->commandManager().runCommandByName("Std_AddonMgr");
843 }
844
845 ///////////////////////////////////////////////////////////
846 namespace
847 {
848
849 class ApplyDockWidget: public ParamHandler
850 {
851 public:
852 bool onChange(const ParamKey*) override
853 {
854 OverlayManager::instance()->reload(OverlayManager::ReloadMode::ReloadPause);
855 return true;
856 }
857
858 void onTimer() override
859 {
860 getMainWindow()->initDockWindows(true);
861 OverlayManager::instance()->reload(OverlayManager::ReloadMode::ReloadResume);
862 }
863 };
864
865 } // anonymous namespace
866
867 void DlgSettingsGeneral::attachObserver()
868 {
869 static ParamHandlers handlers;
870
871 auto hDockWindows = App::GetApplication().GetUserParameter().GetGroup(
872 "BaseApp/Preferences/DockWindows"
873 );
874 auto applyDockWidget = std::shared_ptr<ParamHandler>(new ApplyDockWidget);
875 handlers.addHandler(ParamKey(hDockWindows->GetGroup("ComboView"), "Enabled"), applyDockWidget);
876 handlers.addHandler(ParamKey(hDockWindows->GetGroup("TreeView"), "Enabled"), applyDockWidget);
877 handlers.addHandler(ParamKey(hDockWindows->GetGroup("PropertyView"), "Enabled"), applyDockWidget);
878 handlers.addHandler(ParamKey(hDockWindows->GetGroup("DAGView"), "Enabled"), applyDockWidget);
879 }
880
881 #include "moc_DlgSettingsGeneral.cpp"