File: modulesmodel.cpp

package info (click to toggle)
plasma-settings 25.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 844 kB
  • sloc: cpp: 1,213; xml: 124; makefile: 3; sh: 1
file content (336 lines) | stat: -rw-r--r-- 10,593 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
    SPDX-FileCopyrightText: 2009 Ben Cooksley <bcooksley@kde.org>
    SPDX-FileCopyrightText: 2007 Will Stephenson <wstephenson@kde.org>
    SPDX-FileCopyrightText: 2019 Nicolas Fella <nicolas.fella@gmx.de>
    SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "modulesmodel.h"

#include <QDebug>
#include <QQuickItem>
#include <QSet>
#include <QStandardPaths>

#include <KAuthorized>
#include <KCategorizedSortFilterProxyModel>
#include <KConfigGroup>
#include <KDesktopFile>
#include <KFileUtils>
#include <KJsonUtils>
#include <KPluginFactory>
#include <KRuntimePlatform>

using namespace Qt::Literals::StringLiterals;

ModulesModel::ModulesModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_rootModule{nullptr}
{
    qDebug() << "Current platform is " << KRuntimePlatform::runtimePlatform();
    initModules();
}

void ModulesModel::initModules()
{
    MenuItem *oldRootModule = m_rootModule;
    m_rootModule = new MenuItem{true, nullptr};

    // Filter to whether the kcm belongs to the current platform (unless m_ignorePlatforms = true),
    // also respect kiosk / KAuthorize restrictions and filter out "forbidden" allowed modules
    auto filter = [this](const KPluginMetaData &data) {

        if (!KAuthorized::authorizeControlModule(data.pluginId())) {
            return false;
        }

        if (m_ignorePlatforms) {
            return true;
        }

        auto kRuntimePlatforms = KRuntimePlatform::runtimePlatform();

        // HACK: currently on desktop no form factors are specified
        if (kRuntimePlatforms.empty()) {
            kRuntimePlatforms.append(QStringLiteral("desktop"));
        }

        // Filter out if the form factor does not match the current runtime platform.
        // If the KCM defines "all" or has no defined form factor, don't filter.
        for (const auto &formFactor : data.formFactors()) {
            if (formFactor == QStringLiteral("all")) {
                return true;
            }
            if (kRuntimePlatforms.contains(formFactor)) {
                return true;
            }
        }
        return data.formFactors().empty();
    };

    QList<KPluginMetaData> kcms = KPluginMetaData::findPlugins(u"kcms"_s, filter);
    kcms << KPluginMetaData::findPlugins(u"plasma/kcms"_s, filter);
    kcms << KPluginMetaData::findPlugins(u"plasma/kcms/systemsettings"_s, filter);

    const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::AppDataLocation, QStringLiteral("categories"), QStandardPaths::LocateDirectory);
    QStringList categories = KFileUtils::findAllUniqueFiles(dirs, QStringList(QStringLiteral("*.desktop")));

    initMenuList(m_rootModule, kcms, categories);

    if (oldRootModule) {
        delete oldRootModule;
    }
}

void ModulesModel::initMenuList(MenuItem *parent, const QList<KPluginMetaData> &kcms, const QStringList &categories)
{
    // look for any categories inside this level, and recurse into them
    for (const QString &category : std::as_const(categories)) {
        const KDesktopFile file(category);
        const KConfigGroup entry = file.desktopGroup();
        QString parentCategory = entry.readEntry("X-KDE-System-Settings-Parent-Category");
        QString parentCategory2 = entry.readEntry("X-KDE-System-Settings-Parent-Category-V2");

        if (parentCategory == parent->category() ||
            // V2 entries must not be empty if they want to become a proper category.
            (!parentCategory2.isEmpty() && parentCategory2 == parent->category())) {
            auto menuItem = new MenuItem(true, parent);
            menuItem->setCategoryConfig(file);
            if (entry.readEntry("X-KDE-System-Settings-Category") == QLatin1String("lost-and-found")) {
                // Skip lost and found for now
                continue;
            }
            initMenuList(menuItem, kcms, categories);
        }
    }

    // scan for any modules at this level and add them
    for (const auto &metaData : std::as_const(kcms)) {
        QString category = metaData.value(QStringLiteral("X-KDE-System-Settings-Parent-Category"));
        QString categoryv2 = metaData.value(QStringLiteral("X-KDE-System-Settings-Parent-Category-V2"));
        const QString parentCategoryKcm = parent->systemsettingsCategoryModule();
        bool isCategoryOwner = false;

        if (!parentCategoryKcm.isEmpty() && parentCategoryKcm == metaData.pluginId()) {
            parent->setMetaData(metaData);
            isCategoryOwner = true;
        }

        if (!parent->category().isEmpty() && (category == parent->category() || categoryv2 == parent->category())) {
            if (!metaData.isHidden()) {
                // Add the module info to the menu
                auto infoItem = new MenuItem(false, parent);
                infoItem->setMetaData(metaData);
                infoItem->setCategoryOwner(isCategoryOwner);
            }
        }
    }

    parent->sortChildrenByWeight();
}

QVariant ModulesModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() < 0 || index.row() >= rowCount()) {
        return {};
    }

    auto mi = static_cast<MenuItem *>(index.internalPointer());

    switch (role) {
    case MenuItemRole:
        return QVariant::fromValue(mi);
    case NameRole:
        return mi->name();
    case DescriptionRole:
        return mi->description();
    case IconNameRole:
        return mi->iconName();
    case IdRole:
        return mi->id();
    case UserFilterRole:
        // We join by ZERO WIDTH SPACE to avoid awkward word merging in search terms
        // e.g. ['keys', 'slow'] should match 'keys' and 'slow' but not 'ssl'.
        // https://bugs.kde.org/show_bug.cgi?id=487855
        return mi->keywords().join(u"\u200B"_s);
        break;
    case UserSortRole:
        // Category owners are always before everything else, regardless of weight
        if (mi->isCategoryOwner()) {
            return QStringLiteral("%1").arg(QString::number(mi->weight()), 5, QLatin1Char('0'));
        } else {
            return QStringLiteral("1%1").arg(QString::number(mi->weight()), 5, QLatin1Char('0'));
        }
        break;
    case KCategorizedSortFilterProxyModel::CategorySortRole:
        if (mi->parent()) {
            return QStringLiteral("%1%2").arg(QString::number(mi->parent()->weight()), 5, QLatin1Char('0')).arg(mi->parent()->name());
        }
        break;
    case KCategorizedSortFilterProxyModel::CategoryDisplayRole: {
        MenuItem *candidate = mi->parent();
        // The model has an invisible single root item.
        // So to get the "root category" we don't go up all the way
        // To the actual root, but to the list of the first childs.
        // That's why we check for candidate->parent()->parent()
        while (candidate && candidate->parent() && candidate->parent()->parent()) {
            candidate = candidate->parent();
        }
        if (candidate) {
            // Children of this special root category don't have an user visible category
            if (!candidate->isSystemsettingsRootCategory()) {
                return candidate->name();
            }
        }
        break;
    }
    case IsCategoryRole:
        return mi->menu();
    case IsKCMRole:
        return mi->isLibrary();
    }

    return {};
}

int ModulesModel::columnCount(const QModelIndex & /*parent*/) const
{
    return 1;
}

int ModulesModel::rowCount(const QModelIndex &parent) const
{
    MenuItem *mi;
    if (parent.isValid()) {
        mi = static_cast<MenuItem *>(parent.internalPointer());
    } else {
        mi = m_rootModule;
    }
    return childrenList(mi).count();
}

QHash<int, QByteArray> ModulesModel::roleNames() const
{
    QHash<int, QByteArray> names = QAbstractItemModel::roleNames();
    names[NameRole] = "name";
    names[DescriptionRole] = "description";
    names[IconNameRole] = "iconName";
    names[IdRole] = "pluginId";
    names[IsCategoryRole] = "isCategory";
    names[IsKCMRole] = "isKCM";
    return names;
}

Qt::ItemFlags ModulesModel::flags(const QModelIndex &index) const
{
    if (!index.isValid()) {
        return Qt::NoItemFlags;
    }

    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QModelIndex ModulesModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!hasIndex(row, column, parent)) {
        return {};
    }

    MenuItem *parentItem;
    if (!parent.isValid()) {
        parentItem = m_rootModule;
    } else {
        parentItem = static_cast<MenuItem *>(parent.internalPointer());
    }

    MenuItem *childItem = childrenList(parentItem).value(row);
    if (childItem) {
        return createIndex(row, column, childItem);
    } else {
        return {};
    }
}

QModelIndex ModulesModel::parent(const QModelIndex &index) const
{
    auto childItem = static_cast<MenuItem *>(index.internalPointer());
    if (!childItem) {
        return {};
    }

    MenuItem *parent = parentItem(childItem);
    MenuItem *grandParent = parentItem(parent);

    int childRow = 0;
    if (grandParent) {
        childRow = childrenList(grandParent).indexOf(parent);
    }

    if (parent == m_rootModule) {
        return {};
    }
    return createIndex(childRow, 0, parent);
}

QList<MenuItem *> ModulesModel::childrenList(MenuItem *parent) const
{
    QList<MenuItem *> children = parent->children();
    for (MenuItem *child : children) {
        if (m_exceptions.contains(child)) {
            children.removeOne(child);
            children.append(child->children());
        }
    }
    return children;
}

MenuItem *ModulesModel::parentItem(MenuItem *child) const
{
    MenuItem *parent = child->parent();
    if (m_exceptions.contains(parent)) {
        parent = parentItem(parent);
    }
    return parent;
}

void ModulesModel::addException(MenuItem *exception)
{
    if (exception == m_rootModule) {
        return;
    }
    m_exceptions.append(exception);
}

void ModulesModel::removeException(MenuItem *exception)
{
    m_exceptions.removeAll(exception);
}

void ModulesModel::reset()
{
    beginResetModel();
    initModules();

    // Have top level KCMs be shown, not just categories (which are their parent)
    for (MenuItem *child : m_rootModule->children()) {
        addException(child);
    }
    endResetModel();
}

bool ModulesModel::ignorePlatforms() const
{
    return m_ignorePlatforms;
}

void ModulesModel::setIgnorePlatforms(bool ignorePlatforms)
{
    m_ignorePlatforms = ignorePlatforms;
}

MenuItem *ModulesModel::rootItem() const
{
    return m_rootModule;
}