File: actionlist.cpp

package info (click to toggle)
plasma-workspace 4%3A6.3.6-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 104,900 kB
  • sloc: cpp: 125,434; xml: 31,579; python: 3,976; perl: 572; sh: 234; javascript: 74; ruby: 39; ansic: 13; makefile: 9
file content (490 lines) | stat: -rw-r--r-- 15,029 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
    SPDX-FileCopyrightText: 2013 Aurélien Gâteau <agateau@kde.org>
    SPDX-FileCopyrightText: 2014 Eike Hein <hein@kde.org>

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

#include "actionlist.h"
#include "processrunner.h"

#include <config-appstream.h>

#include <QApplication>
#include <QDesktopServices>
#include <QDir>
#include <QStandardPaths>

#include <KApplicationTrader>
#include <KFileUtils>
#include <KIO/ApplicationLauncherJob>
#include <KLocalizedString>
#include <KNotificationJobUiDelegate>
#include <KPropertiesDialog>
#include <KProtocolInfo>

#include <KIO/DesktopExecParser>
#include <PlasmaActivities/Stats/Cleaning>
#include <PlasmaActivities/Stats/ResultSet>
#include <PlasmaActivities/Stats/Terms>

#include "containmentinterface.h"

#ifdef HAVE_APPSTREAMQT
#include <AppStreamQt/pool.h>
#endif

namespace KAStats = KActivities::Stats;

using namespace KAStats;
using namespace KAStats::Terms;

namespace Kicker
{
QVariantMap createActionItem(const QString &label, const QString &icon, const QString &actionId, const QVariant &argument)
{
    QVariantMap map;

    map[QStringLiteral("text")] = label;
    map[QStringLiteral("icon")] = icon;
    map[QStringLiteral("actionId")] = actionId;

    if (argument.isValid()) {
        map[QStringLiteral("actionArgument")] = argument;
    }

    return map;
}

QVariantMap createTitleActionItem(const QString &label)
{
    QVariantMap map;

    map[QStringLiteral("text")] = label;
    map[QStringLiteral("type")] = QStringLiteral("title");

    return map;
}

QVariantMap createSeparatorActionItem()
{
    QVariantMap map;

    map[QStringLiteral("type")] = QStringLiteral("separator");

    return map;
}

QVariantList createActionListForFileItem(const KFileItem &fileItem)
{
    QVariantList list;

    const KService::List services = KApplicationTrader::queryByMimeType(fileItem.mimetype());

    if (!services.isEmpty()) {
        list << createTitleActionItem(i18n("Open with:"));

        for (const KService::Ptr &service : services) {
            const QString text = service->name().replace(QLatin1Char('&'), QStringLiteral("&&"));
            const QVariantMap item = createActionItem(text, service->icon(), QStringLiteral("_kicker_fileItem_openWith"), service->entryPath());

            list << item;
        }

        list << createSeparatorActionItem();
    }

    const QVariantMap &propertiesItem =
        createActionItem(i18n("Properties"), QStringLiteral("document-properties"), QStringLiteral("_kicker_fileItem_properties"));
    list << propertiesItem;

    return list;
}

bool handleFileItemAction(const KFileItem &fileItem, const QString &actionId, const QVariant &argument, bool *close)
{
    if (actionId == QLatin1String("_kicker_fileItem_properties")) {
        KPropertiesDialog *dlg = new KPropertiesDialog(fileItem, QApplication::activeWindow());
        dlg->setAttribute(Qt::WA_DeleteOnClose);
        dlg->show();

        *close = false;

        return true;
    }

    if (actionId == QLatin1String("_kicker_fileItem_openWith")) {
        const QString path = argument.toString();
        const KService::Ptr service = KService::serviceByDesktopPath(path);

        if (!service) {
            return false;
        }

        auto *job = new KIO::ApplicationLauncherJob(service);
        job->setUrls({fileItem.url()});
        job->setUiDelegate(new KNotificationJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled));
        job->start();

        *close = true;

        return true;
    }

    return false;
}

QVariantList createAddLauncherActionList(QObject *appletInterface, const KService::Ptr &service)
{
    QVariantList actionList;
    if (!service) {
        return actionList;
    }

    if (ContainmentInterface::mayAddLauncher(appletInterface, ContainmentInterface::Desktop)) {
        QVariantMap addToDesktopAction = Kicker::createActionItem(i18n("Add to Desktop"), QStringLiteral("list-add"), QStringLiteral("addToDesktop"));
        actionList << addToDesktopAction;
    }

    if (service && ContainmentInterface::mayAddLauncher(appletInterface, ContainmentInterface::TaskManager, service)) {
        if (!ContainmentInterface::hasLauncher(appletInterface, ContainmentInterface::TaskManager, service)) {
            QVariantMap addToTaskManagerAction =
                Kicker::createActionItem(i18n("Pin to Task Manager"), QStringLiteral("pin"), QStringLiteral("addToTaskManager"));
            actionList << addToTaskManagerAction;
        }
    } else if (ContainmentInterface::mayAddLauncher(appletInterface, ContainmentInterface::Panel)) {
        QVariantMap addToPanelAction = Kicker::createActionItem(i18n("Add to Panel (Widget)"), QStringLiteral("list-add"), QStringLiteral("addToPanel"));
        actionList << addToPanelAction;
    }

    return actionList;
}

bool handleAddLauncherAction(const QString &actionId, QObject *appletInterface, const KService::Ptr &service)
{
    if (!service) {
        return false;
    }

    if (actionId == QLatin1String("addToDesktop")) {
        if (ContainmentInterface::mayAddLauncher(appletInterface, ContainmentInterface::Desktop)) {
            ContainmentInterface::addLauncher(appletInterface, ContainmentInterface::Desktop, service->entryPath());
        }
        return true;
    } else if (actionId == QLatin1String("addToPanel")) {
        if (ContainmentInterface::mayAddLauncher(appletInterface, ContainmentInterface::Panel)) {
            ContainmentInterface::addLauncher(appletInterface, ContainmentInterface::Panel, service->entryPath());
        }
        return true;
    } else if (actionId == QLatin1String("addToTaskManager")) {
        if (ContainmentInterface::mayAddLauncher(appletInterface, ContainmentInterface::TaskManager, service)) {
            ContainmentInterface::addLauncher(appletInterface, ContainmentInterface::TaskManager, service->entryPath());
        }
        return true;
    }

    return false;
}

QString storageIdFromService(KService::Ptr service)
{
    QString storageId = service->storageId();

    if (storageId.endsWith(QLatin1String(".desktop"))) {
        storageId = storageId.left(storageId.length() - 8);
    }

    return storageId;
}

QVariantList jumpListActions(KService::Ptr service)
{
    QVariantList list;

    if (!service) {
        return list;
    }

    // Add frequently used settings modules similar to SystemSetting's overview page.
    if (service->storageId() == QLatin1String("systemsettings.desktop")) {
        list = systemSettingsActions();

        if (!list.isEmpty()) {
            return list;
        }
    }

    const auto &actions = service->actions();
    for (const KServiceAction &action : actions) {
        if (action.text().isEmpty() || action.exec().isEmpty()) {
            continue;
        }

        QVariantMap item = createActionItem(action.text(), action.icon(), QStringLiteral("_kicker_jumpListAction"), QVariant::fromValue(action));

        list << item;
    }

    return list;
}

QVariantList systemSettingsActions()
{
    QVariantList list;

    auto query = AllResources | Agent(QStringLiteral("org.kde.systemsettings")) | HighScoredFirst | Limit(5);

    ResultSet results(query);

    QStringList ids;
    for (const ResultSet::Result &result : results) {
        ids << QUrl(result.resource()).path();
    }

    if (ids.count() < 5) {
        // We'll load the default set of settings from its jump list actions.
        return list;
    }

    for (const QString &id : std::as_const(ids)) {
        KService::Ptr service = KService::serviceByStorageId(id);
        if (!service || !service->isValid()) {
            continue;
        }

        KServiceAction action(service->name(), service->desktopEntryName(), service->icon(), service->exec(), false, service);
        list << createActionItem(service->name(), service->icon(), QStringLiteral("_kicker_jumpListAction"), QVariant::fromValue(action));
    }

    return list;
}

QVariantList recentDocumentActions(const KService::Ptr &service)
{
    QVariantList list;

    if (!service) {
        return list;
    }

    const QString storageId = storageIdFromService(service);

    if (storageId.isEmpty()) {
        return list;
    }

    // clang-format off
    auto query = UsedResources
        | RecentlyUsedFirst
        | Agent(storageId)
        | Type::any()
        | Activity::current()
        | Url::file();
    // clang-format on

    ResultSet results(query);

    ResultSet::const_iterator resultIt;
    resultIt = results.begin();

    while (list.count() < 6 && resultIt != results.end()) {
        const QString resource = (*resultIt).resource();
        const QString mimeType = (*resultIt).mimetype();
        const QUrl url = (*resultIt).url();
        ++resultIt;

        if (!url.isValid()) {
            continue;
        }

        const KFileItem fileItem(url, mimeType);

        if (!fileItem.isFile()) {
            continue;
        }

        if (list.isEmpty()) {
            list << createTitleActionItem(i18n("Recent Files"));
        }

        QVariantMap item = createActionItem(url.fileName(), fileItem.iconName(), QStringLiteral("_kicker_recentDocument"), QStringList{resource, mimeType});

        list << item;
    }

    if (!list.isEmpty()) {
        QVariantMap forgetAction =
            createActionItem(i18n("Forget Recent Files"), QStringLiteral("edit-clear-history"), QStringLiteral("_kicker_forgetRecentDocuments"));
        list << forgetAction;
    }

    return list;
}

bool handleRecentDocumentAction(KService::Ptr service, const QString &actionId, const QVariant &_argument)
{
    if (!service) {
        return false;
    }

    if (actionId == QLatin1String("_kicker_forgetRecentDocuments")) {
        const QString storageId = storageIdFromService(service);

        if (storageId.isEmpty()) {
            return false;
        }

        // clang-format off
        auto query = UsedResources
            | Agent(storageId)
            | Type::any()
            | Activity::current()
            | Url::file();
        // clang-format on

        KAStats::forgetResources(query);

        return false;
    }

    const QStringList argument = _argument.toStringList();
    if (argument.isEmpty()) {
        return false;
    }
    const auto resource = argument.at(0);
    const auto mimeType = argument.at(1);

    // prevents using a service file that does not support opening a mime type for a file it created
    // for instance a screenshot tool
    if (!mimeType.isEmpty()) {
        if (!service->hasMimeType(mimeType)) {
            // needs to find the application that supports this mimetype
            service = KApplicationTrader::preferredService(mimeType);

            if (!service) {
                // no service found to handle the mimetype
                return false;
            }
        }
    }

    auto *job = new KIO::ApplicationLauncherJob(service);
    job->setUrls({QUrl::fromUserInput(resource)});
    job->setUiDelegate(new KNotificationJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled));
    return job->exec();
}

QVariantList editApplicationAction(const KService::Ptr &service)
{
    QVariantList actionList;

    if (service && service->isApplication()) {
        QVariantMap editAction = Kicker::createActionItem(i18n("Edit Application…"), QStringLiteral("kmenuedit"), QStringLiteral("editApplication"));
        actionList << editAction;
    }

    return actionList;
}

bool handleEditApplicationAction(const QString &actionId, const KService::Ptr &service)
{
    if (service && service->isApplication() && actionId == QLatin1String("editApplication")) {
        ProcessRunner::runMenuEditor({service->menuId()});
        return true;
    }

    return false;
}

#ifdef HAVE_APPSTREAMQT
Q_GLOBAL_STATIC(AppStream::Pool, appstreamPool)
#endif

QVariantList appstreamActions(const KService::Ptr &service)
{
    Q_UNUSED(service)
#ifdef HAVE_APPSTREAMQT
    const KService::Ptr appStreamHandler = KApplicationTrader::preferredService(QStringLiteral("x-scheme-handler/appstream"));

    // Don't show action if we can't find any app to handle appstream:// URLs.
    if (!appStreamHandler) {
        return {};
    }

    QVariantMap appstreamAction = Kicker::createActionItem(i18nc("@action opens a software center with the application", "Uninstall or Manage Add-Ons…"),
                                                           appStreamHandler->icon(),
                                                           QStringLiteral("manageApplication"));
    return {appstreamAction};
#else
    return {};
#endif
}

bool handleAppstreamActions(const QString &actionId, const KService::Ptr &service)
{
    if (actionId != QLatin1String("manageApplication")) {
        return false;
    }
#ifdef HAVE_APPSTREAMQT
    if (!appstreamPool.exists()) {
        appstreamPool->load();
    }

    const auto components =
        appstreamPool->componentsByLaunchable(AppStream::Launchable::KindDesktopId, service->desktopEntryName() + QLatin1String(".desktop")).toList();
    if (components.empty()) {
        return false;
    }
    return QDesktopServices::openUrl(QUrl(QLatin1String("appstream://") + components[0].id()));
#else
    return false;
#endif
}

static QList<KServiceAction> additionalActions(const KService::Ptr &service)
{
    QList<KServiceAction> actions;
    const static auto locations =
        QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("plasma/kickeractions"), QStandardPaths::LocateDirectory);
    const auto files = KFileUtils::findAllUniqueFiles(locations);
    for (const auto &file : files) {
        KService actionsService(file);
        const auto filter = actionsService.property<QStringList>(QStringLiteral("X-KDE-OnlyForAppIds"));
        if (filter.empty() || filter.contains(storageIdFromService(service))) {
            actions.append(actionsService.actions());
        }
    }
    return actions;
}

QVariantList additionalAppActions(const KService::Ptr &service)
{
    QVariantList list;
    const auto actions = additionalActions(service);
    list.reserve(actions.size());
    for (const auto &action : actions) {
        list << createActionItem(action.text(), action.icon(), action.name(), action.service()->entryPath());
    }
    return list;
}

bool handleAdditionalAppActions(const QString &actionId, const KService::Ptr &service, const QVariant &argument)
{
    const KService actionProvider(argument.toString());
    if (!actionProvider.isValid()) {
        return false;
    }
    const auto actions = actionProvider.actions();
    auto action = std::find_if(actions.begin(), actions.end(), [&actionId](const KServiceAction &action) {
        return action.name() == actionId;
    });
    if (action == actions.end()) {
        return false;
    }
    auto *job = new KIO::ApplicationLauncherJob(*action);
    job->setUrls({QUrl::fromLocalFile(service->entryPath())});
    job->setUiDelegate(new KNotificationJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled));
    job->start();
    return true;
}
}