FreeCAD

Форк
0
/
DlgPreferencePackManagementImp.cpp 
219 строк · 9.8 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2022 Chris Hennes <chennes@pioneerlibrarysystem.org>    *
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
#include "PreCompiled.h"
24
#ifndef _PreComp_
25
# include <QMessageBox>
26
#endif
27

28
#include "DlgPreferencePackManagementImp.h"
29
#include "ui_DlgPreferencePackManagement.h"
30
#include "Application.h"
31
#include "Command.h"
32
#include "PreferencePackManager.h"
33

34

35
using namespace Gui::Dialog;
36
namespace fs = boost::filesystem;
37

38
/* TRANSLATOR Gui::Dialog::DlgPreferencePackManagementImp */
39

40
/**
41
 *  Constructs a Gui::Dialog::DlgPreferencePackManagementImp as a child of 'parent'
42
 */
43
DlgPreferencePackManagementImp::DlgPreferencePackManagementImp(QWidget* parent)
44
    : QDialog(parent)
45
    , ui(new Ui_DlgPreferencePackManagement)
46
{
47
    ui->setupUi(this);
48
    connect(ui->pushButtonOpenAddonManager, &QPushButton::clicked, this, &DlgPreferencePackManagementImp::showAddonManager);
49
}
50

51
void DlgPreferencePackManagementImp::showEvent(QShowEvent* event)
52
{
53
    // Separate out user-saved packs from installed packs: we can remove individual user-saved packs,
54
    // but can only disable individual installed packs (though we can completely uninstall the pack's
55
    // containing Addon by redirecting to the Addon Manager).
56
    auto savedPreferencePacksDirectory = fs::path(App::Application::getUserAppDataDir()) / "SavedPreferencePacks";
57
    auto modDirectory = fs::path(App::Application::getUserAppDataDir()) / "Mod";
58
    auto resourcePath = fs::path(App::Application::getResourceDir()) / "Gui" / "PreferencePacks";
59

60
    // The displayed tree has two levels: at the toplevel is either "User-Saved Packs" or the name
61
    // of the addon containing the pack. Beneath those are the individual packs themselves. The tree view shows
62
    // "Hide"/"Show" for packs installed as a Mod, and "Delete" for packs in the user-saved pack
63
    // section.
64
    auto userPacks = getPacksFromDirectory(savedPreferencePacksDirectory);
65

66
    auto builtinPacks = getPacksFromDirectory(resourcePath);
67

68
    std::map<std::string, std::vector<std::string>> installedPacks;
69
    if (fs::exists(modDirectory) && fs::is_directory(modDirectory)) {
70
        for (const auto& mod : fs::directory_iterator(modDirectory)) {
71
            auto packs = getPacksFromDirectory(mod);
72
            if (!packs.empty()) {
73
                auto modName = mod.path().filename().string();
74
                installedPacks.emplace(modName, packs);
75
            }
76
        }
77
    }
78

79
    ui->treeWidget->clear(); // Begin by clearing whatever is there
80
    ui->treeWidget->header()->setDefaultAlignment(Qt::AlignLeft);
81
    ui->treeWidget->setColumnCount(2);
82
    ui->treeWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
83
    ui->treeWidget->header()->setStretchLastSection(false);
84
    ui->treeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch);
85
    ui->treeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeMode::ResizeToContents);
86

87
    if (!userPacks.empty()) {
88
        addTreeNode(tr("User-Saved Preference Packs").toStdString(), userPacks, TreeWidgetType::USER);
89
    }
90

91
    if (!builtinPacks.empty()) {
92
        addTreeNode(tr("Built-In Preference Packs").toStdString(), builtinPacks, TreeWidgetType::BUILTIN);
93
    }
94

95
    for (const auto& installedPack : installedPacks) {
96
        addTreeNode(installedPack.first, installedPack.second, TreeWidgetType::ADDON);
97
    }
98

99
    if (event)
100
        QDialog::showEvent(event);
101
}
102

103
void DlgPreferencePackManagementImp::addTreeNode(const std::string &name, const std::vector<std::string> &contents, TreeWidgetType twt)
104
{
105
    static const auto iconIsVisible = QIcon(QLatin1String(":/icons/dagViewVisible.svg"));
106
    static const auto iconIsInvisible = QIcon(QLatin1String(":/icons/Invisible.svg"));
107
    auto packRoot = new QTreeWidgetItem();
108
    packRoot->setText(0, QString::fromStdString(name));
109
    std::vector<QTreeWidgetItem*> items;
110
    for (const auto& packName : contents) {
111
        auto pack = new QTreeWidgetItem(packRoot);
112
        pack->setText(0, QString::fromStdString(packName));
113
        items.push_back(pack);
114
    }
115
    ui->treeWidget->addTopLevelItem(packRoot);
116
    packRoot->setExpanded(true);
117
    for (const auto item : items) {
118
        auto button = new QPushButton();
119
        button->setFlat(true);
120
        switch (twt) {
121
        break; case TreeWidgetType::BUILTIN:
122
            // The button is a "hide" button
123
            if (Application::Instance->prefPackManager()->isVisible("##BUILT_IN##", item->text(0).toStdString()))
124
                button->setIcon(iconIsVisible);
125
            else
126
                button->setIcon(iconIsInvisible);
127
            button->setToolTip(tr("Toggle visibility of built-in preference pack '%1'").arg(item->text(0)));
128
            connect(button, &QPushButton::clicked, [this, name, item]() {
129
                this->hideBuiltInPack(item->text(0).toStdString());
130
                });
131
        break; case TreeWidgetType::USER:
132
            // The button is a "delete" button
133
            button->setIcon(QIcon(QLatin1String(":/icons/delete.svg")));
134
            button->setToolTip(tr("Delete user-saved preference pack '%1'").arg(item->text(0)));
135
            connect(button, &QPushButton::clicked, [this, item]() {
136
                this->deleteUserPack(item->text(0).toStdString());
137
                });
138
        break; case TreeWidgetType::ADDON:
139
            // The button is a "hide" button
140
            if (Application::Instance->prefPackManager()->isVisible(name, item->text(0).toStdString()))
141
                button->setIcon(iconIsVisible);
142
            else
143
                button->setIcon(iconIsInvisible);
144
            button->setToolTip(tr("Toggle visibility of Addon preference pack '%1' (use Addon Manager to permanently remove)").arg(item->text(0)));
145
            connect(button, &QPushButton::clicked, [this, name, item]() {
146
                this->hideInstalledPack(name, item->text(0).toStdString());
147
                });
148
        }
149
        ui->treeWidget->setItemWidget(item, 1, button);
150
    }
151
}
152

153
std::vector<std::string> DlgPreferencePackManagementImp::getPacksFromDirectory(const fs::path& path) const
154
{
155
    std::vector<std::string> results;
156
    auto packageMetadataFile = path / "package.xml";
157
    if (fs::exists(packageMetadataFile) && fs::is_regular_file(packageMetadataFile)) {
158
        try {
159
            App::Metadata metadata(packageMetadataFile);
160
            auto content = metadata.content();
161
            for (const auto& item : content) {
162
                if (item.first == "preferencepack") {
163
                    results.push_back(item.second.name());
164
                }
165
            }
166
        }
167
        catch (...) {
168
            // Failed to read the metadata, or to create the preferencePack based on it...
169
            Base::Console().Error(("Failed to read " + packageMetadataFile.string()).c_str());
170
        }
171
    }
172
    return results;
173
}
174

175

176
void DlgPreferencePackManagementImp::deleteUserPack(const std::string& name)
177
{
178
    // Do the deletion here...
179
    auto result = QMessageBox::warning(this, tr("Delete saved preference pack?"),
180
        tr("Are you sure you want to delete the preference pack named '%1'? This cannot be undone.").arg(QString::fromStdString(name)),
181
        QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
182
    if (result == QMessageBox::Yes) {
183
        Application::Instance->prefPackManager()->deleteUserPack(name);
184
        showEvent(nullptr);
185
        Q_EMIT packVisibilityChanged();
186
    }
187
}
188

189
void DlgPreferencePackManagementImp::hideBuiltInPack(const std::string& prefPackName)
190
{
191
    Application::Instance->prefPackManager()->toggleVisibility("##BUILT_IN##", prefPackName);
192
    showEvent(nullptr);
193
    Q_EMIT packVisibilityChanged();
194
}
195

196
void DlgPreferencePackManagementImp::hideInstalledPack(const std::string& addonName, const std::string& prefPackName)
197
{
198
    Application::Instance->prefPackManager()->toggleVisibility(addonName, prefPackName);
199
    showEvent(nullptr);
200
    Q_EMIT packVisibilityChanged();
201
}
202

203
void DlgPreferencePackManagementImp::showAddonManager()
204
{
205
    // Configure the view to show all preference packs (installed and uninstalled)
206
    auto pref = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Addons");
207
    pref->SetInt("PackageTypeSelection", 3);
208
    pref->SetInt("StatusSelection", 0);
209

210
    CommandManager& rMgr = Application::Instance->commandManager();
211
    rMgr.runCommandByName("Std_AddonMgr");
212
    close();
213
}
214

215
DlgPreferencePackManagementImp::~DlgPreferencePackManagementImp() = default;
216

217

218

219
#include "moc_DlgPreferencePackManagementImp.cpp"
220

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.