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 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
|
/*
SPDX-FileCopyrightText: 2012-2016 Eike Hein <hein@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "backend.h"
#include "log_settings.h"
#include <KConfigGroup>
#include <KDesktopFile>
#include <KFileItem>
#include <KFilePlacesModel>
#include <KLocalizedString>
#include <KNotificationJobUiDelegate>
#include <KProtocolInfo>
#include <KService>
#include <KServiceAction>
#include <KWindowEffects>
#include <KWindowSystem>
#include <KApplicationTrader>
#include <KIO/ApplicationLauncherJob>
#include <QAction>
#include <QActionGroup>
#include <QApplication>
#include <QJsonArray>
#include <QMenu>
#include <QQuickItem>
#include <QQuickWindow>
#include <QStandardPaths>
#include <QTimer>
#include <QVersionNumber>
#include <PlasmaActivities/Consumer>
#include <PlasmaActivities/Stats/Cleaning>
#include <PlasmaActivities/Stats/ResultSet>
#include <PlasmaActivities/Stats/Terms>
#include <processcore/process.h>
#include <processcore/processes.h>
namespace KAStats = KActivities::Stats;
using namespace KAStats;
using namespace KAStats::Terms;
static constexpr int NoApplications = 2; // kactivitymanager StatsPlugin WhatToRemember.
Backend::Backend(QObject *parent)
: QObject(parent)
, m_actionGroup(new QActionGroup(this))
, m_activityManagerPluginsSettingsWatcher(KConfigWatcher::create(m_activityManagerPluginsSettings.sharedConfig()))
{
connect(m_activityManagerPluginsSettingsWatcher.get(),
&KConfigWatcher::configChanged,
this,
[this](const KConfigGroup &group, const QByteArrayList &names) {
if (group.name() == QLatin1String("Plugin-org.kde.ActivityManager.Resources.Scoring")
&& names.contains(QByteArrayLiteral("what-to-remember"))) {
m_activityManagerPluginsSettings.load();
}
});
}
Backend::~Backend()
{
}
QUrl Backend::tryDecodeApplicationsUrl(const QUrl &launcherUrl)
{
if (launcherUrl.isValid() && launcherUrl.scheme() == QLatin1String("applications")) {
const KService::Ptr service = KService::serviceByMenuId(launcherUrl.path());
if (service) {
return QUrl::fromLocalFile(service->entryPath());
}
}
return launcherUrl;
}
QStringList Backend::applicationCategories(const QUrl &launcherUrl)
{
const QUrl desktopEntryUrl = tryDecodeApplicationsUrl(launcherUrl);
if (!desktopEntryUrl.isValid() || !desktopEntryUrl.isLocalFile() || !KDesktopFile::isDesktopFile(desktopEntryUrl.toLocalFile())) {
return QStringList();
}
KDesktopFile desktopFile(desktopEntryUrl.toLocalFile());
// Since we can't have dynamic jump list actions, at least add the user's "Places" for file managers.
return desktopFile.desktopGroup().readXdgListEntry(QStringLiteral("Categories"));
}
QVariantList Backend::jumpListActions(const QUrl &launcherUrl, QObject *parent)
{
QVariantList actions;
if (!parent) {
return actions;
}
QUrl desktopEntryUrl = tryDecodeApplicationsUrl(launcherUrl);
if (!desktopEntryUrl.isValid() || !desktopEntryUrl.isLocalFile() || !KDesktopFile::isDesktopFile(desktopEntryUrl.toLocalFile())) {
return actions;
}
const KService::Ptr service = KService::serviceByDesktopPath(desktopEntryUrl.toLocalFile());
if (!service) {
return actions;
}
if (service->storageId() == QLatin1String("systemsettings.desktop")) {
actions = systemSettingsActions(parent);
if (!actions.isEmpty()) {
return actions;
}
}
const auto jumpListActions = service->actions();
for (const KServiceAction &serviceAction : jumpListActions) {
if (serviceAction.noDisplay()) {
continue;
}
QAction *action = new QAction(parent);
action->setText(serviceAction.text());
action->setIcon(QIcon::fromTheme(serviceAction.icon()));
if (serviceAction.isSeparator()) {
action->setSeparator(true);
}
connect(action, &QAction::triggered, this, [serviceAction]() {
auto *job = new KIO::ApplicationLauncherJob(serviceAction);
auto *delegate = new KNotificationJobUiDelegate;
delegate->setAutoErrorHandlingEnabled(true);
job->setUiDelegate(delegate);
job->start();
});
actions << QVariant::fromValue<QAction *>(action);
}
return actions;
}
QVariantList Backend::systemSettingsActions(QObject *parent) const
{
QVariantList actions;
if (m_activityManagerPluginsSettings.whatToRemember() == NoApplications) {
return actions;
}
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 actions;
}
for (const QString &id : std::as_const(ids)) {
KService::Ptr service = KService::serviceByStorageId(id);
if (!service || !service->isValid()) {
continue;
}
QAction *action = new QAction(parent);
action->setText(service->name());
action->setIcon(QIcon::fromTheme(service->icon()));
connect(action, &QAction::triggered, this, [service]() {
auto *job = new KIO::ApplicationLauncherJob(service);
auto *delegate = new KNotificationJobUiDelegate;
delegate->setAutoErrorHandlingEnabled(true);
job->setUiDelegate(delegate);
job->start();
});
actions << QVariant::fromValue<QAction *>(action);
}
return actions;
}
QVariantList Backend::placesActions(const QUrl &launcherUrl, bool showAllPlaces, QObject *parent)
{
if (!parent) {
return QVariantList();
}
QUrl desktopEntryUrl = tryDecodeApplicationsUrl(launcherUrl);
if (!desktopEntryUrl.isValid() || !desktopEntryUrl.isLocalFile() || !KDesktopFile::isDesktopFile(desktopEntryUrl.toLocalFile())) {
return QVariantList();
}
QVariantList actions;
// Since we can't have dynamic jump list actions, at least add the user's "Places" for file managers.
if (!applicationCategories(launcherUrl).contains(QLatin1String("FileManager"))) {
return actions;
}
QString previousGroup;
QMenu *subMenu = nullptr;
std::unique_ptr<KFilePlacesModel> placesModel(new KFilePlacesModel());
for (int i = 0; i < placesModel->rowCount(); ++i) {
QModelIndex idx = placesModel->index(i, 0);
if (placesModel->isHidden(idx)) {
continue;
}
const QString &title = idx.data(Qt::DisplayRole).toString();
const QIcon &icon = idx.data(Qt::DecorationRole).value<QIcon>();
const QUrl &url = idx.data(KFilePlacesModel::UrlRole).toUrl();
QAction *placeAction = new QAction(icon, title, parent);
connect(placeAction, &QAction::triggered, this, [url, desktopEntryUrl] {
KService::Ptr service = KService::serviceByDesktopPath(desktopEntryUrl.toLocalFile());
if (!service) {
return;
}
auto *job = new KIO::ApplicationLauncherJob(service);
auto *delegate = new KNotificationJobUiDelegate;
delegate->setAutoErrorHandlingEnabled(true);
job->setUiDelegate(delegate);
job->setUrls({url});
job->start();
});
const QString &groupName = idx.data(KFilePlacesModel::GroupRole).toString();
if (previousGroup.isEmpty()) { // Skip first group heading.
previousGroup = groupName;
}
// Put all subsequent categories into a submenu.
if (previousGroup != groupName) {
QAction *subMenuAction = new QAction(groupName, parent);
subMenu = new QMenu();
// Cannot parent a QMenu to a QAction, need to delete it manually.
connect(parent, &QObject::destroyed, subMenu, &QObject::deleteLater);
subMenuAction->setMenu(subMenu);
actions << QVariant::fromValue(subMenuAction);
previousGroup = groupName;
}
if (subMenu) {
subMenu->addAction(placeAction);
} else {
actions << QVariant::fromValue(placeAction);
}
}
// There is nothing more frustrating than having a "More" entry that ends up showing just one or two
// additional entries. Therefore we truncate to max. 5 entries only if there are more than 7 in total.
if (!showAllPlaces && actions.count() > 7) {
const int totalActionCount = actions.count();
while (actions.count() > 5) {
actions.removeLast();
}
QAction *action = new QAction(parent);
action->setIcon(QIcon::fromTheme(QStringLiteral("view-more-symbolic")));
action->setText(i18ncp("Show all user Places", "%1 more Place…", "%1 more Places…", totalActionCount - actions.count()));
connect(action, &QAction::triggered, this, &Backend::showAllPlaces);
actions << QVariant::fromValue(action);
}
return actions;
}
QVariantList Backend::recentDocumentActions(const QUrl &launcherUrl, QObject *parent)
{
QVariantList actions;
if (!parent) {
return actions;
}
if (m_activityManagerPluginsSettings.whatToRemember() == NoApplications) {
return actions;
}
QUrl desktopEntryUrl = tryDecodeApplicationsUrl(launcherUrl);
if (!desktopEntryUrl.isValid() || !desktopEntryUrl.isLocalFile() || !KDesktopFile::isDesktopFile(desktopEntryUrl.toLocalFile())) {
return QVariantList();
}
QString desktopName = desktopEntryUrl.fileName();
QString storageId = desktopName;
if (storageId.endsWith(QLatin1String(".desktop"))) {
storageId = storageId.left(storageId.length() - 8);
}
auto query = UsedResources | RecentlyUsedFirst | Agent(storageId) | Type::any() | Activity::current();
ResultSet results(query);
ResultSet::const_iterator resultIt = results.begin();
int actionCount = 0;
bool allFolders = true;
bool allDownloads = true;
bool allRemoteWithoutFileName = true;
const QString downloadsPath = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
while (actionCount < 5 && resultIt != results.end()) {
const QString resource = (*resultIt).resource();
const QString mimetype = (*resultIt).mimetype();
const QUrl url = (*resultIt).url();
++resultIt;
if (!url.isValid()) {
continue;
}
allFolders = allFolders && mimetype == QLatin1String("inode/directory");
allDownloads = allDownloads && url.toLocalFile().startsWith(downloadsPath);
allRemoteWithoutFileName = allRemoteWithoutFileName && !url.isLocalFile() && url.fileName().isEmpty();
QString name;
if (url.isLocalFile() && !url.fileName().isEmpty()) {
name = url.fileName();
} else {
name = url.toDisplayString();
}
QAction *action = new QAction(parent);
action->setText(name);
action->setIcon(QIcon::fromTheme(KIO::iconNameForUrl(url)));
action->setProperty("agent", storageId);
action->setProperty("entryPath", desktopEntryUrl);
action->setProperty("mimeType", mimetype);
action->setData(url);
connect(action, &QAction::triggered, this, &Backend::handleRecentDocumentAction);
actions << QVariant::fromValue<QAction *>(action);
++actionCount;
}
if (actionCount > 0) {
// Overrides section heading on QML side
if (allDownloads) {
actions.prepend(i18n("Recent Downloads"));
} else if (allRemoteWithoutFileName) {
actions.prepend(i18n("Recent Connections"));
} else if (allFolders) {
actions.prepend(i18n("Recent Places"));
}
QAction *separatorAction = new QAction(parent);
separatorAction->setSeparator(true);
actions << QVariant::fromValue<QAction *>(separatorAction);
QAction *action = new QAction(parent);
if (allDownloads) {
action->setText(i18nc("@action:inmenu", "Forget Recent Downloads"));
} else if (allRemoteWithoutFileName) {
action->setText(i18nc("@action:inmenu", "Forget Recent Connections"));
} else if (allFolders) {
action->setText(i18nc("@action:inmenu", "Forget Recent Places"));
} else {
action->setText(i18nc("@action:inmenu", "Forget Recent Files"));
}
action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history")));
action->setProperty("agent", storageId);
connect(action, &QAction::triggered, this, &Backend::handleRecentDocumentAction);
actions << QVariant::fromValue<QAction *>(action);
}
return actions;
}
void Backend::handleRecentDocumentAction() const
{
const QAction *action = qobject_cast<QAction *>(sender());
if (!action) {
return;
}
const QString agent = action->property("agent").toString();
if (agent.isEmpty()) {
return;
}
const QString desktopPath = action->property("entryPath").toUrl().toLocalFile();
const QUrl url = action->data().toUrl();
if (desktopPath.isEmpty() || url.isEmpty()) {
auto query = UsedResources | Agent(agent) | Type::any() | Activity::current();
KAStats::forgetResources(query);
return;
}
KService::Ptr service = KService::serviceByDesktopPath(desktopPath);
if (!service) {
return;
}
// prevents using a service file that does not support opening a mime type for a file it created
// for instance spectacle
const auto mimetype = action->property("mimeType").toString();
if (!mimetype.isEmpty() && mimetype != QLatin1String("application/octet-stream")) {
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;
} else {
qCWarning(TASKMANAGER_DEBUG) << "Preventing the file to open with " << service->desktopEntryName() << "no alternative found";
}
}
}
auto *job = new KIO::ApplicationLauncherJob(service);
auto *delegate = new KNotificationJobUiDelegate;
delegate->setAutoErrorHandlingEnabled(true);
job->setUiDelegate(delegate);
job->setUrls({url});
job->start();
}
void Backend::setActionGroup(QAction *action) const
{
if (action) {
action->setActionGroup(m_actionGroup);
}
}
QRect Backend::globalRect(QQuickItem *item) const
{
if (!item || !item->window()) {
return QRect();
}
QRect iconRect(item->x(), item->y(), item->width(), item->height());
iconRect.moveTopLeft(item->parentItem()->mapToScene(iconRect.topLeft()).toPoint());
iconRect.moveTopLeft(item->window()->mapToGlobal(iconRect.topLeft()));
return iconRect;
}
bool Backend::isApplication(const QUrl &url) const
{
if (!url.isValid() || !url.isLocalFile()) {
return false;
}
const QString &localPath = url.toLocalFile();
if (!KDesktopFile::isDesktopFile(localPath)) {
return false;
}
KDesktopFile desktopFile(localPath);
return desktopFile.hasApplicationType();
}
qint64 Backend::parentPid(qint64 pid) const
{
KSysGuard::Processes procs;
procs.updateOrAddProcess(pid);
KSysGuard::Process *proc = procs.getProcess(pid);
if (!proc) {
return -1;
}
int parentPid = proc->parentPid();
if (parentPid != -1) {
procs.updateOrAddProcess(parentPid);
KSysGuard::Process *parentProc = procs.getProcess(parentPid);
if (!parentProc) {
return -1;
}
if (!proc->cGroup().isEmpty() && parentProc->cGroup() == proc->cGroup()) {
return parentProc->pid();
}
}
return -1;
}
#include "moc_backend.cpp"
|