diff --git a/libtaskmanager/taskmanagerrulesrc b/libtaskmanager/taskmanagerrulesrc index fb27df5ba..ded9eafbe 100644 --- a/libtaskmanager/taskmanagerrulesrc +++ b/libtaskmanager/taskmanagerrulesrc @@ -1,13 +1,14 @@ [Mapping] Gimp-2.8=GIMP Google-chrome=Google Chrome Google-chrome-stable=Google Chrome Systemsettings=System Settings oracle-ide-boot-Launcher=Oracle SQL Developer Dragon=dragonplayer VirtualBox Manager=virtualbox VirtualBox Machine=virtualbox [Settings] MatchCommandLineFirst=perl TryIgnoreRuntimes=perl +SkipTaskbar=Soffice diff --git a/libtaskmanager/tasksmodel.cpp b/libtaskmanager/tasksmodel.cpp index c881369cb..c6a6b8d29 100644 --- a/libtaskmanager/tasksmodel.cpp +++ b/libtaskmanager/tasksmodel.cpp @@ -1,1806 +1,1859 @@ /******************************************************************** Copyright 2016 Eike Hein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "tasksmodel.h" #include "activityinfo.h" #include "concatenatetasksproxymodel.h" #include "flattentaskgroupsproxymodel.h" #include "taskfilterproxymodel.h" #include "taskgroupingproxymodel.h" #include "tasktools.h" #include "launchertasksmodel.h" #include "startuptasksmodel.h" #include "windowtasksmodel.h" #include "launchertasksmodel_p.h" #include #include #include #include namespace TaskManager { class Q_DECL_HIDDEN TasksModel::Private { public: Private(TasksModel *q); ~Private(); static int instanceCount; static WindowTasksModel* windowTasksModel; static StartupTasksModel* startupTasksModel; LauncherTasksModel* launcherTasksModel = nullptr; ConcatenateTasksProxyModel* concatProxyModel = nullptr; TaskFilterProxyModel* filterProxyModel = nullptr; TaskGroupingProxyModel* groupingProxyModel = nullptr; FlattenTaskGroupsProxyModel* flattenGroupsProxyModel = nullptr; AbstractTasksModelIface *abstractTasksSourceModel = nullptr; bool anyTaskDemandsAttention = false; int launcherCount = 0; int virtualDesktop = -1; int screen = -1; QString activity; SortMode sortMode = SortAlpha; bool separateLaunchers = true; bool launchInPlace = false; bool launchersEverSet = false; bool launcherSortingDirty = false; bool launcherCheckNeeded = false; QList sortedPreFilterRows; QVector sortRowInsertQueue; + bool sortRowInsertQueueStale = false; QHash activityTaskCounts; static ActivityInfo* activityInfo; static int activityInfoUsers; bool groupInline = false; int groupingWindowTasksThreshold = -1; bool usedByQml = false; bool componentComplete = false; void initModels(); void initLauncherTasksModel(); void updateAnyTaskDemandsAttention(); void updateManualSortMap(); void consolidateManualSortMapForGroup(const QModelIndex &groupingProxyIndex); void updateGroupInline(); QModelIndex preFilterIndex(const QModelIndex &sourceIndex) const; void updateActivityTaskCounts(); void forceResort(); bool lessThan(const QModelIndex &left, const QModelIndex &right, bool sortOnlyLaunchers = false) const; private: TasksModel *q; }; class TasksModel::TasksModelLessThan { public: inline TasksModelLessThan(const QAbstractItemModel *s, TasksModel *p, bool sortOnlyLaunchers) : sourceModel(s), tasksModel(p), sortOnlyLaunchers(sortOnlyLaunchers) {} inline bool operator()(int r1, int r2) const { QModelIndex i1 = sourceModel->index(r1, 0); QModelIndex i2 = sourceModel->index(r2, 0); return tasksModel->d->lessThan(i1, i2, sortOnlyLaunchers); } private: const QAbstractItemModel *sourceModel; const TasksModel *tasksModel; bool sortOnlyLaunchers; }; int TasksModel::Private::instanceCount = 0; WindowTasksModel* TasksModel::Private::windowTasksModel = nullptr; StartupTasksModel* TasksModel::Private::startupTasksModel = nullptr; ActivityInfo* TasksModel::Private::activityInfo = nullptr; int TasksModel::Private::activityInfoUsers = 0; TasksModel::Private::Private(TasksModel *q) : q(q) { ++instanceCount; } TasksModel::Private::~Private() { --instanceCount; if (sortMode == SortActivity) { --activityInfoUsers; } if (!instanceCount) { delete windowTasksModel; windowTasksModel = nullptr; delete startupTasksModel; startupTasksModel = nullptr; delete activityInfo; activityInfo = nullptr; } } void TasksModel::Private::initModels() { // NOTE: Overview over the entire model chain assembled here: // WindowTasksModel, StartupTasksModel, LauncherTasksModel // -> concatProxyModel concatenates them into a single list. // -> filterProxyModel filters by state (e.g. virtual desktop). // -> groupingProxyModel groups by application (we go from flat list to tree). // -> flattenGroupsProxyModel (optionally, if groupInline == true) flattens groups out. // -> TasksModel collapses (top-level) items into task lifecycle abstraction; sorts. if (!windowTasksModel) { windowTasksModel = new WindowTasksModel(); } QObject::connect(windowTasksModel, &QAbstractItemModel::rowsInserted, q, [this]() { if (sortMode == SortActivity) { updateActivityTaskCounts(); } } ); QObject::connect(windowTasksModel, &QAbstractItemModel::rowsRemoved, q, [this]() { if (sortMode == SortActivity) { updateActivityTaskCounts(); forceResort(); } } ); QObject::connect(windowTasksModel, &QAbstractItemModel::dataChanged, q, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { Q_UNUSED(topLeft) Q_UNUSED(bottomRight) if (sortMode == SortActivity && roles.contains(AbstractTasksModel::Activities)) { updateActivityTaskCounts(); } if (roles.contains(AbstractTasksModel::IsActive)) { emit q->activeTaskChanged(); } + + // In manual sort mode, updateManualSortMap() may consult the sortRowInsertQueue + // for new tasks to sort in. Hidden tasks remain in the queue to potentially sort + // them later, when they are are actually revealed to the user. + // This is particularly useful in concert with taskmanagerrulesrc's SkipTaskbar + // key, which is used to hide window tasks which update from bogus to useful + // window metadata early in startup. The role change then coincides with positive + // app identication, which is when updateManualSortMap() becomes able to sort the + // task adjacent to its launcher when required to do so. + if (sortMode == SortManual && roles.contains(AbstractTasksModel::SkipTaskbar)) { + updateManualSortMap(); + } } ); if (!startupTasksModel) { startupTasksModel = new StartupTasksModel(); } concatProxyModel = new ConcatenateTasksProxyModel(q); concatProxyModel->addSourceModel(windowTasksModel); concatProxyModel->addSourceModel(startupTasksModel); // If we're in manual sort mode, we need to seed the sort map on pending row // insertions. QObject::connect(concatProxyModel, &QAbstractItemModel::rowsAboutToBeInserted, q, [this](const QModelIndex &parent, int start, int end) { Q_UNUSED(parent) if (sortMode != SortManual) { return; } const int delta = (end - start) + 1; QMutableListIterator it(sortedPreFilterRows); while (it.hasNext()) { it.next(); if (it.value() >= start) { it.setValue(it.value() + delta); } } for (int i = start; i <= end; ++i) { sortedPreFilterRows.append(i); if (!separateLaunchers) { + if (sortRowInsertQueueStale) { + sortRowInsertQueue.clear(); + sortRowInsertQueueStale = false; + } + sortRowInsertQueue.append(sortedPreFilterRows.count() - 1); } } } ); // If we're in manual sort mode, we need to update the sort map on row insertions. QObject::connect(concatProxyModel, &QAbstractItemModel::rowsInserted, q, [this](const QModelIndex &parent, int start, int end) { Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) if (sortMode == SortManual) { updateManualSortMap(); } } ); // If we're in manual sort mode, we need to update the sort map after row removals. QObject::connect(concatProxyModel, &QAbstractItemModel::rowsRemoved, q, [this](const QModelIndex &parent, int first, int last) { Q_UNUSED(parent) if (sortMode != SortManual) { return; } + if (sortRowInsertQueueStale) { + sortRowInsertQueue.clear(); + sortRowInsertQueueStale = false; + } + for (int i = first; i <= last; ++i) { sortedPreFilterRows.removeOne(i); } const int delta = (last - first) + 1; QMutableListIterator it(sortedPreFilterRows); while (it.hasNext()) { it.next(); if (it.value() > last) { it.setValue(it.value() - delta); } } } ); filterProxyModel = new TaskFilterProxyModel(q); filterProxyModel->setSourceModel(concatProxyModel); QObject::connect(filterProxyModel, &TaskFilterProxyModel::virtualDesktopChanged, q, &TasksModel::virtualDesktopChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::screenGeometryChanged, q, &TasksModel::screenGeometryChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::activityChanged, q, &TasksModel::activityChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterByVirtualDesktopChanged, q, &TasksModel::filterByVirtualDesktopChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterByScreenChanged, q, &TasksModel::filterByScreenChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterByActivityChanged, q, &TasksModel::filterByActivityChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterNotMinimizedChanged, q, &TasksModel::filterNotMinimizedChanged); groupingProxyModel = new TaskGroupingProxyModel(q); groupingProxyModel->setSourceModel(filterProxyModel); QObject::connect(groupingProxyModel, &TaskGroupingProxyModel::groupModeChanged, q, &TasksModel::groupModeChanged); QObject::connect(groupingProxyModel, &TaskGroupingProxyModel::blacklistedAppIdsChanged, q, &TasksModel::groupingAppIdBlacklistChanged); QObject::connect(groupingProxyModel, &TaskGroupingProxyModel::blacklistedLauncherUrlsChanged, q, &TasksModel::groupingLauncherUrlBlacklistChanged); QObject::connect(groupingProxyModel, &QAbstractItemModel::rowsInserted, q, [this](const QModelIndex &parent, int first, int last) { if (parent.isValid()) { if (sortMode == SortManual) { consolidateManualSortMapForGroup(parent); } // Existence of a group means everything below this has already been done. return; } bool demandsAttentionUpdateNeeded = false; for (int i = first; i <= last; ++i) { const QModelIndex &sourceIndex = groupingProxyModel->index(i, 0); const QString &appId = sourceIndex.data(AbstractTasksModel::AppId).toString(); if (sourceIndex.data(AbstractTasksModel::IsDemandingAttention).toBool()) { demandsAttentionUpdateNeeded = true; } // When we get a window we have a startup for, cause the startup to be re-filtered. if (sourceIndex.data(AbstractTasksModel::IsWindow).toBool()) { const QString &appName = sourceIndex.data(AbstractTasksModel::AppName).toString(); for (int i = 0; i < filterProxyModel->rowCount(); ++i) { QModelIndex filterIndex = filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsStartup).toBool()) { continue; } if ((!appId.isEmpty() && appId == filterIndex.data(AbstractTasksModel::AppId).toString()) || (!appName.isEmpty() && appName == filterIndex.data(AbstractTasksModel::AppName).toString())) { filterProxyModel->dataChanged(filterIndex, filterIndex); } } } // When we get a window or startup we have a launcher for, cause the launcher to be re-filtered. if (sourceIndex.data(AbstractTasksModel::IsWindow).toBool() || sourceIndex.data(AbstractTasksModel::IsStartup).toBool()) { for (int i = 0; i < filterProxyModel->rowCount(); ++i) { const QModelIndex &filterIndex = filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsLauncher).toBool()) { continue; } if (appsMatch(sourceIndex, filterIndex)) { filterProxyModel->dataChanged(filterIndex, filterIndex); } } } } if (!anyTaskDemandsAttention && demandsAttentionUpdateNeeded) { updateAnyTaskDemandsAttention(); } } ); QObject::connect(groupingProxyModel, &QAbstractItemModel::rowsAboutToBeRemoved, q, [this](const QModelIndex &parent, int first, int last) { // We can ignore group members. if (parent.isValid()) { return; } for (int i = first; i <= last; ++i) { const QModelIndex &sourceIndex = groupingProxyModel->index(i, 0); // When a window or startup task is removed, we have to trigger a re-filter of // our launchers to (possibly) pop them back in. // NOTE: An older revision of this code compared the window and startup tasks // to the launchers to figure out which launchers should be re-filtered. This // was fine until we discovered that certain applications (e.g. Google Chrome) // change their window metadata specifically during tear-down, sometimes // breaking TaskTools::appsMatch (it's a race) and causing the associated // launcher to remain hidden. Therefore we now consider any top-level window or // startup task removal a trigger to re-filter all launchers. We don't do this // in response to the window metadata changes (even though it would be strictly // more correct, as then-ending identity match-up was what caused the launcher // to be hidden) because we don't want the launcher and window/startup task to // briefly co-exist in the model. if (!launcherCheckNeeded && launcherTasksModel && (sourceIndex.data(AbstractTasksModel::IsWindow).toBool() || sourceIndex.data(AbstractTasksModel::IsStartup).toBool())) { launcherCheckNeeded = true; } } } ); QObject::connect(filterProxyModel, &QAbstractItemModel::rowsRemoved, q, [this](const QModelIndex &parent, int first, int last) { Q_UNUSED(parent) Q_UNUSED(first) Q_UNUSED(last) if (launcherCheckNeeded) { for (int i = 0; i < filterProxyModel->rowCount(); ++i) { const QModelIndex &idx = filterProxyModel->index(i, 0); if (idx.data(AbstractTasksModel::IsLauncher).toBool()) { filterProxyModel->dataChanged(idx, idx); } } launcherCheckNeeded = false; } // One of the removed tasks might have been demanding attention, but // we can't check the state after the window has been closed already, // so we always have to do a full update. if (anyTaskDemandsAttention) { updateAnyTaskDemandsAttention(); } } ); // Update anyTaskDemandsAttention on source data changes. QObject::connect(groupingProxyModel, &QAbstractItemModel::dataChanged, q, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { Q_UNUSED(bottomRight) // We can ignore group members. if (topLeft.parent().isValid()) { return; } if (roles.isEmpty() || roles.contains(AbstractTasksModel::IsDemandingAttention)) { updateAnyTaskDemandsAttention(); } } ); // Update anyTaskDemandsAttention on source model resets. QObject::connect(groupingProxyModel, &QAbstractItemModel::modelReset, q, [this]() { updateAnyTaskDemandsAttention(); } ); } void TasksModel::Private::updateAnyTaskDemandsAttention() { bool taskFound = false; for (int i = 0; i < groupingProxyModel->rowCount(); ++i) { if (groupingProxyModel->index(i, 0).data(AbstractTasksModel::IsDemandingAttention).toBool()) { taskFound = true; break; } } if (taskFound != anyTaskDemandsAttention) { anyTaskDemandsAttention = taskFound; q->anyTaskDemandsAttentionChanged(); } } void TasksModel::Private::initLauncherTasksModel() { if (launcherTasksModel) { return; } launcherTasksModel = new LauncherTasksModel(q); QObject::connect(launcherTasksModel, &LauncherTasksModel::launcherListChanged, q, &TasksModel::launcherListChanged); QObject::connect(launcherTasksModel, &LauncherTasksModel::launcherListChanged, q, &TasksModel::updateLauncherCount); // TODO: On the assumptions that adding/removing launchers is a rare event and // the HasLaunchers data role is rarely used, this refreshes it for all rows in // the model. If those assumptions are proven wrong later, this could be // optimized to only refresh non-launcher rows matching the inserted or about- // to-be-removed launcherTasksModel rows using TaskTools::appsMatch(). QObject::connect(launcherTasksModel, &LauncherTasksModel::launcherListChanged, q, [this]() { q->dataChanged(q->index(0, 0), q->index(q->rowCount() - 1, 0), QVector{AbstractTasksModel::HasLauncher}); } ); // data() implements AbstractTasksModel::HasLauncher by checking with // TaskTools::appsMatch, which evaluates ::AppId and ::LauncherUrlWithoutIcon. QObject::connect(q, &QAbstractItemModel::dataChanged, q, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { if (roles.contains(AbstractTasksModel::AppId) || roles.contains(AbstractTasksModel::LauncherUrlWithoutIcon)) { for (int i = topLeft.row(); i <= bottomRight.row(); ++i) { const QModelIndex &index = q->index(i, 0); if (!index.data(AbstractTasksModel::IsLauncher).toBool()) { q->dataChanged(index, index, QVector{AbstractTasksModel::HasLauncher}); } } } } ); concatProxyModel->addSourceModel(launcherTasksModel); } void TasksModel::Private::updateManualSortMap() { // Empty map; full sort. if (sortedPreFilterRows.isEmpty()) { sortedPreFilterRows.reserve(concatProxyModel->rowCount()); for (int i = 0; i < concatProxyModel->rowCount(); ++i) { sortedPreFilterRows.append(i); } // Full sort. TasksModelLessThan lt(concatProxyModel, q, false); std::stable_sort(sortedPreFilterRows.begin(), sortedPreFilterRows.end(), lt); // Consolidate sort map entries for groups. if (q->groupMode() != GroupDisabled) { for (int i = 0; i < groupingProxyModel->rowCount(); ++i) { const QModelIndex &groupingIndex = groupingProxyModel->index(i, 0); if (groupingIndex.data(AbstractTasksModel::IsGroupParent).toBool()) { consolidateManualSortMapForGroup(groupingIndex); } } } return; } // Existing map; check whether launchers need sorting by launcher list position. if (separateLaunchers) { // Sort only launchers. TasksModelLessThan lt(concatProxyModel, q, true); std::stable_sort(sortedPreFilterRows.begin(), sortedPreFilterRows.end(), lt); // Otherwise process any entries in the insert queue and move them intelligently // in the sort map. } else { - while (sortRowInsertQueue.count()) { - const int row = sortRowInsertQueue.takeFirst(); - const QModelIndex &idx = concatProxyModel->index(sortedPreFilterRows.at(row), 0); + QMutableVectorIterator i(sortRowInsertQueue); + + while (i.hasNext()) { + i.next(); + + const int row = i.value(); + const QModelIndex &idx = concatProxyModel->index(sortedPreFilterRows.at(row), 0); + + // If a window task is currently hidden, we may want to keep it in the queue + // to sort it in later once it gets revealed. + // This is important in concert with taskmanagerrulesrc's SkipTaskbar key, which + // is used to hide window tasks which update from bogus to useful window metadata + // early in startup. Once the task no longer uses bogus metadata listed in the + // config key, its SkipTaskbar role changes to false, and then is it possible to + // sort the task adjacent to its launcher in the code below. + if (idx.data(AbstractTasksModel::IsWindow).toBool() && idx.data(AbstractTasksModel::SkipTaskbar).toBool()) { + // Since we're going to keep a row in the queue for now, make sure to + // mark the queue as stale so it's cleared on appends or row removals + // when they follow this sorting attempt. This frees us from having to + // update the indices in the queue to keep them valid. + // This means windowing system changes such as the opening or closing + // of a window task which happen during the time period that a window + // task has known bogus metadata, can upset what we're trying to + // achieve with this exception. However, due to the briefness of the + // time period and usage patterns, this is improbable, making this + // likely good enough. If it turns out not to be, this decision may be + // revisited later. + sortRowInsertQueueStale = true; + + break; + } else { + i.remove(); + } - bool moved = false; + bool moved = false; - // Try to move the task up to its right-most app sibling, unless this - // is us sorting in a launcher list for the first time. - if (launchersEverSet && !idx.data(AbstractTasksModel::IsLauncher).toBool()) { - for (int i = (row - 1); i >= 0; --i) { - const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); + // Try to move the task up to its right-most app sibling, unless this + // is us sorting in a launcher list for the first time. + if (launchersEverSet && !idx.data(AbstractTasksModel::IsLauncher).toBool()) { + for (int i = (row - 1); i >= 0; --i) { + const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); - if (appsMatch(concatProxyIndex, idx)) { - // Our sort map contains row indices prior to any filtering, but we don't - // want to sort new tasks in next to siblings we're filtering out higher up - // in the proxy chain, so check in with the filter model. - const QModelIndex &filterProxyIndex = filterProxyModel->mapFromSource(concatProxyIndex); + if (appsMatch(concatProxyIndex, idx)) { + // Our sort map contains row indices prior to any filtering, but we don't + // want to sort new tasks in next to siblings we're filtering out higher up + // in the proxy chain, so check in with the filter model. + const QModelIndex &filterProxyIndex = filterProxyModel->mapFromSource(concatProxyIndex); - if (filterProxyIndex.isValid()) { + if (filterProxyIndex.isValid()) { sortedPreFilterRows.move(row, i + 1); moved = true; - } + } - break; - } - } - } + break; + } + } + } - int insertPos = 0; + int insertPos = 0; - // If unsuccessful or skipped, and the new task is a launcher, put after - // the rightmost launcher or launcher-backed task in the map, or failing - // that at the start of the map. - if (!moved && idx.data(AbstractTasksModel::IsLauncher).toBool()) { - for (int i = 0; i < row; ++i) { - const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); + // If unsuccessful or skipped, and the new task is a launcher, put after + // the rightmost launcher or launcher-backed task in the map, or failing + // that at the start of the map. + if (!moved && idx.data(AbstractTasksModel::IsLauncher).toBool()) { + for (int i = 0; i < row; ++i) { + const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); - if (concatProxyIndex.data(AbstractTasksModel::IsLauncher).toBool() + if (concatProxyIndex.data(AbstractTasksModel::IsLauncher).toBool() || launcherTasksModel->launcherPosition(concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()) != -1) { insertPos = i + 1; - } else { + } else { break; - } - } - - sortedPreFilterRows.move(row, insertPos); - moved = true; - } - - // If we sorted in a launcher and it's the first time we're sorting in a - // launcher list, move existing windows to the launcher position now. - if (moved && !launchersEverSet) { - for (int i = (sortedPreFilterRows.count() - 1); i >= 0; --i) { - const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); - - if (!concatProxyIndex.data(AbstractTasksModel::IsLauncher).toBool() - && idx.data(AbstractTasksModel::LauncherUrlWithoutIcon) == concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon)) { - sortedPreFilterRows.move(i, insertPos); - - if (insertPos > i) { - --insertPos; - } - } - } - } + } + } + + sortedPreFilterRows.move(row, insertPos); + moved = true; + } + + // If we sorted in a launcher and it's the first time we're sorting in a + // launcher list, move existing windows to the launcher position now. + if (moved && !launchersEverSet) { + for (int i = (sortedPreFilterRows.count() - 1); i >= 0; --i) { + const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); + + if (!concatProxyIndex.data(AbstractTasksModel::IsLauncher).toBool() + && idx.data(AbstractTasksModel::LauncherUrlWithoutIcon) == concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon)) { + sortedPreFilterRows.move(i, insertPos); + + if (insertPos > i) { + --insertPos; + } + } + } + } } } } void TasksModel::Private::consolidateManualSortMapForGroup(const QModelIndex &groupingProxyIndex) { // Consolidates sort map entries for a group's items to be contiguous // after the group's first item and the same order as in groupingProxyModel. const int childCount = groupingProxyModel->rowCount(groupingProxyIndex); if (!childCount) { return; } const QModelIndex &leader = groupingProxyIndex.child(0, 0); const QModelIndex &preFilterLeader = filterProxyModel->mapToSource(groupingProxyModel->mapToSource(leader)); // We're moving the trailing children to the sort map position of // the first child, so we're skipping the first child. for (int i = 1; i < childCount; ++i) { const QModelIndex &child = groupingProxyIndex.child(i, 0); const QModelIndex &preFilterChild = filterProxyModel->mapToSource(groupingProxyModel->mapToSource(child)); const int leaderPos = sortedPreFilterRows.indexOf(preFilterLeader.row()); const int childPos = sortedPreFilterRows.indexOf(preFilterChild.row()); const int insertPos = (leaderPos + i) + ((leaderPos + i) > childPos ? -1 : 0); sortedPreFilterRows.move(childPos, insertPos); } } void TasksModel::Private::updateGroupInline() { if (usedByQml && !componentComplete) { return; } bool hadSourceModel = (q->sourceModel() != nullptr); if (q->groupMode() != GroupDisabled && groupInline) { if (flattenGroupsProxyModel) { return; } // Exempting tasks which demand attention from grouping is not // necessary when all group children are shown inline anyway // and would interfere with our sort-tasks-together goals. groupingProxyModel->setGroupDemandingAttention(true); // Likewise, ignore the window tasks threshold when making // grouping decisions. groupingProxyModel->setWindowTasksThreshold(-1); flattenGroupsProxyModel = new FlattenTaskGroupsProxyModel(q); flattenGroupsProxyModel->setSourceModel(groupingProxyModel); abstractTasksSourceModel = flattenGroupsProxyModel; q->setSourceModel(flattenGroupsProxyModel); if (sortMode == SortManual) { forceResort(); } } else { if (hadSourceModel && !flattenGroupsProxyModel) { return; } groupingProxyModel->setGroupDemandingAttention(false); groupingProxyModel->setWindowTasksThreshold(groupingWindowTasksThreshold); abstractTasksSourceModel = groupingProxyModel; q->setSourceModel(groupingProxyModel); delete flattenGroupsProxyModel; flattenGroupsProxyModel = nullptr; if (hadSourceModel && sortMode == SortManual) { forceResort(); } } // Minor optimization: We only make these connections after we populate for // the first time to avoid some churn. if (!hadSourceModel) { QObject::connect(q, &QAbstractItemModel::rowsInserted, q, &TasksModel::updateLauncherCount, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::rowsRemoved, q, &TasksModel::updateLauncherCount, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::modelReset, q, &TasksModel::updateLauncherCount, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::rowsInserted, q, &TasksModel::countChanged, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::rowsRemoved, q, &TasksModel::countChanged, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::modelReset, q, &TasksModel::countChanged, Qt::UniqueConnection); } } QModelIndex TasksModel::Private::preFilterIndex(const QModelIndex &sourceIndex) const { // Only in inline grouping mode, we have an additional proxy layer. if (flattenGroupsProxyModel) { return filterProxyModel->mapToSource(groupingProxyModel->mapToSource(flattenGroupsProxyModel->mapToSource(sourceIndex))); } else { return filterProxyModel->mapToSource(groupingProxyModel->mapToSource(sourceIndex)); } } void TasksModel::Private::updateActivityTaskCounts() { // Collects the number of window tasks on each activity. activityTaskCounts.clear(); if (!windowTasksModel || !activityInfo) { return; } foreach(const QString &activity, activityInfo->runningActivities()) { activityTaskCounts.insert(activity, 0); } for (int i = 0; i < windowTasksModel->rowCount(); ++i) { const QModelIndex &windowIndex = windowTasksModel->index(i, 0); const QStringList &activities = windowIndex.data(AbstractTasksModel::Activities).toStringList(); if (activities.isEmpty()) { QMutableHashIterator i(activityTaskCounts); while (i.hasNext()) { i.next(); i.setValue(i.value() + 1); } } else { foreach(const QString &activity, activities) { ++activityTaskCounts[activity]; } } } } void TasksModel::Private::forceResort() { // HACK: This causes QSortFilterProxyModel to run all rows through // our lessThan() implementation again. q->setDynamicSortFilter(false); q->setDynamicSortFilter(true); } bool TasksModel::Private::lessThan(const QModelIndex &left, const QModelIndex &right, bool sortOnlyLaunchers) const { // Launcher tasks go first. // When launchInPlace is enabled, startup and window tasks are sorted // as the launchers they replace (see also move()). if (separateLaunchers) { if (left.data(AbstractTasksModel::IsLauncher).toBool() && right.data(AbstractTasksModel::IsLauncher).toBool()) { return (left.row() < right.row()); } else if (left.data(AbstractTasksModel::IsLauncher).toBool() && !right.data(AbstractTasksModel::IsLauncher).toBool()) { if (launchInPlace) { const int leftPos = q->launcherPosition(left.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); const int rightPos = q->launcherPosition(right.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); if (rightPos != -1) { return (leftPos < rightPos); } } return true; } else if (!left.data(AbstractTasksModel::IsLauncher).toBool() && right.data(AbstractTasksModel::IsLauncher).toBool()) { if (launchInPlace) { const int leftPos = q->launcherPosition(left.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); const int rightPos = q->launcherPosition(right.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); if (leftPos != -1) { return (leftPos < rightPos); } } return false; } else if (launchInPlace) { const int leftPos = q->launcherPosition(left.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); const int rightPos = q->launcherPosition(right.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); if (leftPos != -1 && rightPos != -1) { return (leftPos < rightPos); } else if (leftPos != -1 && rightPos == -1) { return true; } else if (leftPos == -1 && rightPos != -1) { return false; } } } // If told to stop after launchers we fall through to the existing map if it exists. if (sortOnlyLaunchers && !sortedPreFilterRows.isEmpty()) { return (sortedPreFilterRows.indexOf(left.row()) < sortedPreFilterRows.indexOf(right.row())); } // Sort other cases by sort mode. switch (sortMode) { case SortVirtualDesktop: { const QVariant &leftDesktopVariant = left.data(AbstractTasksModel::VirtualDesktop); bool leftOk = false; const int leftDesktop = leftDesktopVariant.toInt(&leftOk); const QVariant &rightDesktopVariant = right.data(AbstractTasksModel::VirtualDesktop); bool rightOk = false; const int rightDesktop = rightDesktopVariant.toInt(&rightOk); if (leftOk && rightOk && (leftDesktop != rightDesktop)) { return (leftDesktop < rightDesktop); } else if (leftOk && !rightOk) { return false; } else if (!leftOk && rightOk) { return true; } } case SortActivity: { // updateActivityTaskCounts() counts the number of window tasks on each // activity. This will sort tasks by comparing a cumulative score made // up of the task counts for each acvtivity a task is assigned to, and // otherwise fall through to alphabetical sorting. int leftScore = -1; int rightScore = -1; const QStringList &leftActivities = left.data(AbstractTasksModel::Activities).toStringList(); if (!leftActivities.isEmpty()) { foreach(const QString& activity, leftActivities) { leftScore += activityTaskCounts[activity]; } } const QStringList &rightActivities = right.data(AbstractTasksModel::Activities).toStringList(); if (!rightActivities.isEmpty()) { foreach(const QString& activity, rightActivities) { rightScore += activityTaskCounts[activity]; } } if (leftScore == -1 || rightScore == -1) { const int sumScore = std::accumulate(activityTaskCounts.constBegin(), activityTaskCounts.constEnd(), 0); if (leftScore == -1) { leftScore = sumScore; } if (rightScore == -1) { rightScore = sumScore; } } if (leftScore != rightScore) { return (leftScore > rightScore); } } // Fall through to source order if sorting is disabled or manual, or alphabetical by app name otherwise. default: { if (sortMode == SortDisabled) { return (left.row() < right.row()); } else { // The overall goal of alphabetic sorting is to sort tasks belonging to the // same app together, while sorting the resulting sets alphabetically among // themselves by the app name. The following code tries to achieve this by // going for AppName first, and falling back to DisplayRole - which for // window-type tasks generally contains the window title - if AppName is // not available. When comparing tasks with identical resulting sort strings, // we sort them by the source model order (i.e. insertion/creation). Older // versions of this code compared tasks by a concatenation of AppName and // DisplayRole at all times, but always sorting by the window title does more // than our goal description - and can cause tasks within an app's set to move // around when window titles change, which is a nuisance for users (especially // in case of tabbed apps that have the window title reflect the active tab, // e.g. web browsers). To recap, the common case is "sort by AppName, then // insertion order", only swapping out AppName for DisplayRole (i.e. window // title) when necessary. QString leftSortString = left.data(AbstractTasksModel::AppName).toString(); if (leftSortString.isEmpty()) { leftSortString = left.data(Qt::DisplayRole).toString(); } QString rightSortString = right.data(AbstractTasksModel::AppName).toString(); if (rightSortString.isEmpty()) { rightSortString = right.data(Qt::DisplayRole).toString(); } const int sortResult = leftSortString.localeAwareCompare(rightSortString); // If the string are identical fall back to source model (creation/append) order. if (sortResult == 0) { return (left.row() < right.row()); } return (sortResult < 0); } } } } TasksModel::TasksModel(QObject *parent) : QSortFilterProxyModel(parent) , d(new Private(this)) { d->initModels(); // Start sorting. sort(0); // Private::updateGroupInline() sets our source model, populating the model. We // delay running this until the QML runtime had a chance to call our implementation // of QQmlParserStatus::classBegin(), setting Private::usedByQml to true. If used // by QML, Private::updateGroupInline() will abort if the component is not yet // complete, instead getting called through QQmlParserStatus::componentComplete() // only after all properties have been set. This avoids delegate churn in Qt Quick // views using the model. If not used by QML, Private::updateGroupInline() will run // directly. QTimer::singleShot(0, this, [this]() { d->updateGroupInline(); }); } TasksModel::~TasksModel() { } QHash TasksModel::roleNames() const { if (d->windowTasksModel) { return d->windowTasksModel->roleNames(); } return QHash(); } int TasksModel::rowCount(const QModelIndex &parent) const { return QSortFilterProxyModel::rowCount(parent); } QVariant TasksModel::data(const QModelIndex &proxyIndex, int role) const { if (role == AbstractTasksModel::HasLauncher && proxyIndex.isValid() && proxyIndex.row() < rowCount()) { if (proxyIndex.data(AbstractTasksModel::IsLauncher).toBool()) { return true; } else { if (!d->launcherTasksModel) { return false; } for (int i = 0; i < d->launcherTasksModel->rowCount(); ++i) { const QModelIndex &launcherIndex = d->launcherTasksModel->index(i, 0); if (appsMatch(proxyIndex, launcherIndex)) { return true; } } return false; } } else if (rowCount(proxyIndex) && role == AbstractTasksModel::LegacyWinIdList) { QVariantList winIds; for (int i = 0; i < rowCount(proxyIndex); ++i) { winIds.append(proxyIndex.child(i, 0).data(AbstractTasksModel::LegacyWinIdList).toList()); } return winIds; } return QSortFilterProxyModel::data(proxyIndex, role); } void TasksModel::updateLauncherCount() { if (!d->launcherTasksModel) { return; } int count = 0; for (int i = 0; i < rowCount(); ++i) { if (index(i, 0).data(AbstractTasksModel::IsLauncher).toBool()) { ++count; } } if (d->launcherCount != count) { d->launcherCount = count; emit launcherCountChanged(); } } int TasksModel::launcherCount() const { return d->launcherCount; } bool TasksModel::anyTaskDemandsAttention() const { return d->anyTaskDemandsAttention; } int TasksModel::virtualDesktop() const { return d->filterProxyModel->virtualDesktop(); } void TasksModel::setVirtualDesktop(int virtualDesktop) { d->filterProxyModel->setVirtualDesktop(virtualDesktop); } QRect TasksModel::screenGeometry() const { return d->filterProxyModel->screenGeometry(); } void TasksModel::setScreenGeometry(const QRect &geometry) { d->filterProxyModel->setScreenGeometry(geometry); } QString TasksModel::activity() const { return d->filterProxyModel->activity(); } void TasksModel::setActivity(const QString &activity) { d->filterProxyModel->setActivity(activity); } bool TasksModel::filterByVirtualDesktop() const { return d->filterProxyModel->filterByVirtualDesktop(); } void TasksModel::setFilterByVirtualDesktop(bool filter) { d->filterProxyModel->setFilterByVirtualDesktop(filter); } bool TasksModel::filterByScreen() const { return d->filterProxyModel->filterByScreen(); } void TasksModel::setFilterByScreen(bool filter) { d->filterProxyModel->setFilterByScreen(filter); } bool TasksModel::filterByActivity() const { return d->filterProxyModel->filterByActivity(); } void TasksModel::setFilterByActivity(bool filter) { d->filterProxyModel->setFilterByActivity(filter); } bool TasksModel::filterNotMinimized() const { return d->filterProxyModel->filterNotMinimized(); } void TasksModel::setFilterNotMinimized(bool filter) { d->filterProxyModel->setFilterNotMinimized(filter); } TasksModel::SortMode TasksModel::sortMode() const { return d->sortMode; } void TasksModel::setSortMode(SortMode mode) { if (d->sortMode != mode) { if (mode == SortManual) { d->updateManualSortMap(); } else if (d->sortMode == SortManual) { d->sortedPreFilterRows.clear(); } if (mode == SortActivity) { if (!d->activityInfo) { d->activityInfo = new ActivityInfo(); } ++d->activityInfoUsers; d->updateActivityTaskCounts(); setSortRole(AbstractTasksModel::Activities); } else if (d->sortMode == SortActivity) { --d->activityInfoUsers; if (!d->activityInfoUsers) { delete d->activityInfo; d->activityInfo = nullptr; } d->activityTaskCounts.clear(); setSortRole(Qt::DisplayRole); } d->sortMode = mode; d->forceResort(); emit sortModeChanged(); } } bool TasksModel::separateLaunchers() const { return d->separateLaunchers; } void TasksModel::setSeparateLaunchers(bool separate) { if (d->separateLaunchers != separate) { d->separateLaunchers = separate; d->updateManualSortMap(); d->forceResort(); emit separateLaunchersChanged(); } } bool TasksModel::launchInPlace() const { return d->launchInPlace; } void TasksModel::setLaunchInPlace(bool launchInPlace) { if (d->launchInPlace != launchInPlace) { d->launchInPlace = launchInPlace; d->forceResort(); emit launchInPlaceChanged(); } } TasksModel::GroupMode TasksModel::groupMode() const { if (!d->groupingProxyModel) { return GroupDisabled; } return d->groupingProxyModel->groupMode(); } void TasksModel::setGroupMode(GroupMode mode) { if (d->groupingProxyModel) { if (mode == GroupDisabled && d->flattenGroupsProxyModel) { d->flattenGroupsProxyModel->setSourceModel(nullptr); } d->groupingProxyModel->setGroupMode(mode); d->updateGroupInline(); } } bool TasksModel::groupInline() const { return d->groupInline; } void TasksModel::setGroupInline(bool groupInline) { if (d->groupInline != groupInline) { d->groupInline = groupInline; d->updateGroupInline(); emit groupInlineChanged(); } } int TasksModel::groupingWindowTasksThreshold() const { return d->groupingWindowTasksThreshold; } void TasksModel::setGroupingWindowTasksThreshold(int threshold) { if (d->groupingWindowTasksThreshold != threshold) { d->groupingWindowTasksThreshold = threshold; if (!d->groupInline && d->groupingProxyModel) { d->groupingProxyModel->setWindowTasksThreshold(threshold); } emit groupingWindowTasksThresholdChanged(); } } QStringList TasksModel::groupingAppIdBlacklist() const { if (!d->groupingProxyModel) { return QStringList(); } return d->groupingProxyModel->blacklistedAppIds(); } void TasksModel::setGroupingAppIdBlacklist(const QStringList &list) { if (d->groupingProxyModel) { d->groupingProxyModel->setBlacklistedAppIds(list); } } QStringList TasksModel::groupingLauncherUrlBlacklist() const { if (!d->groupingProxyModel) { return QStringList(); } return d->groupingProxyModel->blacklistedLauncherUrls(); } void TasksModel::setGroupingLauncherUrlBlacklist(const QStringList &list) { if (d->groupingProxyModel) { d->groupingProxyModel->setBlacklistedLauncherUrls(list); } } QStringList TasksModel::launcherList() const { if (d->launcherTasksModel) { return d->launcherTasksModel->launcherList(); } return QStringList(); } void TasksModel::setLauncherList(const QStringList &launchers) { d->initLauncherTasksModel(); d->launcherTasksModel->setLauncherList(launchers); d->launchersEverSet = true; } bool TasksModel::requestAddLauncher(const QUrl &url) { d->initLauncherTasksModel(); bool added = d->launcherTasksModel->requestAddLauncher(url); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks to // their launcher position now. if (added && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return added; } bool TasksModel::requestRemoveLauncher(const QUrl &url) { if (d->launcherTasksModel) { bool removed = d->launcherTasksModel->requestRemoveLauncher(url); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks no // longer backed by a launcher out of the launcher area. if (removed && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return removed; } return false; } bool TasksModel::requestAddLauncherToActivity(const QUrl &url, const QString &activity) { d->initLauncherTasksModel(); bool added = d->launcherTasksModel->requestAddLauncherToActivity(url, activity); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks to // their launcher position now. if (added && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return added; } bool TasksModel::requestRemoveLauncherFromActivity(const QUrl &url, const QString &activity) { if (d->launcherTasksModel) { bool removed = d->launcherTasksModel->requestRemoveLauncherFromActivity(url, activity); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks no // longer backed by a launcher out of the launcher area. if (removed && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return removed; } return false; } QStringList TasksModel::launcherActivities(const QUrl &url) { if (d->launcherTasksModel) { return d->launcherTasksModel->launcherActivities(url); } return {}; } int TasksModel::launcherPosition(const QUrl &url) const { if (d->launcherTasksModel) { return d->launcherTasksModel->launcherPosition(url); } return -1; } void TasksModel::requestActivate(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestActivate(mapToSource(index)); } } void TasksModel::requestNewInstance(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestNewInstance(mapToSource(index)); } } void TasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestOpenUrls(mapToSource(index), urls); } } void TasksModel::requestClose(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestClose(mapToSource(index)); } } void TasksModel::requestMove(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestMove(mapToSource(index)); } } void TasksModel::requestResize(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestResize(mapToSource(index)); } } void TasksModel::requestToggleMinimized(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleMinimized(mapToSource(index)); } } void TasksModel::requestToggleMaximized(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleMaximized(mapToSource(index)); } } void TasksModel::requestToggleKeepAbove(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleKeepAbove(mapToSource(index)); } } void TasksModel::requestToggleKeepBelow(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleKeepBelow(mapToSource(index)); } } void TasksModel::requestToggleFullScreen(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleFullScreen(mapToSource(index)); } } void TasksModel::requestToggleShaded(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleShaded(mapToSource(index)); } } void TasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestVirtualDesktop(mapToSource(index), desktop); } } void TasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { if (index.isValid() && index.model() == this) { d->groupingProxyModel->requestActivities(mapToSource(index), activities); } } void TasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestPublishDelegateGeometry(mapToSource(index), geometry, delegate); } } void TasksModel::requestToggleGrouping(const QModelIndex &index) { if (index.isValid() && index.model() == this) { const QModelIndex &target = (d->flattenGroupsProxyModel ? d->flattenGroupsProxyModel->mapToSource(mapToSource(index)) : mapToSource(index)); d->groupingProxyModel->requestToggleGrouping(target); } } bool TasksModel::move(int row, int newPos, const QModelIndex &parent) { if (d->sortMode != SortManual || row == newPos || newPos < 0 || newPos >= rowCount(parent)) { return false; } const QModelIndex &idx = index(row, 0); bool isLauncherMove = false; // Figure out if we're moving a launcher so we can run barrier checks. if (idx.isValid()) { if (idx.data(AbstractTasksModel::IsLauncher).toBool()) { isLauncherMove = true; // When using launch-in-place sorting, launcher-backed window tasks act as launchers. } else if ((d->launchInPlace || !d->separateLaunchers) && idx.data(AbstractTasksModel::IsWindow).toBool()) { const QUrl &launcherUrl = idx.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); const int launcherPos = launcherPosition(launcherUrl); if (launcherPos != -1) { isLauncherMove = true; } } } else { return false; } if (d->separateLaunchers) { const int firstTask = (d->launcherTasksModel ? (d->launchInPlace ? d->launcherTasksModel->rowCount() : launcherCount()) : 0); // Don't allow launchers to be moved past the last launcher. if (isLauncherMove && newPos >= firstTask) { return false; } // Don't allow tasks to be moved into the launchers. if (!isLauncherMove && newPos < firstTask) { return false; } } // Treat flattened-out groups as single items. if (d->flattenGroupsProxyModel) { QModelIndex groupingRowIndex = d->flattenGroupsProxyModel->mapToSource(mapToSource(index(row, 0))); const QModelIndex &groupingRowIndexParent = groupingRowIndex.parent(); QModelIndex groupingNewPosIndex = d->flattenGroupsProxyModel->mapToSource(mapToSource(index(newPos, 0))); const QModelIndex &groupingNewPosIndexParent = groupingNewPosIndex.parent(); // Disallow moves within a flattened-out group (TODO: for now, anyway). if (groupingRowIndexParent.isValid() && (groupingRowIndexParent == groupingNewPosIndex || groupingRowIndexParent == groupingNewPosIndexParent)) { return false; } int offset = 0; int extraChildCount = 0; if (groupingRowIndexParent.isValid()) { offset = groupingRowIndex.row(); extraChildCount = d->groupingProxyModel->rowCount(groupingRowIndexParent) - 1; groupingRowIndex = groupingRowIndexParent; } if (groupingNewPosIndexParent.isValid()) { int extra = d->groupingProxyModel->rowCount(groupingNewPosIndexParent) - 1; if (newPos > row) { newPos += extra; newPos -= groupingNewPosIndex.row(); groupingNewPosIndex = groupingNewPosIndexParent.child(extra, 0); } else { newPos -= groupingNewPosIndex.row(); groupingNewPosIndex = groupingNewPosIndexParent; } } beginMoveRows(QModelIndex(), (row - offset), (row - offset) + extraChildCount, QModelIndex(), (newPos > row) ? newPos + 1 : newPos); row = d->sortedPreFilterRows.indexOf(d->filterProxyModel->mapToSource(d->groupingProxyModel->mapToSource(groupingRowIndex)).row()); newPos = d->sortedPreFilterRows.indexOf(d->filterProxyModel->mapToSource(d->groupingProxyModel->mapToSource(groupingNewPosIndex)).row()); // Update sort mappings. d->sortedPreFilterRows.move(row, newPos); if (groupingRowIndexParent.isValid()) { d->consolidateManualSortMapForGroup(groupingRowIndexParent); } endMoveRows(); } else { beginMoveRows(parent, row, row, parent, (newPos > row) ? newPos + 1 : newPos); // Translate to sort map indices. const QModelIndex &groupingRowIndex = mapToSource(index(row, 0)); const QModelIndex &preFilterRowIndex = d->preFilterIndex(groupingRowIndex); row = d->sortedPreFilterRows.indexOf(preFilterRowIndex.row()); newPos = d->sortedPreFilterRows.indexOf(d->preFilterIndex(mapToSource(index(newPos, 0))).row()); // Update sort mapping. d->sortedPreFilterRows.move(row, newPos); // If we moved a group parent, consolidate sort map for children. if (!parent.isValid() && groupMode() != GroupDisabled && d->groupingProxyModel->rowCount(groupingRowIndex)) { d->consolidateManualSortMapForGroup(groupingRowIndex); } endMoveRows(); } // Resort. d->forceResort(); if (!d->separateLaunchers && isLauncherMove) { const QModelIndex &idx = d->concatProxyModel->index(d->sortedPreFilterRows.at(newPos), 0); const QUrl &launcherUrl = idx.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); // Move launcher for launcher-backed task along with task if launchers // are not being kept separate. // We don't need to resort again because the launcher is implictly hidden // at this time. if (!idx.data(AbstractTasksModel::IsLauncher).toBool()) { const int launcherPos = d->launcherTasksModel->launcherPosition(launcherUrl); const QModelIndex &launcherIndex = d->launcherTasksModel->index(launcherPos, 0); const int sortIndex = d->sortedPreFilterRows.indexOf(d->concatProxyModel->mapFromSource(launcherIndex).row()); d->sortedPreFilterRows.move(sortIndex, newPos); // Otherwise move matching windows to after the launcher task (they are // currently hidden but might be on another virtual desktop). } else { for (int i = (d->sortedPreFilterRows.count() - 1); i >= 0; --i) { const QModelIndex &concatProxyIndex = d->concatProxyModel->index(d->sortedPreFilterRows.at(i), 0); if (launcherUrl == concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()) { d->sortedPreFilterRows.move(i, newPos); if (newPos > i) { --newPos; } } } } } // Setup for syncLaunchers(). d->launcherSortingDirty = isLauncherMove; return true; } void TasksModel::syncLaunchers() { // Writes the launcher order exposed through the model back to the launcher // tasks model, committing any move() operations to persistent state. if (!d->launcherTasksModel || !d->launcherSortingDirty) { return; } QMap sortedShownLaunchers; QStringList sortedHiddenLaunchers; foreach(const QString &launcherUrlStr, launcherList()) { int row = -1; QStringList activities; QUrl launcherUrl; std::tie(launcherUrl, activities) = deserializeLauncher(launcherUrlStr); for (int i = 0; i < rowCount(); ++i) { const QUrl &rowLauncherUrl = index(i, 0).data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); if (launcherUrlsMatch(launcherUrl, rowLauncherUrl, IgnoreQueryItems)) { row = i; break; } } if (row != -1) { sortedShownLaunchers.insert(row, launcherUrlStr); } else { sortedHiddenLaunchers << launcherUrlStr; } } // Prep sort map for source model data changes. if (d->sortMode == SortManual) { QVector sortMapIndices; QVector preFilterRows; for (int i = 0; i < d->launcherTasksModel->rowCount(); ++i) { const QModelIndex &launcherIndex = d->launcherTasksModel->index(i, 0); const QModelIndex &concatIndex = d->concatProxyModel->mapFromSource(launcherIndex); sortMapIndices << d->sortedPreFilterRows.indexOf(concatIndex.row()); preFilterRows << concatIndex.row(); } // We're going to write back launcher model entries in the sort // map in concat model order, matching the reordered launcher list // we're about to pass down. std::sort(sortMapIndices.begin(), sortMapIndices.end()); for (int i = 0; i < sortMapIndices.count(); ++i) { d->sortedPreFilterRows.replace(sortMapIndices.at(i), preFilterRows.at(i)); } } setLauncherList(sortedShownLaunchers.values() + sortedHiddenLaunchers); d->launcherSortingDirty = false; } QModelIndex TasksModel::activeTask() const { for (int i = 0; i < rowCount(); ++i) { const QModelIndex &idx = index(i, 0); if (idx.data(AbstractTasksModel::IsActive).toBool()) { if (groupMode() != GroupDisabled && rowCount(idx)) { for (int j = 0; j < rowCount(idx); ++j) { const QModelIndex &child = idx.child(j, 0); if (child.data(AbstractTasksModel::IsActive).toBool()) { return child; } } } else { return idx; } } } return QModelIndex(); } QModelIndex TasksModel::makeModelIndex(int row, int childRow) const { if (row < 0 || row >= rowCount()) { return QModelIndex(); } if (childRow == -1) { return index(row, 0); } else { const QModelIndex &parent = index(row, 0); if (childRow < rowCount(parent)) { return parent.child(childRow, 0); } } return QModelIndex(); } QPersistentModelIndex TasksModel::makePersistentModelIndex(int row, int childCount) const { return QPersistentModelIndex(makeModelIndex(row, childCount)); } void TasksModel::classBegin() { d->usedByQml = true; } void TasksModel::componentComplete() { d->componentComplete = true; // Sets our source model, populating the model. d->updateGroupInline(); } bool TasksModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { // All our filtering occurs at the top-level; anything below always // goes through. if (sourceParent.isValid()) { return true; } const QModelIndex &sourceIndex = sourceModel()->index(sourceRow, 0); // In inline grouping mode, filter out group parents. if (d->groupInline && d->flattenGroupsProxyModel && sourceIndex.data(AbstractTasksModel::IsGroupParent).toBool()) { return false; } const QString &appId = sourceIndex.data(AbstractTasksModel::AppId).toString(); const QString &appName = sourceIndex.data(AbstractTasksModel::AppName).toString(); // Filter startup tasks we already have a window task for. if (sourceIndex.data(AbstractTasksModel::IsStartup).toBool()) { for (int i = 0; i < d->filterProxyModel->rowCount(); ++i) { const QModelIndex &filterIndex = d->filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsWindow).toBool()) { continue; } if ((!appId.isEmpty() && appId == filterIndex.data(AbstractTasksModel::AppId).toString()) || (!appName.isEmpty() && appName == filterIndex.data(AbstractTasksModel::AppName).toString())) { return false; } } } // Filter launcher tasks we already have a startup or window task for (that // got through filtering). if (sourceIndex.data(AbstractTasksModel::IsLauncher).toBool()) { for (int i = 0; i < d->filterProxyModel->rowCount(); ++i) { const QModelIndex &filteredIndex = d->filterProxyModel->index(i, 0); if (!filteredIndex.data(AbstractTasksModel::IsWindow).toBool() && !filteredIndex.data(AbstractTasksModel::IsStartup).toBool()) { continue; } if (appsMatch(sourceIndex, filteredIndex)) { return false; } } } return true; } bool TasksModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { // In manual sort mode, sort by map. if (d->sortMode == SortManual) { return (d->sortedPreFilterRows.indexOf(d->preFilterIndex(left).row()) < d->sortedPreFilterRows.indexOf(d->preFilterIndex(right).row())); } return d->lessThan(left, right); } } diff --git a/libtaskmanager/tasktools.cpp b/libtaskmanager/tasktools.cpp index 6be094e24..090981eb9 100644 --- a/libtaskmanager/tasktools.cpp +++ b/libtaskmanager/tasktools.cpp @@ -1,781 +1,807 @@ /******************************************************************** Copyright 2016 Eike Hein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "tasktools.h" #include "abstracttasksmodel.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if HAVE_X11 #include #endif namespace TaskManager { AppData appDataFromUrl(const QUrl &url, const QIcon &fallbackIcon) { AppData data; data.url = url; if (url.hasQuery()) { QUrlQuery uQuery(url); if (uQuery.hasQueryItem(QLatin1String("iconData"))) { QString iconData(uQuery.queryItemValue(QLatin1String("iconData"))); QPixmap pixmap; QByteArray bytes = QByteArray::fromBase64(iconData.toLocal8Bit(), QByteArray::Base64UrlEncoding); pixmap.loadFromData(bytes); data.icon.addPixmap(pixmap); } + + if (uQuery.hasQueryItem(QLatin1String("skipTaskbar"))) { + QString skipTaskbar(uQuery.queryItemValue(QLatin1String("skipTaskbar"))); + data.skipTaskbar = (skipTaskbar == QStringLiteral("true")); + } } // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (url.scheme() == QStringLiteral("applications")) { const KService::Ptr service = KService::serviceByMenuId(url.path()); if (service && url.path() == service->menuId()) { data.name = service->name(); data.genericName = service->genericName(); data.id = service->storageId(); if (data.icon.isNull()) { data.icon = QIcon::fromTheme(service->icon()); } } } if (url.isLocalFile() && KDesktopFile::isDesktopFile(url.toLocalFile())) { KDesktopFile f(url.toLocalFile()); const KService::Ptr service = KService::serviceByStorageId(f.fileName()); // Resolve to non-absolute menuId-based URL if possible. if (service) { const QString &menuId = service->menuId(); if (!menuId.isEmpty()) { data.url = QUrl(QStringLiteral("applications:") + menuId); } } if (service && QUrl::fromLocalFile(service->entryPath()) == url) { data.name = service->name(); data.genericName = service->genericName(); data.id = service->storageId(); if (data.icon.isNull()) { data.icon = QIcon::fromTheme(service->icon()); } } else if (f.tryExec()) { data.name = f.readName(); data.genericName = f.readGenericName(); data.id = QUrl::fromLocalFile(f.fileName()).fileName(); if (data.icon.isNull()) { data.icon = QIcon::fromTheme(f.readIcon()); } } if (data.id.endsWith(".desktop")) { data.id = data.id.left(data.id.length() - 8); } } else if (url.scheme() == QLatin1String("preferred")) { data.id = defaultApplication(url); const KService::Ptr service = KService::serviceByStorageId(data.id); if (service) { const QString &menuId = service->menuId(); const QString &desktopFile = service->entryPath(); data.name = service->name(); data.genericName = service->genericName(); data.id = service->storageId(); if (data.icon.isNull()) { data.icon = QIcon::fromTheme(service->icon()); } // Update with resolved URL. if (!menuId.isEmpty()) { data.url = QUrl(QStringLiteral("applications:") + menuId); } else { data.url = QUrl::fromLocalFile(desktopFile); } } } if (data.name.isEmpty()) { data.name = url.fileName(); } if (data.icon.isNull()) { data.icon = fallbackIcon; } return data; } AppData appDataFromAppId(const QString &appId) { AppData data; KService::Ptr service = KService::serviceByStorageId(appId); if (service) { data.id = service->storageId(); data.name = service->name(); data.genericName = service->genericName(); const QString &menuId = service->menuId(); // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (!menuId.isEmpty()) { data.url = QUrl(QStringLiteral("applications:") + menuId); } else { data.url = QUrl::fromLocalFile(service->entryPath()); } return data; } QString desktopFile = appId; if (!desktopFile.endsWith(QLatin1String(".desktop"))) { desktopFile.append(QLatin1String(".desktop")); } if (KDesktopFile::isDesktopFile(desktopFile) && QFile::exists(desktopFile)) { KDesktopFile f(desktopFile); data.id = QUrl::fromLocalFile(f.fileName()).fileName(); if (data.id.endsWith(QLatin1String(".desktop"))) { data.id = data.id.left(data.id.length() - 8); } data.name = f.readName(); data.genericName = f.readGenericName(); data.url = QUrl::fromLocalFile(desktopFile); } return data; } QUrl windowUrlFromMetadata(const QString &appId, quint32 pid, KSharedConfig::Ptr rulesConfig, const QString &xWindowsWMClassName) { if (!rulesConfig) { return QUrl(); } QUrl url; KService::List services; bool triedPid = false; // The code below this function goes on a hunt for services based on the metadata // that has been passed in. Occasionally, it will find more than one matching // service. In some scenarios (e.g. multiple identically-named .desktop files) // there's a need to pick the most useful one. The function below promises to "sort" // a list of services by how closely their KService::menuId() relates to the key that // has been passed in. The current naive implementation simply looks for a menuId // that starts with the key, prepends it to the list and returns it. In practice, // that means a KService with a menuId matching the appId will win over one with a // menuId that encodes a subfolder hierarchy. // A concrete example: Valve's Steam client is sometimes installed two times, once // natively as a Linux application, once via Wine. Both have .desktop files named // (S|)steam.desktop. The Linux native version is located in the menu by means of // categorization ("Games") and just has a menuId() matching the .desktop file name, // but the Wine version is placed in a folder hierarchy by Wine and gets a menuId() // of wine-Programs-Steam-Steam.desktop. The weighing done by this function makes // sure the Linux native version gets mapped to the former, while other heuristics // map the Wine version reliably to the latter. // In lieu of this weighing we just used whatever KServiceTypeTrader returned first, // so what we do here can be no worse. auto sortServicesByMenuId = [](KService::List &services, const QString &key) { if (services.count() == 1) { return; } for (const auto service : services) { if (service->menuId().startsWith(key, Qt::CaseInsensitive)) { services.prepend(service); return; } } }; if (!(appId.isEmpty() && xWindowsWMClassName.isEmpty())) { // Check to see if this wmClass matched a saved one ... KConfigGroup grp(rulesConfig, "Mapping"); KConfigGroup set(rulesConfig, "Settings"); // Evaluate MatchCommandLineFirst directives from config first. // Some apps have different launchers depending upon command line ... QStringList matchCommandLineFirst = set.readEntry("MatchCommandLineFirst", QStringList()); if (!appId.isEmpty() && matchCommandLineFirst.contains(appId)) { triedPid = true; services = servicesFromPid(pid, rulesConfig); } // Try to match using xWindowsWMClassName also. if (!xWindowsWMClassName.isEmpty() && matchCommandLineFirst.contains("::"+xWindowsWMClassName)) { triedPid = true; services = servicesFromPid(pid, rulesConfig); } if (!appId.isEmpty()) { // Evaluate any mapping rules that map to a specific .desktop file. QString mapped(grp.readEntry(appId + "::" + xWindowsWMClassName, QString())); if (mapped.endsWith(QLatin1String(".desktop"))) { url = QUrl(mapped); return url; } if (mapped.isEmpty()) { mapped = grp.readEntry(appId, QString()); if (mapped.endsWith(QLatin1String(".desktop"))) { url = QUrl(mapped); return url; } } // Some apps, such as Wine, cannot use xWindowsWMClassName to map to launcher name - as Wine itself is not a GUI app // So, Settings/ManualOnly lists window classes where the user will always have to manualy set the launcher ... QStringList manualOnly = set.readEntry("ManualOnly", QStringList()); if (!appId.isEmpty() && manualOnly.contains(appId)) { return url; } // Try matching both appId and xWindowsWMClassName against StartupWMClass. // We do this before evaluating the mapping rules further, because StartupWMClass // is essentially a mapping rule, and we expect it to be set deliberately and // sensibly to instruct us what to do. Also, mapping rules // // StartupWMClass=STRING // // If true, it is KNOWN that the application will map at least one // window with the given string as its WM class or WM name hint. // // Source: https://specifications.freedesktop.org/startup-notification-spec/startup-notification-0.1.txt if (services.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ StartupWMClass)").arg(appId)); sortServicesByMenuId(services, appId); } if (services.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ StartupWMClass)").arg(xWindowsWMClassName)); sortServicesByMenuId(services, xWindowsWMClassName); } // Evaluate rewrite rules from config. if (services.isEmpty()) { KConfigGroup rewriteRulesGroup(rulesConfig, QStringLiteral("Rewrite Rules")); if (rewriteRulesGroup.hasGroup(appId)) { KConfigGroup rewriteGroup(&rewriteRulesGroup, appId); const QStringList &rules = rewriteGroup.groupList(); for (const QString &rule : rules) { KConfigGroup ruleGroup(&rewriteGroup, rule); const QString propertyConfig = ruleGroup.readEntry(QStringLiteral("Property"), QString()); QString matchProperty; if (propertyConfig == QLatin1String("ClassClass")) { matchProperty = appId; } else if (propertyConfig == QLatin1String("ClassName")) { matchProperty = xWindowsWMClassName; } if (matchProperty.isEmpty()) { continue; } const QString serviceSearchIdentifier = ruleGroup.readEntry(QStringLiteral("Identifier"), QString()); if (serviceSearchIdentifier.isEmpty()) { continue; } QRegularExpression regExp(ruleGroup.readEntry(QStringLiteral("Match"))); const auto match = regExp.match(matchProperty); if (match.hasMatch()) { const QString actualMatch = match.captured(QStringLiteral("match")); if (actualMatch.isEmpty()) { continue; } QString rewrittenString = ruleGroup.readEntry(QStringLiteral("Target")).arg(actualMatch); // If no "Target" is provided, instead assume the matched property (appId/xWindowsWMClassName). if (rewrittenString.isEmpty()) { rewrittenString = matchProperty; } services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ %2)").arg(rewrittenString, serviceSearchIdentifier)); sortServicesByMenuId(services, serviceSearchIdentifier); if (!services.isEmpty()) { break; } } } } } // The appId looks like a path. if (services.isEmpty() && appId.startsWith(QStringLiteral("/"))) { // Check if it's a path to a .desktop file. if (KDesktopFile::isDesktopFile(appId) && QFile::exists(appId)) { return QUrl::fromLocalFile(appId); } // Check if the appId passes as a .desktop file path if we add the extension. const QString appIdPlusExtension(appId + QStringLiteral(".desktop")); if (KDesktopFile::isDesktopFile(appIdPlusExtension) && QFile::exists(appIdPlusExtension)) { return QUrl::fromLocalFile(appIdPlusExtension); } } // Try matching mapped name against DesktopEntryName. if (!mapped.isEmpty() && services.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ DesktopEntryName) and (not exist NoDisplay or not NoDisplay)").arg(mapped)); sortServicesByMenuId(services, mapped); } // Try matching mapped name against 'Name'. if (!mapped.isEmpty() && services.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Name) and (not exist NoDisplay or not NoDisplay)").arg(mapped)); sortServicesByMenuId(services, mapped); } // Try matching appId against DesktopEntryName. if (services.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ DesktopEntryName) and (not exist NoDisplay or not NoDisplay)").arg(appId)); sortServicesByMenuId(services, appId); } // Try matching appId against 'Name'. // This has a shaky chance of success as appId is untranslated, but 'Name' may be localized. if (services.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Name) and (not exist NoDisplay or not NoDisplay)").arg(appId)); sortServicesByMenuId(services, appId); } + + // Check rules configuration for whether we want to hide this task. + // Some window tasks update from bogus to useful metadata early during startup. + // This config key allows listing the bogus metadata, and the matching window + // tasks are hidden until they perform a metadate update that stops them from + // matching. + QStringList skipTaskbar = set.readEntry("SkipTaskbar", QStringList()); + + if (skipTaskbar.contains(appId)) { + QUrlQuery query(url); + query.addQueryItem(QStringLiteral("skipTaskbar"), QStringLiteral("true")); + url.setQuery(query); + } else if (skipTaskbar.contains(mapped)) { + QUrlQuery query(url); + query.addQueryItem(QStringLiteral("skipTaskbar"), QStringLiteral("true")); + url.setQuery(query); + } } // Ok, absolute *last* chance, try matching via pid (but only if we have not already tried this!) ... if (services.isEmpty() && !triedPid) { services = servicesFromPid(pid, rulesConfig); } } // Try to improve on a possible from-binary fallback. // If no services were found or we got a fake-service back from getServicesViaPid() // we attempt to improve on this by adding a loosely matched reverse-domain-name // DesktopEntryName. Namely anything that is '*.appId.desktop' would qualify here. // // Illustrative example of a case where the above heuristics would fail to produce // a reasonable result: // - org.kde.dragonplayer.desktop // - binary is 'dragon' // - qapp appname and thus appId is 'dragonplayer' // - appId cannot directly match the desktop file because of RDN // - appId also cannot match the binary because of name mismatch // - in the following code *.appId can match org.kde.dragonplayer though if (services.isEmpty() || services.at(0)->desktopEntryName().isEmpty()) { auto matchingServices = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' ~~ DesktopEntryName)").arg(appId)); QMutableListIterator it(matchingServices); while (it.hasNext()) { auto service = it.next(); if (!service->desktopEntryName().endsWith("." + appId)) { it.remove(); } } // Exactly one match is expected, otherwise we discard the results as to reduce // the likelihood of false-positive mappings. Since we essentially eliminate the // uniqueness that RDN is meant to bring to the table we could potentially end // up with more than one match here. if (matchingServices.length() == 1) { services = matchingServices; } } if (!services.isEmpty()) { const QString &menuId = services.at(0)->menuId(); // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (!menuId.isEmpty()) { - return QUrl(QStringLiteral("applications:") + menuId); + url.setUrl(QStringLiteral("applications:") + menuId); + return url; } QString path = services.at(0)->entryPath(); if (path.isEmpty()) { path = services.at(0)->exec(); } if (!path.isEmpty()) { + QString query = url.query(); url = QUrl::fromLocalFile(path); + url.setQuery(query); + return url; } } return url; } KService::List servicesFromPid(quint32 pid, KSharedConfig::Ptr rulesConfig) { if (pid == 0) { return KService::List(); } if (!rulesConfig) { return KService::List(); } KSysGuard::Processes procs; procs.updateOrAddProcess(pid); KSysGuard::Process *proc = procs.getProcess(pid); const QString &cmdLine = proc ? proc->command().simplified() : QString(); // proc->command has a trailing space??? if (cmdLine.isEmpty()) { return KService::List(); } return servicesFromCmdLine(cmdLine, proc->name(), rulesConfig); } KService::List servicesFromCmdLine(const QString &_cmdLine, const QString &processName, KSharedConfig::Ptr rulesConfig) { QString cmdLine = _cmdLine; KService::List services; if (!rulesConfig) { return services; } const int firstSpace = cmdLine.indexOf(' '); int slash = 0; services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdLine)); if (services.isEmpty()) { // Could not find with complete command line, so strip out the path part ... slash = cmdLine.lastIndexOf('/', firstSpace); if (slash > 0) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdLine.mid(slash + 1))); } } if (services.isEmpty() && firstSpace > 0) { // Could not find with arguments, so try without ... cmdLine = cmdLine.left(firstSpace); services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdLine)); if (services.isEmpty()) { slash = cmdLine.lastIndexOf('/'); if (slash > 0) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdLine.mid(slash + 1))); } } } if (services.isEmpty()) { KConfigGroup set(rulesConfig, "Settings"); const QStringList &runtimes = set.readEntry("TryIgnoreRuntimes", QStringList()); bool ignore = runtimes.contains(cmdLine); if (!ignore && slash > 0) { ignore = runtimes.contains(cmdLine.mid(slash + 1)); } if (ignore) { return servicesFromCmdLine(_cmdLine.mid(firstSpace + 1), processName, rulesConfig); } } if (services.isEmpty() && !processName.isEmpty() && !QStandardPaths::findExecutable(cmdLine).isEmpty()) { // cmdLine now exists without arguments if there were any. services << QExplicitlySharedDataPointer(new KService(processName, cmdLine, QString())); } return services; } QString defaultApplication(const QUrl &url) { if (url.scheme() != QLatin1String("preferred")) { return QString(); } const QString &application = url.host(); if (application.isEmpty()) { return QString(); } if (application.compare(QLatin1String("mailer"), Qt::CaseInsensitive) == 0) { KEMailSettings settings; // In KToolInvocation, the default is kmail; but let's be friendlier. QString command = settings.getSetting(KEMailSettings::ClientProgram); if (command.isEmpty()) { if (KService::Ptr kontact = KService::serviceByStorageId(QStringLiteral("kontact"))) { return kontact->storageId(); } else if (KService::Ptr kmail = KService::serviceByStorageId(QStringLiteral("kmail"))) { return kmail->storageId(); } } if (!command.isEmpty()) { if (settings.getSetting(KEMailSettings::ClientTerminal) == QLatin1String("true")) { KConfigGroup confGroup(KSharedConfig::openConfig(), "General"); const QString preferredTerminal = confGroup.readPathEntry("TerminalApplication", QStringLiteral("konsole")); command = preferredTerminal + QLatin1String(" -e ") + command; } return command; } } else if (application.compare(QLatin1String("browser"), Qt::CaseInsensitive) == 0) { KConfigGroup config(KSharedConfig::openConfig(), "General"); QString browserApp = config.readPathEntry("BrowserApplication", QString()); if (browserApp.isEmpty()) { const KService::Ptr htmlApp = KMimeTypeTrader::self()->preferredService(QStringLiteral("text/html")); if (htmlApp) { browserApp = htmlApp->storageId(); } } else if (browserApp.startsWith('!')) { browserApp = browserApp.mid(1); } return browserApp; } else if (application.compare(QLatin1String("terminal"), Qt::CaseInsensitive) == 0) { KConfigGroup confGroup(KSharedConfig::openConfig(), "General"); return confGroup.readPathEntry("TerminalApplication", QStringLiteral("konsole")); } else if (application.compare(QLatin1String("filemanager"), Qt::CaseInsensitive) == 0) { KService::Ptr service = KMimeTypeTrader::self()->preferredService(QStringLiteral("inode/directory")); if (service) { return service->storageId(); } } else if (KService::Ptr service = KMimeTypeTrader::self()->preferredService(application)) { return service->storageId(); } else { // Try the files in share/apps/kcm_componentchooser/*.desktop. QStringList directories = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("kcm_componentchooser"), QStandardPaths::LocateDirectory); QStringList services; foreach(const QString& directory, directories) { QDir dir(directory); foreach(const QString& f, dir.entryList(QStringList("*.desktop"))) services += dir.absoluteFilePath(f); } foreach (const QString & service, services) { KConfig config(service, KConfig::SimpleConfig); KConfigGroup cg = config.group(QByteArray()); const QString type = cg.readEntry("valueName", QString()); if (type.compare(application, Qt::CaseInsensitive) == 0) { KConfig store(cg.readPathEntry("storeInFile", QStringLiteral("null"))); KConfigGroup storeCg(&store, cg.readEntry("valueSection", QString())); const QString exec = storeCg.readPathEntry(cg.readEntry("valueName", "kcm_componenchooser_null"), cg.readEntry("defaultImplementation", QString())); if (!exec.isEmpty()) { return exec; } break; } } } return QString(""); } bool launcherUrlsMatch(const QUrl &a, const QUrl &b, UrlComparisonMode mode) { QUrl sanitizedA = a; QUrl sanitizedB = b; if (mode == IgnoreQueryItems) { sanitizedA = a.adjusted(QUrl::RemoveQuery); sanitizedB = b.adjusted(QUrl::RemoveQuery); } auto tryResolveToApplicationsUrl = [](const QUrl &url) -> QUrl { QUrl resolvedUrl = url; if (url.isLocalFile() && KDesktopFile::isDesktopFile(url.toLocalFile())) { KDesktopFile f(url.toLocalFile()); const KService::Ptr service = KService::serviceByStorageId(f.fileName()); // Resolve to non-absolute menuId-based URL if possible. if (service) { const QString &menuId = service->menuId(); if (!menuId.isEmpty()) { resolvedUrl = QUrl(QStringLiteral("applications:") + menuId); resolvedUrl.setQuery(url.query()); } } } return resolvedUrl; }; sanitizedA = tryResolveToApplicationsUrl(sanitizedA); sanitizedB = tryResolveToApplicationsUrl(sanitizedB); return (sanitizedA == sanitizedB); } bool appsMatch(const QModelIndex &a, const QModelIndex &b) { const QString &aAppId = a.data(AbstractTasksModel::AppId).toString(); const QString &bAppId = b.data(AbstractTasksModel::AppId).toString(); if (!aAppId.isEmpty() && aAppId == bAppId) { return true; } const QUrl &aUrl = a.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); const QUrl &bUrl = b.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); if (aUrl.isValid() && aUrl == bUrl) { return true; } return false; } QRect screenGeometry(const QPoint &pos) { if (pos.isNull()) { return QRect(); } const QList &screens = QGuiApplication::screens(); QRect screenGeometry; int shortestDistance = INT_MAX; for (int i = 0; i < screens.count(); ++i) { const QRect &geometry = screens.at(i)->geometry(); if (geometry.contains(pos)) { return geometry; } int distance = QPoint(geometry.topLeft() - pos).manhattanLength(); distance = qMin(distance, QPoint(geometry.topRight() - pos).manhattanLength()); distance = qMin(distance, QPoint(geometry.bottomRight() - pos).manhattanLength()); distance = qMin(distance, QPoint(geometry.bottomLeft() - pos).manhattanLength()); if (distance < shortestDistance) { shortestDistance = distance; screenGeometry = geometry; } } return screenGeometry; } void runApp(const AppData &appData, const QList &urls) { if (appData.url.isValid()) { quint32 timeStamp = 0; #if HAVE_X11 if (KWindowSystem::isPlatformX11()) { timeStamp = QX11Info::appUserTime(); } #endif KService::Ptr service; // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (appData.url.scheme() == QStringLiteral("applications")) { service = KService::serviceByMenuId(appData.url.path()); } else if (appData.url.scheme() == QLatin1String("preferred")) { const KService::Ptr service = KService::serviceByStorageId(defaultApplication(appData.url)); } else { service = KService::serviceByDesktopPath(appData.url.toLocalFile()); } if (service && service->isApplication()) { KRun::runApplication(*service, urls, nullptr, KRun::RunFlags(), QString(), KStartupInfo::createNewStartupIdForTimestamp(timeStamp)); KActivities::ResourceInstance::notifyAccessed(QUrl(QStringLiteral("applications:") + service->storageId()), QStringLiteral("org.kde.libtaskmanager")); } else { new KRun(appData.url, nullptr, false, KStartupInfo::createNewStartupIdForTimestamp(timeStamp)); if (!appData.id.isEmpty()) { KActivities::ResourceInstance::notifyAccessed(QUrl(QStringLiteral("applications:") + appData.id), QStringLiteral("org.kde.libtaskmanager")); } } } } } diff --git a/libtaskmanager/tasktools.h b/libtaskmanager/tasktools.h index b8b8ec79a..45e8d0c3c 100644 --- a/libtaskmanager/tasktools.h +++ b/libtaskmanager/tasktools.h @@ -1,196 +1,197 @@ /******************************************************************** Copyright 2016 Eike Hein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #ifndef TASKTOOLS_H #define TASKTOOLS_H #include "taskmanager_export.h" #include #include #include #include #include namespace TaskManager { struct AppData { QString id; // Application id (*.desktop sans extension). QString name; // Application name. QString genericName; // Generic application name. QIcon icon; QUrl url; + bool skipTaskbar = false; }; enum UrlComparisonMode { Strict = 0, IgnoreQueryItems }; /** * Fills in and returns an AppData struct based on the given URL. * * If the URL contains iconData in its query string, it is decoded and * set as AppData.icon, taking precedence over normal icon discovery. * * If the URL is using the preferred:// scheme, the URL it resolves to * is set as AppData.url. * * The supplied fallback icon is set as AppData.icon if no other icon * could be found. * * @see defaultApplication * @param url A URL to a .desktop file or executable, or a preferred:// URL. * @param fallbackIcon An icon to use when none could be read from the URL or * otherwise found. * @returns @c AppData filled in based on the given URL. */ TASKMANAGER_EXPORT AppData appDataFromUrl(const QUrl &url, const QIcon &fallbackIcon = QIcon()); /** * Takes several bits of window metadata as input and tries to find * the .desktop file for the application owning this window, or, * failing that, the path to its executable. * * The source for the metadata is generally the window's appId on * Wayland, or the window class part of the WM_CLASS window property * on X Windows. * * TODO: The supplied config object can contain various mapping and * mangling rules that affect the behavior of this function, allowing * to map bits of metadata to different values and other things. This * config file format still needs to be documented fully; in the * meantime the bundled default rules in taskmanagerrulesrc (the * config file opened by various models in this library) can be used * for reference. * * @param appId A string uniquely identifying the application owning * the window, ideally matching a .desktop file name. * @param pid The process id for the process owning the window. * @param rulesConfig A KConfig object parameterizing the matching * behavior. * @param xWindowsWMClassName The instance name part of X Windows' * WM_CLASS window property. * @returns A .desktop file or executable path for the application * owning the window. */ TASKMANAGER_EXPORT QUrl windowUrlFromMetadata(const QString &appId, quint32 pid = 0, KSharedConfig::Ptr config = KSharedConfig::Ptr(), const QString &xWindowsWMClassName = QString()); /** * Returns a list of (usually application) KService instances for the * given process id, by examining the process and querying the service * database for process metadata. * * @param pid A process id. * @param rulesConfig A KConfig object parameterizing the matching * behavior. * @returns A list of KService instances. */ TASKMANAGER_EXPORT KService::List servicesFromPid(quint32 pid, KSharedConfig::Ptr rulesConfig = KSharedConfig::Ptr()); /** * Returns a list of (usually application) KService instances for the * given process command line and process name, by mangling the command * line in various ways and checking the data against the Exec keys in * the service database. Mangling is done e.g. to check for executable * names with and without paths leading to them and to ignore arguments. * if needed. * * The [Settings]TryIgnoreRuntimes key in the supplied config object can * hold a comma-separated list of runtime executables that this code will * try to ignore in the process command line. This is useful in cases where * the command line has the contents of a .desktop Exec key prefixed with * a runtime executable. The code tries to strip the path to the runtime * executable if needed. * * @param cmdLine A process command line. * @param processName The process name. * @param rulesConfig A KConfig object parameterizing the matching * behavior. * @returns A list of KService instances. */ TASKMANAGER_EXPORT KService::List servicesFromCmdLine(const QString &cmdLine, const QString &processName, KSharedConfig::Ptr rulesConfig = KSharedConfig::Ptr()); /** * Returns an application id for an URL using the preferred:// scheme. * * Recognized values for the host component of the URL are: * - "browser" * - "mailer" * - "terminal" * - "windowmanager" * * If the host component matches none of the above, an attempt is made * to match to application links stored in kcm_componentchooser/. * * @param url A URL using the preferred:// scheme. * @returns an application id for the given URL. **/ TASKMANAGER_EXPORT QString defaultApplication(const QUrl &url); /** * Convenience function to compare two launcher URLs either strictly * or ignoring their query strings. * * @see LauncherTasksModel * @param a The first launcher URL. * @param b The second launcher URL. * @param c The comparison mode. Either Strict or IgnoreQueryItems. * @returns @c true if the URLs match. **/ TASKMANAGER_EXPORT bool launcherUrlsMatch(const QUrl &a, const QUrl &b, UrlComparisonMode mode = Strict); /** * Determines whether tasks model entries belong to the same app. * * @param a The first model index. * @param b The second model index. * @returns @c true if the model entries belong to the same app. **/ TASKMANAGER_EXPORT bool appsMatch(const QModelIndex &a, const QModelIndex &b); /** * Given global coordinates, returns the geometry of the screen they are * on, or the geometry of the screen they are closest to. * * @param pos Coordinates in global space. * @return The geometry of the screen containing pos or closest to pos. */ TASKMANAGER_EXPORT QRect screenGeometry(const QPoint &pos); /** * Attempts to run the application described by the AppData struct that * is passed in, optionally also handing the application a list of URLs * to open. * * @param appData An application data struct. * @param urls A list of URLs for the application to open. */ TASKMANAGER_EXPORT void runApp(const AppData &appData, const QList &urls = QList()); } #endif diff --git a/libtaskmanager/waylandtasksmodel.cpp b/libtaskmanager/waylandtasksmodel.cpp index 73c3d6e66..ffc236784 100644 --- a/libtaskmanager/waylandtasksmodel.cpp +++ b/libtaskmanager/waylandtasksmodel.cpp @@ -1,607 +1,608 @@ /******************************************************************** Copyright 2016 Eike Hein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "waylandtasksmodel.h" #include "tasktools.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace TaskManager { class Q_DECL_HIDDEN WaylandTasksModel::Private { public: Private(WaylandTasksModel *q); QList windows; QHash appDataCache; KWayland::Client::PlasmaWindowManagement *windowManagement = nullptr; KSharedConfig::Ptr rulesConfig; KDirWatch *configWatcher = nullptr; void init(); void initWayland(); void addWindow(KWayland::Client::PlasmaWindow *window); AppData appData(KWayland::Client::PlasmaWindow *window); QIcon icon(KWayland::Client::PlasmaWindow *window); void dataChanged(KWayland::Client::PlasmaWindow *window, int role); void dataChanged(KWayland::Client::PlasmaWindow *window, const QVector &roles); private: WaylandTasksModel *q; }; WaylandTasksModel::Private::Private(WaylandTasksModel *q) : q(q) { } void WaylandTasksModel::Private::init() { auto clearCacheAndRefresh = [this] { if (!windows.count()) { return; } appDataCache.clear(); // Emit changes of all roles satisfied from app data cache. q->dataChanged(q->index(0, 0), q->index(windows.count() - 1, 0), QVector{Qt::DecorationRole, AbstractTasksModel::AppId, AbstractTasksModel::AppName, AbstractTasksModel::GenericName, AbstractTasksModel::LauncherUrl, - AbstractTasksModel::LauncherUrlWithoutIcon}); + AbstractTasksModel::LauncherUrlWithoutIcon, + AbstractTasksModel::SkipTaskbar}); }; rulesConfig = KSharedConfig::openConfig(QStringLiteral("taskmanagerrulesrc")); configWatcher = new KDirWatch(q); foreach (const QString &location, QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)) { configWatcher->addFile(location + QLatin1String("/taskmanagerrulesrc")); } auto rulesConfigChange = [this, clearCacheAndRefresh] { rulesConfig->reparseConfiguration(); clearCacheAndRefresh(); }; QObject::connect(configWatcher, &KDirWatch::dirty, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::created, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::deleted, rulesConfigChange); initWayland(); } void WaylandTasksModel::Private::initWayland() { if (!KWindowSystem::isPlatformWayland()) { return; } KWayland::Client::ConnectionThread *connection = KWayland::Client::ConnectionThread::fromApplication(q); if (!connection) { return; } KWayland::Client::Registry *registry = new KWayland::Client::Registry(q); registry->create(connection); QObject::connect(registry, &KWayland::Client::Registry::plasmaWindowManagementAnnounced, [this, registry] (quint32 name, quint32 version) { windowManagement = registry->createPlasmaWindowManagement(name, version, q); QObject::connect(windowManagement, &KWayland::Client::PlasmaWindowManagement::interfaceAboutToBeReleased, q, [this] { q->beginResetModel(); windows.clear(); q->endResetModel(); } ); QObject::connect(windowManagement, &KWayland::Client::PlasmaWindowManagement::windowCreated, q, [this](KWayland::Client::PlasmaWindow *window) { addWindow(window); } ); const auto windows = windowManagement->windows(); for (auto it = windows.constBegin(); it != windows.constEnd(); ++it) { addWindow(*it); } } ); registry->setup(); } void WaylandTasksModel::Private::addWindow(KWayland::Client::PlasmaWindow *window) { if (windows.indexOf(window) != -1) { return; } const int count = windows.count(); q->beginInsertRows(QModelIndex(), count, count); windows.append(window); q->endInsertRows(); auto removeWindow = [window, this] { const int row = windows.indexOf(window); if (row != -1) { q->beginRemoveRows(QModelIndex(), row, row); windows.removeAt(row); appDataCache.remove(window); q->endRemoveRows(); } }; QObject::connect(window, &KWayland::Client::PlasmaWindow::unmapped, q, removeWindow); QObject::connect(window, &QObject::destroyed, q, removeWindow); QObject::connect(window, &KWayland::Client::PlasmaWindow::titleChanged, q, [window, this] { this->dataChanged(window, Qt::DisplayRole); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::iconChanged, q, [window, this] { // The icon in the AppData struct might come from PlasmaWindow if it wasn't // filled in by windowUrlFromMetadata+appDataFromUrl. // TODO: Don't evict the cache unnecessarily if this isn't the case. As icons // are currently very static on Wayland, this eviction is unlikely to happen // frequently as of now. appDataCache.remove(window); this->dataChanged(window, Qt::DecorationRole); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::appIdChanged, q, [window, this] { // The AppData struct in the cache is derived from this and needs // to be evicted in favor of a fresh struct based on the changed // window metadata. appDataCache.remove(window); // Refresh roles satisfied from the app data cache. this->dataChanged(window, QVector{AppId, AppName, GenericName, - LauncherUrl, LauncherUrlWithoutIcon}); + LauncherUrl, LauncherUrlWithoutIcon, SkipTaskbar}); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::activeChanged, q, [window, this] { this->dataChanged(window, IsActive); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::closeableChanged, q, [window, this] { this->dataChanged(window, IsClosable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::movableChanged, q, [window, this] { this->dataChanged(window, IsMovable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::resizableChanged, q, [window, this] { this->dataChanged(window, IsResizable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::fullscreenableChanged, q, [window, this] { this->dataChanged(window, IsFullScreenable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::fullscreenChanged, q, [window, this] { this->dataChanged(window, IsFullScreen); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::maximizeableChanged, q, [window, this] { this->dataChanged(window, IsMaximizable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::maximizedChanged, q, [window, this] { this->dataChanged(window, IsMaximized); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::minimizeableChanged, q, [window, this] { this->dataChanged(window, IsMinimizable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::minimizedChanged, q, [window, this] { this->dataChanged(window, IsMinimized); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::keepAboveChanged, q, [window, this] { this->dataChanged(window, IsKeepAbove); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::keepBelowChanged, q, [window, this] { this->dataChanged(window, IsKeepBelow); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::shadeableChanged, q, [window, this] { this->dataChanged(window, IsShadeable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::virtualDesktopChangeableChanged, q, [window, this] { this->dataChanged(window, IsVirtualDesktopChangeable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::virtualDesktopChanged, q, [window, this] { this->dataChanged(window, VirtualDesktop); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::onAllDesktopsChanged, q, [window, this] { this->dataChanged(window, IsOnAllVirtualDesktops); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::geometryChanged, q, [window, this] { this->dataChanged(window, QVector{Geometry, ScreenGeometry}); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::demandsAttentionChanged, q, [window, this] { this->dataChanged(window, IsDemandingAttention); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::skipTaskbarChanged, q, [window, this] { this->dataChanged(window, SkipTaskbar); } ); } AppData WaylandTasksModel::Private::appData(KWayland::Client::PlasmaWindow *window) { const auto &it = appDataCache.constFind(window); if (it != appDataCache.constEnd()) { return *it; } const AppData &data = appDataFromUrl(windowUrlFromMetadata(window->appId(), window->pid(), rulesConfig)); appDataCache.insert(window, data); return data; } QIcon WaylandTasksModel::Private::icon(KWayland::Client::PlasmaWindow *window) { const AppData &app = appData(window); if (!app.icon.isNull()) { return app.icon; } appDataCache[window].icon = window->icon(); return window->icon(); } void WaylandTasksModel::Private::dataChanged(KWayland::Client::PlasmaWindow *window, int role) { QModelIndex idx = q->index(windows.indexOf(window)); emit q->dataChanged(idx, idx, QVector{role}); } void WaylandTasksModel::Private::dataChanged(KWayland::Client::PlasmaWindow *window, const QVector &roles) { QModelIndex idx = q->index(windows.indexOf(window)); emit q->dataChanged(idx, idx, roles); } WaylandTasksModel::WaylandTasksModel(QObject *parent) : AbstractWindowTasksModel(parent) , d(new Private(this)) { d->init(); } WaylandTasksModel::~WaylandTasksModel() = default; QVariant WaylandTasksModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->windows.count()) { return QVariant(); } KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); if (role == Qt::DisplayRole) { return window->title(); } else if (role == Qt::DecorationRole) { return d->icon(window); } else if (role == AppId) { const QString &id = d->appData(window).id; if (id.isEmpty()) { return window->appId(); } else { return id; } } else if (role == AppName) { return d->appData(window).name; } else if (role == GenericName) { return d->appData(window).genericName; } else if (role == LauncherUrl || role == LauncherUrlWithoutIcon) { return d->appData(window).url; } else if (role == IsWindow) { return true; } else if (role == IsActive) { return window->isActive(); } else if (role == IsClosable) { return window->isCloseable(); } else if (role == IsMovable) { return window->isMovable(); } else if (role == IsResizable) { return window->isResizable(); } else if (role == IsMaximizable) { return window->isMaximizeable(); } else if (role == IsMaximized) { return window->isMaximized(); } else if (role == IsMinimizable) { return window->isMinimizeable(); } else if (role == IsMinimized) { return window->isMinimized(); } else if (role == IsKeepAbove) { return window->isKeepAbove(); } else if (role == IsKeepBelow) { return window->isKeepBelow(); } else if (role == IsFullScreenable) { return window->isFullscreenable(); } else if (role == IsFullScreen) { return window->isFullscreen(); } else if (role == IsShadeable) { return window->isShadeable(); } else if (role == IsShaded) { return window->isShaded(); } else if (role == IsVirtualDesktopChangeable) { return window->isVirtualDesktopChangeable(); } else if (role == VirtualDesktop) { return window->virtualDesktop(); } else if (role == IsOnAllVirtualDesktops) { return window->isOnAllDesktops(); } else if (role == Geometry) { return window->geometry(); } else if (role == ScreenGeometry) { return screenGeometry(window->geometry().center()); } else if (role == Activities) { // FIXME Implement. } else if (role == IsDemandingAttention) { return window->isDemandingAttention(); } else if (role == SkipTaskbar) { - return window->skipTaskbar(); + return window->skipTaskbar() || d->appData(window).skipTaskbar; } else if (role == SkipPager) { // FIXME Implement. } else if (role == AppPid) { return window->pid(); } return QVariant(); } int WaylandTasksModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->windows.count(); } QModelIndex WaylandTasksModel::index(int row, int column, const QModelIndex &parent) const { return hasIndex(row, column, parent) ? createIndex(row, column, d->windows.at(row)) : QModelIndex(); } void WaylandTasksModel::requestActivate(const QModelIndex &index) { // FIXME Lacks transient handling of the XWindows version. if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestActivate(); } void WaylandTasksModel::requestNewInstance(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } runApp(d->appData(d->windows.at(index.row()))); } void WaylandTasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count() || urls.isEmpty()) { return; } runApp(d->appData(d->windows.at(index.row())), urls); } void WaylandTasksModel::requestClose(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestClose(); } void WaylandTasksModel::requestMove(const QModelIndex &index) { // FIXME Move-to-desktop logic from XWindows version. (See also others.) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestMove(); } void WaylandTasksModel::requestResize(const QModelIndex &index) { // FIXME Move-to-desktop logic from XWindows version. (See also others.) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestResize(); } void WaylandTasksModel::requestToggleMinimized(const QModelIndex &index) { // FIXME Move-to-desktop logic from XWindows version. (See also others.) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleMinimized(); } void WaylandTasksModel::requestToggleMaximized(const QModelIndex &index) { // FIXME Move-to-desktop logic from XWindows version. (See also others.) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleMaximized(); } void WaylandTasksModel::requestToggleKeepAbove(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleKeepAbove(); } void WaylandTasksModel::requestToggleKeepBelow(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleKeepBelow(); } void WaylandTasksModel::requestToggleFullScreen(const QModelIndex &index) { Q_UNUSED(index) // FIXME Implement. } void WaylandTasksModel::requestToggleShaded(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleShaded(); } void WaylandTasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) { // FIXME Lacks add-new-desktop code from XWindows version. // FIXME Does this do the set-on-all-desktops stuff from the XWindows version? if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestVirtualDesktop(desktop); } void WaylandTasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { Q_UNUSED(index) Q_UNUSED(activities) } void WaylandTasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { /* FIXME: This introduces the dependency on Qt5::Quick. I might prefer reversing this and publishing the window pointer through the model, then calling PlasmaWindow::setMinimizeGeometry in the applet backend, rather than hand delegate items into the lib, keeping the lib more UI- agnostic. */ Q_UNUSED(geometry) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const QQuickItem *item = qobject_cast(delegate); if (!item || !item->parentItem() || !item->window()) { return; } QWindow *itemWindow = item->window(); if (!itemWindow) { return; } using namespace KWayland::Client; Surface *surface = Surface::fromWindow(itemWindow); if (!surface) { return; } QRect rect(item->x(), item->y(), item->width(), item->height()); rect.moveTopLeft(item->parentItem()->mapToScene(rect.topLeft()).toPoint()); KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); window->setMinimizedGeometry(surface, rect); } } diff --git a/libtaskmanager/xwindowtasksmodel.cpp b/libtaskmanager/xwindowtasksmodel.cpp index f0d6a80f4..853ce8b53 100644 --- a/libtaskmanager/xwindowtasksmodel.cpp +++ b/libtaskmanager/xwindowtasksmodel.cpp @@ -1,1068 +1,1071 @@ /******************************************************************** Copyright 2016 Eike Hein Copyright 2008 Aaron J. Seigo This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "xwindowtasksmodel.h" #include "tasktools.h" #include "xwindowsystemeventbatcher.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace TaskManager { static const NET::Properties windowInfoFlags = NET::WMState | NET::XAWMState | NET::WMDesktop | NET::WMVisibleName | NET::WMGeometry | NET::WMFrameExtents | NET::WMWindowType | NET::WMPid; static const NET::Properties2 windowInfoFlags2 = NET::WM2DesktopFileName | NET::WM2Activities | NET::WM2WindowClass | NET::WM2AllowedActions; class Q_DECL_HIDDEN XWindowTasksModel::Private { public: Private(XWindowTasksModel *q); ~Private(); QVector windows; QSet transients; QMultiHash transientsDemandingAttention; QHash windowInfoCache; QHash appDataCache; QHash delegateGeometries; QSet usingFallbackIcon; WId activeWindow = -1; KSharedConfig::Ptr rulesConfig; KDirWatch *configWatcher = nullptr; QTimer sycocaChangeTimer; void init(); void addWindow(WId window); void removeWindow(WId window); void windowChanged(WId window, NET::Properties properties, NET::Properties2 properties2); void transientChanged(WId window, NET::Properties properties, NET::Properties2 properties2); void dataChanged(WId window, const QVector &roles); KWindowInfo* windowInfo(WId window); AppData appData(WId window); QIcon icon(WId window); static QString mimeType(); static QString groupMimeType(); QUrl windowUrl(WId window); QUrl launcherUrl(WId window, bool encodeFallbackIcon = true); bool demandsAttention(WId window); private: XWindowTasksModel *q; }; XWindowTasksModel::Private::Private(XWindowTasksModel *q) : q(q) { } XWindowTasksModel::Private::~Private() { qDeleteAll(windowInfoCache); windowInfoCache.clear(); } void XWindowTasksModel::Private::init() { auto clearCacheAndRefresh = [this] { if (!windows.count()) { return; } appDataCache.clear(); // Emit changes of all roles satisfied from app data cache. q->dataChanged(q->index(0, 0), q->index(windows.count() - 1, 0), QVector{Qt::DecorationRole, AbstractTasksModel::AppId, AbstractTasksModel::AppName, AbstractTasksModel::GenericName, AbstractTasksModel::LauncherUrl, - AbstractTasksModel::LauncherUrlWithoutIcon}); + AbstractTasksModel::LauncherUrlWithoutIcon, + AbstractTasksModel::SkipTaskbar}); }; sycocaChangeTimer.setSingleShot(true); sycocaChangeTimer.setInterval(100); QObject::connect(&sycocaChangeTimer, &QTimer::timeout, q, clearCacheAndRefresh); void (KSycoca::*myDatabaseChangeSignal)(const QStringList &) = &KSycoca::databaseChanged; QObject::connect(KSycoca::self(), myDatabaseChangeSignal, q, [this](const QStringList &changedResources) { if (changedResources.contains(QLatin1String("services")) || changedResources.contains(QLatin1String("apps")) || changedResources.contains(QLatin1String("xdgdata-apps"))) { sycocaChangeTimer.start(); } } ); rulesConfig = KSharedConfig::openConfig(QStringLiteral("taskmanagerrulesrc")); configWatcher = new KDirWatch(q); foreach (const QString &location, QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)) { configWatcher->addFile(location + QLatin1String("/taskmanagerrulesrc")); } auto rulesConfigChange = [this, clearCacheAndRefresh] { rulesConfig->reparseConfiguration(); clearCacheAndRefresh(); }; QObject::connect(configWatcher, &KDirWatch::dirty, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::created, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::deleted, rulesConfigChange); auto windowSystem = new XWindowSystemEventBatcher(q); QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowAdded, q, [this](WId window) { addWindow(window); } ); QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowRemoved, q, [this](WId window) { removeWindow(window); } ); QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowChanged, q, [this](WId window, NET::Properties properties, NET::Properties2 properties2) { windowChanged(window, properties, properties2); } ); // Update IsActive for previously- and newly-active windows. QObject::connect(KWindowSystem::self(), &KWindowSystem::activeWindowChanged, q, [this](WId window) { const WId oldActiveWindow = activeWindow; activeWindow = window; int row = windows.indexOf(oldActiveWindow); if (row != -1) { dataChanged(oldActiveWindow, QVector{IsActive}); } row = windows.indexOf(window); if (row != -1) { dataChanged(window, QVector{IsActive}); } } ); activeWindow = KWindowSystem::activeWindow(); // Add existing windows. foreach(const WId window, KWindowSystem::windows()) { addWindow(window); } } void XWindowTasksModel::Private::addWindow(WId window) { // Don't add window twice. if (windows.contains(window)) { return; } KWindowInfo info(window, NET::WMWindowType | NET::WMState | NET::WMName | NET::WMVisibleName, NET::WM2TransientFor); NET::WindowType wType = info.windowType(NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask); const WId leader = info.transientFor(); // Handle transient. if (leader > 0 && leader != window && leader != QX11Info::appRootWindow() && !transients.contains(window) && windows.contains(leader)) { transients.insert(window); // Update demands attention state for leader. if (info.hasState(NET::DemandsAttention) && windows.contains(leader)) { transientsDemandingAttention.insertMulti(leader, window); dataChanged(leader, QVector{IsDemandingAttention}); } return; } // Ignore NET::Tool and other special window types; they are not considered tasks. if (wType != NET::Normal && wType != NET::Override && wType != NET::Unknown && wType != NET::Dialog && wType != NET::Utility) { return; } const int count = windows.count(); q->beginInsertRows(QModelIndex(), count, count); windows.append(window); q->endInsertRows(); } void XWindowTasksModel::Private::removeWindow(WId window) { const int row = windows.indexOf(window); if (row != -1) { q->beginRemoveRows(QModelIndex(), row, row); windows.removeAt(row); transientsDemandingAttention.remove(window); windowInfoCache.remove(window); appDataCache.remove(window); usingFallbackIcon.remove(window); delegateGeometries.remove(window); q->endRemoveRows(); } else { // Could be a transient. // Removing a transient might change the demands attention state of the leader. if (transients.remove(window)) { const WId leader = transientsDemandingAttention.key(window, XCB_WINDOW_NONE); if (leader != XCB_WINDOW_NONE) { transientsDemandingAttention.remove(leader, window); dataChanged(leader, QVector{IsDemandingAttention}); } } } if (activeWindow == window) { activeWindow = -1; } } void XWindowTasksModel::Private::transientChanged(WId window, NET::Properties properties, NET::Properties2 properties2) { // Changes to a transient's state might change demands attention state for leader. if (properties & (NET::WMState | NET::XAWMState)) { const KWindowInfo info(window, NET::WMState | NET::XAWMState, NET::WM2TransientFor); const WId leader = info.transientFor(); if (!windows.contains(leader)) { return; } if (info.hasState(NET::DemandsAttention)) { if (!transientsDemandingAttention.values(leader).contains(window)) { transientsDemandingAttention.insertMulti(leader, window); dataChanged(leader, QVector{IsDemandingAttention}); } } else if (transientsDemandingAttention.remove(window)) { dataChanged(leader, QVector{IsDemandingAttention}); } // Leader might have changed. } else if (properties2 & NET::WM2TransientFor) { const KWindowInfo info(window, NET::WMState | NET::XAWMState, NET::WM2TransientFor); if (info.hasState(NET::DemandsAttention)) { const WId oldLeader = transientsDemandingAttention.key(window, XCB_WINDOW_NONE); if (oldLeader != XCB_WINDOW_NONE) { const WId leader = info.transientFor(); if (leader != oldLeader) { transientsDemandingAttention.remove(oldLeader, window); transientsDemandingAttention.insertMulti(leader, window); dataChanged(oldLeader, QVector{IsDemandingAttention}); dataChanged(leader, QVector{IsDemandingAttention}); } } } } } void XWindowTasksModel::Private::windowChanged(WId window, NET::Properties properties, NET::Properties2 properties2) { if (transients.contains(window)) { transientChanged(window, properties, properties2); return; } bool wipeInfoCache = false; bool wipeAppDataCache = false; QVector changedRoles; if (properties & (NET::WMPid) || properties2 & (NET::WM2DesktopFileName | NET::WM2WindowClass)) { wipeInfoCache = true; wipeAppDataCache = true; - changedRoles << Qt::DecorationRole << AppId << AppName << GenericName << LauncherUrl << AppPid; + changedRoles << Qt::DecorationRole << AppId << AppName << GenericName << LauncherUrl << AppPid << SkipTaskbar; } if (properties & (NET::WMName | NET::WMVisibleName)) { changedRoles << Qt::DisplayRole; wipeInfoCache = true; } if ((properties & NET::WMIcon) && usingFallbackIcon.contains(window)) { wipeAppDataCache = true; if (!changedRoles.contains(Qt::DecorationRole)) { changedRoles << Qt::DecorationRole; } } // FIXME TODO: It might be worth keeping track of which windows were demanding // attention (or not) to avoid emitting this role on every state change, as // TaskGroupingProxyModel needs to check for group-ability when a change to it // is announced and the queried state is false. if (properties & (NET::WMState | NET::XAWMState)) { wipeInfoCache = true; changedRoles << IsFullScreen << IsMaximized << IsMinimized << IsKeepAbove << IsKeepBelow; changedRoles << IsShaded << IsDemandingAttention << SkipTaskbar << SkipPager; } if (properties & NET::WMWindowType) { wipeInfoCache = true; changedRoles << SkipTaskbar; } if (properties2 & NET::WM2AllowedActions) { wipeInfoCache = true; changedRoles << IsClosable << IsMovable << IsResizable << IsMaximizable << IsMinimizable; changedRoles << IsFullScreenable << IsShadeable << IsVirtualDesktopChangeable; } if (properties & NET::WMDesktop) { wipeInfoCache = true; changedRoles << VirtualDesktop << IsOnAllVirtualDesktops; } if (properties & NET::WMGeometry) { wipeInfoCache = true; changedRoles << Geometry << ScreenGeometry; } if (properties2 & NET::WM2Activities) { changedRoles << Activities; } if (wipeInfoCache) { delete windowInfoCache.take(window); } if (wipeAppDataCache) { appDataCache.remove(window); usingFallbackIcon.remove(window); } if (!changedRoles.isEmpty()) { dataChanged(window, changedRoles); } } void XWindowTasksModel::Private::dataChanged(WId window, const QVector &roles) { const int i = windows.indexOf(window); if (i == -1) { return; } QModelIndex idx = q->index(i); emit q->dataChanged(idx, idx, roles); } KWindowInfo* XWindowTasksModel::Private::windowInfo(WId window) { const auto &it = windowInfoCache.constFind(window); if (it != windowInfoCache.constEnd()) { return *it; } KWindowInfo *info = new KWindowInfo(window, windowInfoFlags, windowInfoFlags2); windowInfoCache.insert(window, info); return info; } AppData XWindowTasksModel::Private::appData(WId window) { const auto &it = appDataCache.constFind(window); if (it != appDataCache.constEnd()) { return *it; } const AppData &data = appDataFromUrl(windowUrl(window)); // If we weren't able to derive a launcher URL from the window meta data, // fall back to WM_CLASS Class string as app id. This helps with apps we // can't map to an URL due to existing outside the regular system // environment, e.g. wine clients. if (data.id.isEmpty() && data.url.isEmpty()) { AppData dataCopy = data; dataCopy.id = windowInfo(window)->windowClassClass(); appDataCache.insert(window, dataCopy); return dataCopy; } appDataCache.insert(window, data); return data; } QIcon XWindowTasksModel::Private::icon(WId window) { const AppData &app = appData(window); if (!app.icon.isNull()) { return app.icon; } QIcon icon; icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeSmall, KIconLoader::SizeSmall, false)); icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeSmallMedium, KIconLoader::SizeSmallMedium, false)); icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeMedium, KIconLoader::SizeMedium, false)); icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeLarge, KIconLoader::SizeLarge, false)); appDataCache[window].icon = icon; usingFallbackIcon.insert(window); return icon; } QString XWindowTasksModel::Private::mimeType() { return QStringLiteral("windowsystem/winid"); } QString XWindowTasksModel::Private::groupMimeType() { return QStringLiteral("windowsystem/multiple-winids"); } QUrl XWindowTasksModel::Private::windowUrl(WId window) { const KWindowInfo *info = windowInfo(window); QString desktopFile = QString::fromUtf8(info->desktopFileName()); if (!desktopFile.isEmpty()) { KService::Ptr service = KService::serviceByStorageId(desktopFile); if (service) { const QString &menuId = service->menuId(); // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (!menuId.isEmpty()) { return QUrl(QStringLiteral("applications:") + menuId); } return QUrl::fromLocalFile(service->entryPath()); } if (!desktopFile.endsWith(QLatin1String(".desktop"))) { desktopFile.append(QLatin1String(".desktop")); } if (KDesktopFile::isDesktopFile(desktopFile) && QFile::exists(desktopFile)) { return QUrl::fromLocalFile(desktopFile); } } return windowUrlFromMetadata(info->windowClassClass(), NETWinInfo(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMPid, NET::Properties2()).pid(), rulesConfig, info->windowClassName()); } QUrl XWindowTasksModel::Private::launcherUrl(WId window, bool encodeFallbackIcon) { const AppData &data = appData(window); if (!encodeFallbackIcon || !data.icon.name().isEmpty()) { return data.url; } QUrl url = data.url; // Forego adding the window icon pixmap if the URL is otherwise empty. if (!url.isValid()) { return QUrl(); } const QPixmap pixmap = KWindowSystem::icon(window, KIconLoader::SizeLarge, KIconLoader::SizeLarge, false); if (pixmap.isNull()) { return data.url; } QUrlQuery uQuery(url); QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); pixmap.save(&buffer, "PNG"); uQuery.addQueryItem(QStringLiteral("iconData"), bytes.toBase64(QByteArray::Base64UrlEncoding)); url.setQuery(uQuery); return url; } bool XWindowTasksModel::Private::demandsAttention(WId window) { if (windows.contains(window)) { return ((windowInfo(window)->hasState(NET::DemandsAttention)) || transientsDemandingAttention.contains(window)); } return false; } XWindowTasksModel::XWindowTasksModel(QObject *parent) : AbstractWindowTasksModel(parent) , d(new Private(this)) { d->init(); } XWindowTasksModel::~XWindowTasksModel() { } QVariant XWindowTasksModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->windows.count()) { return QVariant(); } const WId window = d->windows.at(index.row()); if (role == Qt::DisplayRole) { return d->windowInfo(window)->visibleName(); } else if (role == Qt::DecorationRole) { return d->icon(window); } else if (role == AppId) { return d->appData(window).id; } else if (role == AppName) { return d->appData(window).name; } else if (role == GenericName) { return d->appData(window).genericName; } else if (role == LauncherUrl) { return d->launcherUrl(window); } else if (role == LauncherUrlWithoutIcon) { return d->launcherUrl(window, false /* encodeFallbackIcon */); } else if (role == LegacyWinIdList) { return QVariantList() << window; } else if (role == MimeType) { return d->mimeType(); } else if (role == MimeData) { return QByteArray((char*)&window, sizeof(window)); } else if (role == IsWindow) { return true; } else if (role == IsActive) { return (window == d->activeWindow); } else if (role == IsClosable) { return d->windowInfo(window)->actionSupported(NET::ActionClose); } else if (role == IsMovable) { return d->windowInfo(window)->actionSupported(NET::ActionMove); } else if (role == IsResizable) { return d->windowInfo(window)->actionSupported(NET::ActionResize); } else if (role == IsMaximizable) { return d->windowInfo(window)->actionSupported(NET::ActionMax); } else if (role == IsMaximized) { const KWindowInfo *info = d->windowInfo(window); return info->hasState(NET::MaxHoriz) && info->hasState(NET::MaxVert); } else if (role == IsMinimizable) { return d->windowInfo(window)->actionSupported(NET::ActionMinimize); } else if (role == IsMinimized) { return d->windowInfo(window)->isMinimized(); } else if (role == IsKeepAbove) { return d->windowInfo(window)->hasState(NET::StaysOnTop); } else if (role == IsKeepBelow) { return d->windowInfo(window)->hasState(NET::KeepBelow); } else if (role == IsFullScreenable) { return d->windowInfo(window)->actionSupported(NET::ActionFullScreen); } else if (role == IsFullScreen) { return d->windowInfo(window)->hasState(NET::FullScreen); } else if (role == IsShadeable) { return d->windowInfo(window)->actionSupported(NET::ActionShade); } else if (role == IsShaded) { return d->windowInfo(window)->hasState(NET::Shaded); } else if (role == IsVirtualDesktopChangeable) { return d->windowInfo(window)->actionSupported(NET::ActionChangeDesktop); } else if (role == VirtualDesktop) { return d->windowInfo(window)->desktop(); } else if (role == IsOnAllVirtualDesktops) { return d->windowInfo(window)->onAllDesktops(); } else if (role == Geometry) { return d->windowInfo(window)->frameGeometry(); } else if (role == ScreenGeometry) { return screenGeometry(d->windowInfo(window)->frameGeometry().center()); } else if (role == Activities) { return d->windowInfo(window)->activities(); } else if (role == IsDemandingAttention) { return d->demandsAttention(window); } else if (role == SkipTaskbar) { const KWindowInfo *info = d->windowInfo(window); // _NET_WM_WINDOW_TYPE_UTILITY type windows should not be on task bars, // but they should be shown on pagers. - return (info->hasState(NET::SkipTaskbar) || info->windowType(NET::UtilityMask) == NET::Utility); + return (info->hasState(NET::SkipTaskbar) + || info->windowType(NET::UtilityMask) == NET::Utility + || d->appData(window).skipTaskbar); } else if (role == SkipPager) { return d->windowInfo(window)->hasState(NET::SkipPager); } else if (role == AppPid) { return d->windowInfo(window)->pid(); } return QVariant(); } int XWindowTasksModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->windows.count(); } void XWindowTasksModel::requestActivate(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } if (index.row() >= 0 && index.row() < d->windows.count()) { WId window = d->windows.at(index.row()); // Pull forward any transient demanding attention. if (d->transientsDemandingAttention.contains(window)) { window = d->transientsDemandingAttention.value(window); // Quote from legacy libtaskmanager: // "this is a work around for (at least?) kwin where a shaded transient will prevent the main // window from being brought forward unless the transient is actually pulled forward, most // easily reproduced by opening a modal file open/save dialog on an app then shading the file // dialog and trying to bring the window forward by clicking on it in a tasks widget // TODO: do we need to check all the transients for shaded?" } else if (!d->transients.isEmpty()) { foreach (const WId transient, d->transients) { KWindowInfo info(transient, NET::WMState, NET::WM2TransientFor); if (info.valid(true) && info.hasState(NET::Shaded) && info.transientFor() == window) { window = transient; break; } } } KWindowSystem::forceActiveWindow(window); } } void XWindowTasksModel::requestNewInstance(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } runApp(d->appData(d->windows.at(index.row()))); } void XWindowTasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count() || urls.isEmpty()) { return; } runApp(d->appData(d->windows.at(index.row())), urls); } void XWindowTasksModel::requestClose(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } NETRootInfo ri(QX11Info::connection(), NET::CloseWindow); ri.closeWindowRequest(d->windows.at(index.row())); } void XWindowTasksModel::requestMove(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); bool onCurrent = info->isOnCurrentDesktop(); if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); KWindowSystem::forceActiveWindow(window); } if (info->isMinimized()) { KWindowSystem::unminimizeWindow(window); } const QRect &geom = info->geometry(); NETRootInfo ri(QX11Info::connection(), NET::WMMoveResize); ri.moveResizeRequest(window, geom.center().x(), geom.center().y(), NET::Move); } void XWindowTasksModel::requestResize(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); bool onCurrent = info->isOnCurrentDesktop(); if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); KWindowSystem::forceActiveWindow(window); } if (info->isMinimized()) { KWindowSystem::unminimizeWindow(window); } const QRect &geom = info->geometry(); NETRootInfo ri(QX11Info::connection(), NET::WMMoveResize); ri.moveResizeRequest(window, geom.bottomRight().x(), geom.bottomRight().y(), NET::BottomRight); } void XWindowTasksModel::requestToggleMinimized(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); if (info->isMinimized()) { bool onCurrent = info->isOnCurrentDesktop(); // FIXME: Move logic up into proxy? (See also others.) if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); } KWindowSystem::unminimizeWindow(window); if (onCurrent) { KWindowSystem::forceActiveWindow(window); } } else { KWindowSystem::minimizeWindow(window); } } void XWindowTasksModel::requestToggleMaximized(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); bool onCurrent = info->isOnCurrentDesktop(); bool restore = (info->hasState(NET::MaxHoriz) && info->hasState(NET::MaxVert)); // FIXME: Move logic up into proxy? (See also others.) if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); } if (info->isMinimized()) { KWindowSystem::unminimizeWindow(window); } NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (restore) { ni.setState(NET::States(), NET::Max); } else { ni.setState(NET::Max, NET::Max); } if (!onCurrent) { KWindowSystem::forceActiveWindow(window); } } void XWindowTasksModel::requestToggleKeepAbove(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::StaysOnTop)) { ni.setState(NET::States(), NET::StaysOnTop); } else { ni.setState(NET::StaysOnTop, NET::StaysOnTop); } } void XWindowTasksModel::requestToggleKeepBelow(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::KeepBelow)) { ni.setState(NET::States(), NET::KeepBelow); } else { ni.setState(NET::KeepBelow, NET::KeepBelow); } } void XWindowTasksModel::requestToggleFullScreen(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::FullScreen)) { ni.setState(NET::States(), NET::FullScreen); } else { ni.setState(NET::FullScreen, NET::FullScreen); } } void XWindowTasksModel::requestToggleShaded(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::Shaded)) { ni.setState(NET::States(), NET::Shaded); } else { ni.setState(NET::Shaded, NET::Shaded); } } void XWindowTasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); if (desktop == 0) { if (info->onAllDesktops()) { KWindowSystem::setOnDesktop(window, KWindowSystem::currentDesktop()); KWindowSystem::forceActiveWindow(window); } else { KWindowSystem::setOnAllDesktops(window, true); } return; // FIXME Move add-new-desktop logic up into proxy. } else if (desktop > KWindowSystem::numberOfDesktops()) { desktop = KWindowSystem::numberOfDesktops() + 1; // FIXME Arbitrary limit of 20 copied from old code. if (desktop > 20) { return; } NETRootInfo ri(QX11Info::connection(), NET::NumberOfDesktops); ri.setNumberOfDesktops(desktop); } KWindowSystem::setOnDesktop(window, desktop); if (desktop == KWindowSystem::currentDesktop()) { KWindowSystem::forceActiveWindow(window); } } void XWindowTasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); KWindowSystem::setOnActivities(window, activities); } void XWindowTasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { Q_UNUSED(delegate) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); if (d->delegateGeometries.contains(window) && d->delegateGeometries.value(window) == geometry) { return; } NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::Properties(), NET::Properties2()); NETRect rect; if (geometry.isValid()) { rect.pos.x = geometry.x(); rect.pos.y = geometry.y(); rect.size.width = geometry.width(); rect.size.height = geometry.height(); d->delegateGeometries.insert(window, geometry); } else { d->delegateGeometries.remove(window); } ni.setIconGeometry(rect); } WId XWindowTasksModel::winIdFromMimeData(const QMimeData *mimeData, bool *ok) { Q_ASSERT(mimeData); if (ok) { *ok = false; } if (!mimeData->hasFormat(Private::mimeType())) { return 0; } QByteArray data(mimeData->data(Private::mimeType())); if (data.size() != sizeof(WId)) { return 0; } WId id; memcpy(&id, data.data(), sizeof(WId)); if (ok) { *ok = true; } return id; } QList XWindowTasksModel::winIdsFromMimeData(const QMimeData *mimeData, bool *ok) { Q_ASSERT(mimeData); QList ids; if (ok) { *ok = false; } if (!mimeData->hasFormat(Private::groupMimeType())) { // Try to extract single window id. bool singularOk; WId id = winIdFromMimeData(mimeData, &singularOk); if (ok) { *ok = singularOk; } if (singularOk) { ids << id; } return ids; } QByteArray data(mimeData->data(Private::groupMimeType())); if ((unsigned int)data.size() < sizeof(int) + sizeof(WId)) { return ids; } int count = 0; memcpy(&count, data.data(), sizeof(int)); if (count < 1 || (unsigned int)data.size() < sizeof(int) + sizeof(WId) * count) { return ids; } WId id; for (int i = 0; i < count; ++i) { memcpy(&id, data.data() + sizeof(int) + sizeof(WId) * i, sizeof(WId)); ids << id; } if (ok) { *ok = true; } return ids; } }