sourcesmodel.cpp 11.2 KB
Newer Older
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
/*
 * Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
 * Copyright (C) 2007 Jeremy Whiting <jpwhiting@kde.org>
 * Copyright (C) 2016 Olivier Churlaud <olivier@churlaud.com>
 * Copyright (C) 2019 Kai Uwe Broulik <kde@privat.broulik.de>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "sourcesmodel.h"

#include <QCollator>
#include <QDir>
#include <QStandardPaths>
#include <QStringList>
#include <QRegularExpression>

#include <KConfig>
#include <KConfigGroup>
34
#include <KLocalizedString>
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <KSharedConfig>
#include <KService>
#include <KServiceTypeTrader>

#include <algorithm>

SourcesModel::SourcesModel(QObject *parent) : QAbstractItemModel(parent)
{

}

SourcesModel::~SourcesModel() = default;

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
48
QPersistentModelIndex SourcesModel::makePersistentModelIndex(const QModelIndex &idx) const
49
{
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
50
51
52
53
54
    return QPersistentModelIndex(idx);
}

QPersistentModelIndex SourcesModel::persistentIndexForDesktopEntry(const QString &desktopEntry) const
{
55
56
57
    if (desktopEntry.isEmpty()) {
        return QPersistentModelIndex();
    }
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
58
59
60
61
62
63
64
65
66
    const auto matches = match(index(0, 0), SourcesModel::DesktopEntryRole, desktopEntry, 1, Qt::MatchFixedString);
    if (matches.isEmpty()) {
        return QPersistentModelIndex();
    }
    return QPersistentModelIndex(matches.first());
}

QPersistentModelIndex SourcesModel::persistentIndexForNotifyRcName(const QString &notifyRcName) const
{
67
68
69
    if (notifyRcName.isEmpty()) {
        return QPersistentModelIndex();
    }
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
70
71
72
73
74
    const auto matches = match(index(0, 0), SourcesModel::NotifyRcNameRole, notifyRcName, 1, Qt::MatchFixedString);
    if (matches.isEmpty()) {
        return QPersistentModelIndex();
    }
    return QPersistentModelIndex(matches.first());
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
}

int SourcesModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 1;
}

int SourcesModel::rowCount(const QModelIndex &parent) const
{
    if (parent.column() > 0) {
        return 0;
    }

    if (!parent.isValid()) {
        return m_data.count();
    }

    if (parent.internalId()) {
        return 0;
    }

    return m_data.at(parent.row()).events.count();
}

QVariant SourcesModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

106
    if (index.internalId()) { // event
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        const auto &event = m_data.at(index.internalId() - 1).events.at(index.row());

        switch (role) {
        case Qt::DisplayRole: return event.name;
        case Qt::DecorationRole: return event.iconName;
        case EventIdRole: return event.eventId;
        case ActionsRole: return event.actions;
        }

        return QVariant();
    }

    const auto &source = m_data.at(index.row());

    switch (role) {
    case Qt::DisplayRole: return source.display();
    case Qt::DecorationRole: return source.iconName;
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
124
    case SourceTypeRole: return source.desktopEntry.isEmpty() ? ServiceType : ApplicationType;
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    case NotifyRcNameRole: return source.notifyRcName;
    case DesktopEntryRole: return source.desktopEntry;
    }

    return QVariant();
}

bool SourcesModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid()) {
        return false;
    }

    bool dirty = false;

140
141
142
143
144
145
146
147
148
149
150
151
    if (index.internalId()) { // event
        auto &event = m_data[index.internalId() - 1].events[index.row()];
        switch (role) {
        case ActionsRole: {
            const QStringList newActions = value.toStringList();
            if (event.actions != newActions) {
                event.actions = newActions;
                dirty = true;
            }
            break;
        }
        }
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
    }

    if (dirty) {
        emit dataChanged(index, index, {role});
    }

    return dirty;
}

QModelIndex SourcesModel::index(int row, int column, const QModelIndex &parent) const
{
    if (row < 0 || column != 0) {
        return QModelIndex();
    }

    if (parent.isValid()) {
        const auto events = m_data.at(parent.row()).events;
        if (row < events.count()) {
            return createIndex(row, column, parent.row() + 1);
        }

        return QModelIndex();
    }

    if (row < m_data.count()) {
        return createIndex(row, column, nullptr);
    }

    return QModelIndex();
}

QModelIndex SourcesModel::parent(const QModelIndex &child) const
{
    if (child.internalId()) {
        return createIndex(child.internalId() - 1, 0, nullptr);
    }

    return QModelIndex();
}

QHash<int, QByteArray> SourcesModel::roleNames() const
{
    return {
        {Qt::DisplayRole, QByteArrayLiteral("display")},
        {Qt::DecorationRole, QByteArrayLiteral("decoration")},
        {SourceTypeRole, QByteArrayLiteral("sourceType")},
        {NotifyRcNameRole, QByteArrayLiteral("notifyRcName")},
        {DesktopEntryRole, QByteArrayLiteral("desktopEntry")},
        {EventIdRole, QByteArrayLiteral("eventId")},
201
        {ActionsRole, QByteArrayLiteral("actions")}
202
203
204
205
206
207
208
209
210
    };
}

void SourcesModel::load()
{
    beginResetModel();

    m_data.clear();

211
212
    QCollator collator;

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
213
    QVector<SourceData> appsData;
214
215
216
    QVector<SourceData> servicesData;

    QStringList notifyRcFiles;
217
    QStringList desktopEntries;
218

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
219
220
    // old code did KGlobal::dirs()->findAllResources("data", QStringLiteral("*/*.notifyrc")) but in KF5
    // only notifyrc files in knotifications5/ folder are supported
221
222
223
224
225
226
227
228
229
230
231
    const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
                            QStringLiteral("knotifications5"), QStandardPaths::LocateDirectory);
    for (const QString &dir : dirs) {
        const QStringList fileNames = QDir(dir).entryList(QStringList() << QStringLiteral("*.notifyrc"));
        for (const QString &file : fileNames) {
            if (notifyRcFiles.contains(file)) {
                continue;
            }

            notifyRcFiles.append(file);

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
232
233
            KConfig config(file, KConfig::NoGlobals);
            config.addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
234
235
                                        QStringLiteral("knotifications5/") + file));

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
236
            KConfigGroup globalGroup(&config, QLatin1String("Global"));
237
238

            const QRegularExpression regExp(QStringLiteral("^Event/([^/]*)$"));
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
239
            const QStringList groups = config.groupList().filter(regExp);
240
241

            const QString notifyRcName = file.section(QLatin1Char('.'), 0, -2);
242
243
            const QString desktopEntry = globalGroup.readEntry(QStringLiteral("DesktopEntry"));
            if (!desktopEntry.isEmpty()) {
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
244
245
246
247
                if (desktopEntries.contains(desktopEntry)) {
                    continue;
                }

248
249
                desktopEntries.append(desktopEntry);
            }
250
251
252
253
254
255
256
257
258
259

            SourceData source{
                // The old KCM read the Name and Comment from global settings disregarding
                // any user settings and just used user-specific files for actions config
                // I'm pretty sure there's a readEntry equivalent that does that without
                // reading the config stuff twice, assuming we care about this to begin with
                globalGroup.readEntry(QStringLiteral("Name")),
                globalGroup.readEntry(QStringLiteral("Comment")),
                globalGroup.readEntry(QStringLiteral("IconName")),
                notifyRcName,
260
                desktopEntry,
261
                {} // events
262
263
264
265
            };

            QVector<EventData> events;
            for (const QString &group : groups) {
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
266
                KConfigGroup cg(&config, group);
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

                const QString eventId = regExp.match(group).captured(1);
                // TODO context stuff
                // TODO load defaults thing

                EventData event{
                    cg.readEntry("Name"),
                    cg.readEntry("Comment"),
                    cg.readEntry("IconName"),
                    eventId,
                    // TODO Flags?
                    cg.readEntry("Action").split(QLatin1Char('|'))
                };
                events.append(event);
            }

283
284
285
286
            std::sort(events.begin(), events.end(), [&collator](const EventData &a, const EventData &b) {
                return collator.compare(a.name, b.name) < 0;
            });

287
288
289
            source.events = events;

            if (!source.desktopEntry.isEmpty()) {
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
290
                appsData.append(source);
291
292
293
294
295
296
297
298
299
            } else {
                servicesData.append(source);
            }
        }
    }

    const auto services = KServiceTypeTrader::self()->query(QStringLiteral("Application"),
                                                            QStringLiteral("exist Exec and TRUE == [X-GNOME-UsesNotifications]"));
    for (const auto &service : services) {
300
301
302
303
        if (service->noDisplay()) {
            continue;
        }

304
305
306
307
        if (desktopEntries.contains(service->desktopEntryName())) {
            continue;
        }

308
309
310
311
312
313
        SourceData source{
            service->name(),
            service->comment(),
            service->icon(),
            QString(), //notifyRcFile
            service->desktopEntryName(),
314
            {} // events
315
        };
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
316
        appsData.append(source);
317
        desktopEntries.append(service->desktopEntryName());
318
319
    }

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
320
321
322
    KSharedConfig::Ptr plasmanotifyrc = KSharedConfig::openConfig(QStringLiteral("plasmanotifyrc"));
    KConfigGroup applicationsGroup = plasmanotifyrc->group("Applications");
    const QStringList seenApps = applicationsGroup.groupList();
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    for (const QString &app : seenApps) {
        if (desktopEntries.contains(app)) {
            continue;
        }

        KService::Ptr service = KService::serviceByDesktopName(app);
        if (!service || service->noDisplay()) {
            continue;
        }

        SourceData source{
            service->name(),
            service->comment(),
            service->icon(),
            QString(), //notifyRcFile
            service->desktopEntryName(),
339
            {}
340
        };
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
341
342
        appsData.append(source);
        desktopEntries.append(service->desktopEntryName());
343
    }
344
345
346
347
348

    auto sortData = [&collator](const SourceData &a, const SourceData &b) {
        return collator.compare(a.display(), b.display()) < 0;
    };

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
349
    std::sort(appsData.begin(), appsData.end(), sortData);
350
351
352
353
354
355
356
357
358
359
360

    // Fake entry for configuring non-identifyable applications
    appsData << SourceData{
        i18n("Other Applications"),
        {},
        QStringLiteral("applications-other"),
        QString(),
        QStringLiteral("@other"),
        {}
    };

361
362
    std::sort(servicesData.begin(), servicesData.end(), sortData);

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
363
    m_data << appsData << servicesData;
364
365
366

    endResetModel();
}