diff --git a/libtaskmanager/abstracttasksmodel.h b/libtaskmanager/abstracttasksmodel.h index 531f12c2..cb6e74f5 100644 --- a/libtaskmanager/abstracttasksmodel.h +++ b/libtaskmanager/abstracttasksmodel.h @@ -1,280 +1,280 @@ /******************************************************************** 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 ABSTRACTTASKSMODEL_H #define ABSTRACTTASKSMODEL_H #include "abstracttasksmodeliface.h" #include #include "taskmanager_export.h" namespace TaskManager { /** * @short An abstract base class for (flat) tasks models. * * This class serves as abstract base class for flat tasks model implementations. * It provides data roles and no-op default implementations of methods in the * AbstractTasksModelIface interface. * * @author Eike Hein **/ class TASKMANAGER_EXPORT AbstractTasksModel : public QAbstractListModel, public AbstractTasksModelIface { Q_OBJECT Q_ENUMS(AdditionalRoles) public: enum AdditionalRoles { AppId = Qt::UserRole + 1, /**< KService storage id (.desktop name sans extension). */ AppName, /**< Application name. */ GenericName, /**< Generic application name. */ LauncherUrl, /**< URL that can be used to launch this application (.desktop or executable). */ LauncherUrlWithoutIcon, /**< Special path to get a launcher URL while skipping fallback icon encoding. Used as speed optimization. */ LegacyWinIdList, /**< X11 window ids. Stopgap until we have something better. */ MimeType, /**< MIME type for this task (window, window group), needed for DND. */ MimeData, /**< Data for MimeType. */ IsWindow, /**< This is a window task. */ IsStartup, /**< This is a startup task. */ IsLauncher, /**< This is a launcher task. */ IsGroupParent, /**< This is a parent item for a group of child tasks. */ IsGroupable, /**< Whether this task is being ignored by grouping or not. */ IsActive, /**< This is the currently active task. */ IsClosable, /**< requestClose (see below) available. */ IsMovable, /**< requestMove (see below) available. */ IsResizable, /**< requestResize (see below) available. */ IsMaximizable, /**< requestToggleMaximize (see below) available. */ IsMaximized, /**< Task (i.e. window) is maximized. */ IsMinimizable, /**< requestToggleMinimize (see below) available. */ IsMinimized, /**< Task (i.e. window) is minimized. */ IsKeepAbove, /**< Task (i.e. window) is keep-above. */ IsKeepBelow, /**< Task (i.e. window) is keep-below. */ IsFullScreenable, /**< requestToggleFullScreen (see below) available. */ IsFullScreen, /**< Task (i.e. window) is fullscreen. */ IsShadeable, /**< requestToggleShade (see below) available. */ IsShaded, /**< Task (i.e. window) is shaded. */ IsVirtualDesktopChangeable, /**< requestVirtualDesktop (see below) available. */ VirtualDesktop, /**< Virtual desktop for the task (i.e. window). */ IsOnAllVirtualDesktops, /**< Task is on all virtual desktops. */ Geometry, /**< The task's geometry (i.e. the window's). */ ScreenGeometry, /**< Screen geometry for the task (i.e. the window's screen). */ Activities, /**< Activities for the task (i.e. window). */ IsDemandingAttention, /**< Task is demanding attention. */ - SkipTaskbar, /**< Task desires not to be shown in a 'task bar' user interface. */ - SkipPager, /**< Task desires not to be shown in a 'pager' user interface. */ + SkipTaskbar, /**< Task should not be shown in a 'task bar' user interface. */ + SkipPager, /**< Task should not to be shown in a 'pager' user interface. */ }; explicit AbstractTasksModel(QObject *parent = nullptr); virtual ~AbstractTasksModel(); QHash roleNames() const override; virtual QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const override; /** * Request activation of the task at the given index. Derived classes are * free to interpret the meaning of "activate" themselves depending on * the nature and state of the task, e.g. launch or raise a window task. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestActivate(const QModelIndex &index) override; /** * Request an additional instance of the application backing the task * at the given index. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestNewInstance(const QModelIndex &index) override; /** * Requests to open the given URLs with the application backing the task * at the given index. * * This base implementation does nothing. * * @param index An index in this tasks model. * @param urls The URLs to be passed to the application. **/ virtual void requestOpenUrls(const QModelIndex &index, const QList &urls); /** * Request the task at the given index be closed. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestClose(const QModelIndex &index) override; /** * Request starting an interactive move for the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestMove(const QModelIndex &index) override; /** * Request starting an interactive resize for the task at the given index. * * This is meant for tasks that have an associated window, and may be a * no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestResize(const QModelIndex &index) override; /** * Request toggling the minimized state of the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestToggleMinimized(const QModelIndex &index) override; /** * Request toggling the maximized state of the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestToggleMaximized(const QModelIndex &index) override; /** * Request toggling the keep-above state of the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestToggleKeepAbove(const QModelIndex &index) override; /** * Request toggling the keep-below state of the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestToggleKeepBelow(const QModelIndex &index) override; /** * Request toggling the fullscreen state of the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestToggleFullScreen(const QModelIndex &index) override; /** * Request toggling the shaded state of the task at the given index. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ virtual void requestToggleShaded(const QModelIndex &index) override; /** * Request moving the task at the given index to the specified virtual * desktop. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. * @param desktop A virtual desktop number. **/ virtual void requestVirtualDesktop(const QModelIndex &index, qint32 desktop) override; /** * Request moving the task at the given index to the specified activities. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * This base implementation does nothing. * * @param index An index in this tasks model. * @param activities The new list of activities. **/ virtual void requestActivities(const QModelIndex &index, const QStringList &activities) override; /** * Request informing the window manager of new geometry for a visual * delegate for the task at the given index. The geometry should be in * screen coordinates. * * This base implementation does nothing. * * @param index An index in this tasks model. * @param geometry Visual delegate geometry in screen coordinates. * @param delegate The delegate. Implementations are on their own with * regard to extracting information from this, and should take care to * reject invalid objects. **/ virtual void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; }; } #endif diff --git a/libtaskmanager/taskfilterproxymodel.cpp b/libtaskmanager/taskfilterproxymodel.cpp index dbf552e5..b2cd2b1d 100644 --- a/libtaskmanager/taskfilterproxymodel.cpp +++ b/libtaskmanager/taskfilterproxymodel.cpp @@ -1,295 +1,313 @@ /******************************************************************** 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 "taskfilterproxymodel.h" #include "abstracttasksmodel.h" namespace TaskManager { class TaskFilterProxyModel::Private { public: Private(TaskFilterProxyModel *q); AbstractTasksModelIface *sourceTasksModel = nullptr; uint virtualDesktop = 0; QRect screenGeometry; QString activity; bool filterByVirtualDesktop = false; bool filterByScreen = false; bool filterByActivity = false; bool filterNotMinimized = false; bool filterSkipTaskbar = true; bool filterSkipPager = false; + bool demandingAttentionSkipsFilters = true; + private: TaskFilterProxyModel *q; }; TaskFilterProxyModel::Private::Private(TaskFilterProxyModel *q) : q(q) { } TaskFilterProxyModel::TaskFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent) , d(new Private(this)) { } TaskFilterProxyModel::~TaskFilterProxyModel() { } void TaskFilterProxyModel::setSourceModel(QAbstractItemModel *sourceModel) { d->sourceTasksModel = dynamic_cast(sourceModel); QSortFilterProxyModel::setSourceModel(sourceModel); } uint TaskFilterProxyModel::virtualDesktop() const { return d->virtualDesktop; } void TaskFilterProxyModel::setVirtualDesktop(uint virtualDesktop) { if (d->virtualDesktop != virtualDesktop) { d->virtualDesktop = virtualDesktop; if (d->filterByVirtualDesktop) { invalidateFilter(); } emit virtualDesktopChanged(); } } QRect TaskFilterProxyModel::screenGeometry() const { return d->screenGeometry; } void TaskFilterProxyModel::setScreenGeometry(const QRect &geometry) { if (d->screenGeometry != geometry) { d->screenGeometry = geometry; if (d->filterByScreen) { invalidateFilter(); } emit screenGeometryChanged(); } } QString TaskFilterProxyModel::activity() const { return d->activity; } void TaskFilterProxyModel::setActivity(const QString &activity) { if (d->activity != activity) { d->activity = activity; if (d->filterByActivity) { invalidateFilter(); } emit activityChanged(); } } bool TaskFilterProxyModel::filterByVirtualDesktop() const { return d->filterByVirtualDesktop; } void TaskFilterProxyModel::setFilterByVirtualDesktop(bool filter) { if (d->filterByVirtualDesktop != filter) { d->filterByVirtualDesktop = filter; invalidateFilter(); emit filterByVirtualDesktopChanged(); } } bool TaskFilterProxyModel::filterByScreen() const { return d->filterByScreen; } void TaskFilterProxyModel::setFilterByScreen(bool filter) { if (d->filterByScreen != filter) { d->filterByScreen = filter; invalidateFilter(); emit filterByScreenChanged(); } } bool TaskFilterProxyModel::filterByActivity() const { return d->filterByActivity; } void TaskFilterProxyModel::setFilterByActivity(bool filter) { if (d->filterByActivity != filter) { d->filterByActivity = filter; invalidateFilter(); emit filterByActivityChanged(); } } bool TaskFilterProxyModel::filterNotMinimized() const { return d->filterNotMinimized; } void TaskFilterProxyModel::setFilterNotMinimized(bool filter) { if (d->filterNotMinimized != filter) { d->filterNotMinimized = filter; invalidateFilter(); emit filterNotMinimizedChanged(); } } bool TaskFilterProxyModel::filterSkipTaskbar() const { return d->filterSkipTaskbar; } void TaskFilterProxyModel::setFilterSkipTaskbar(bool filter) { if (d->filterSkipTaskbar != filter) { d->filterSkipTaskbar = filter; invalidateFilter(); emit filterSkipTaskbarChanged(); } } bool TaskFilterProxyModel::filterSkipPager() const { return d->filterSkipPager; } void TaskFilterProxyModel::setFilterSkipPager(bool filter) { if (d->filterSkipPager != filter) { d->filterSkipPager = filter; invalidateFilter(); emit filterSkipPagerChanged(); } } +bool TaskFilterProxyModel::demandingAttentionSkipsFilters() const +{ + return d->demandingAttentionSkipsFilters; +} + +void TaskFilterProxyModel::setDemandingAttentionSkipsFilters(bool skip) +{ + if (d->demandingAttentionSkipsFilters != skip) { + d->demandingAttentionSkipsFilters = skip; + + invalidateFilter(); + + emit demandingAttentionSkipsFiltersChanged(); + } +} + QModelIndex TaskFilterProxyModel::mapIfaceToSource(const QModelIndex &index) const { return mapToSource(index); } bool TaskFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { Q_UNUSED(sourceParent) const QModelIndex &sourceIdx = sourceModel()->index(sourceRow, 0); // Filter tasks that are not to be shown on the task bar. if (d->filterSkipTaskbar && sourceIdx.data(AbstractTasksModel::SkipTaskbar).toBool()) { return false; } // Filter tasks that are not to be shown on the pager. if (d->filterSkipPager && sourceIdx.data(AbstractTasksModel::SkipPager).toBool()) { return false; } // Filter by virtual desktop. if (d->filterByVirtualDesktop && d->virtualDesktop != 0) { if (!sourceIdx.data(AbstractTasksModel::IsOnAllVirtualDesktops).toBool() - && !sourceIdx.data(AbstractTasksModel::IsDemandingAttention).toBool()) { + && (!d->demandingAttentionSkipsFilters || !sourceIdx.data(AbstractTasksModel::IsDemandingAttention).toBool())) { const QVariant &virtualDesktop = sourceIdx.data(AbstractTasksModel::VirtualDesktop); if (!virtualDesktop.isNull()) { bool ok = false; const uint i = virtualDesktop.toUInt(&ok); if (ok && i != d->virtualDesktop) { return false; } } } } // Filter by screen. if (d->filterByScreen && d->screenGeometry.isValid()) { const QRect &screenGeometry = sourceIdx.data(AbstractTasksModel::ScreenGeometry).toRect(); if (screenGeometry.isValid() && screenGeometry != d->screenGeometry) { return false; } } // Filter by activity. if (d->filterByActivity && !d->activity.isEmpty()) { - if (!sourceIdx.data(AbstractTasksModel::IsDemandingAttention).toBool()) { + if (!d->demandingAttentionSkipsFilters || !sourceIdx.data(AbstractTasksModel::IsDemandingAttention).toBool()) { const QVariant &activities = sourceIdx.data(AbstractTasksModel::Activities); if (!activities.isNull()) { const QStringList l = activities.toStringList(); if (!l.isEmpty() && !l.contains(d->activity)) { return false; } } } } // Filter not minimized. if (d->filterNotMinimized) { bool isMinimized = sourceIdx.data(AbstractTasksModel::IsMinimized).toBool(); if (!isMinimized) { return false; } } return true; } } diff --git a/libtaskmanager/taskfilterproxymodel.h b/libtaskmanager/taskfilterproxymodel.h index 86345795..4fdb80c1 100644 --- a/libtaskmanager/taskfilterproxymodel.h +++ b/libtaskmanager/taskfilterproxymodel.h @@ -1,276 +1,297 @@ /******************************************************************** 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 TASKFILTERPROXYMODEL_H #define TASKFILTERPROXYMODEL_H #include #include #include "abstracttasksproxymodeliface.h" #include "taskmanager_export.h" namespace TaskManager { /** * @short A proxy tasks model filtering its source model by various properties. * * This proxy model class filters its source tasks model by properties such as * virtual desktop or minimixed state. The values to filter for or by are set * as properties on the proxy model instance. * * @author Eike Hein **/ class TASKMANAGER_EXPORT TaskFilterProxyModel : public QSortFilterProxyModel, public AbstractTasksProxyModelIface { Q_OBJECT Q_PROPERTY(int virtualDesktop READ virtualDesktop WRITE setVirtualDesktop NOTIFY virtualDesktopChanged) Q_PROPERTY(QRect screenGeometry READ screenGeometry WRITE setScreenGeometry NOTIFY screenGeometryChanged) Q_PROPERTY(QString activity READ activity WRITE setActivity NOTIFY activityChanged) Q_PROPERTY(bool filterByVirtualDesktop READ filterByVirtualDesktop WRITE setFilterByVirtualDesktop NOTIFY filterByVirtualDesktopChanged) Q_PROPERTY(bool filterByScreen READ filterByScreen WRITE setFilterByScreen NOTIFY filterByScreenChanged) Q_PROPERTY(bool filterByActivity READ filterByActivity WRITE setFilterByActivity NOTIFY filterByActivityChanged) Q_PROPERTY(bool filterNotMinimized READ filterNotMinimized WRITE setFilterNotMinimized NOTIFY filterNotMinimizedChanged) Q_PROPERTY(bool filterSkipTaskbar READ filterSkipTaskbar WRITE setFilterSkipTaskbar NOTIFY filterSkipTaskbarChanged) Q_PROPERTY(bool filterSkipPager READ filterSkipPager WRITE setFilterSkipPager NOTIFY filterSkipPagerChanged) + Q_PROPERTY(bool demandingAttentionSkipsFilters READ demandingAttentionSkipsFilters WRITE setDemandingAttentionSkipsFilters NOTIFY demandingAttentionSkipsFiltersChanged) + public: explicit TaskFilterProxyModel(QObject *parent = 0); virtual ~TaskFilterProxyModel(); void setSourceModel(QAbstractItemModel *sourceModel) override; /** * The number of the virtual desktop used in filtering by virtual * desktop. Usually set to the number of the current virtual desktop. * Defaults to @c 0 (virtual desktop numbers start at 1). * * @see setVirtualDesktop * @returns the number of the virtual desktop used in filtering. **/ uint virtualDesktop() const; /** * Set the number of the virtual desktop to use in filtering by virtual * desktop. * * If set to 0 (virtual desktop numbers start at 1), filtering by virtual * desktop is disabled. * * @see virtualDesktop * @param virtualDesktop A virtual desktop number. **/ void setVirtualDesktop(uint virtualDesktop); /** * The geometry of the screen used in filtering by screen. Defaults * to a null QRect. * * @see setGeometryScreen * @returns the geometry of the screen used in filtering. **/ QRect screenGeometry() const; /** * Set the geometry of the screen to use in filtering by screen. * * If set to an invalid QRect, filtering by screen is disabled. * * @see screenGeometry * @param geometry A screen geometry. **/ void setScreenGeometry(const QRect &geometry); /** * The id of the activity used in filtering by activity. Usually * set to the id of the current activity. Defaults to an empty id. * * @see setActivity * @returns the id of the activity used in filtering. **/ QString activity() const; /** * Set the id of the activity to use in filtering by activity. * * @see activity * @param activity An activity id. **/ void setActivity(const QString &activity); /** * Whether tasks should be filtered by virtual desktop. Defaults to * @c false. * * Filtering by virtual desktop only happens if a virtual desktop * number greater than -1 is set, even if this returns @c true. * * @see setFilterByVirtualDesktop * @see setVirtualDesktop * @returns @c true if tasks should be filtered by virtual desktop. **/ bool filterByVirtualDesktop() const; /** * Set whether tasks should be filtered by virtual desktop. * * Filtering by virtual desktop only happens if a virtual desktop * number is set, even if this is set to @c true. * * @see filterByVirtualDesktop * @see setVirtualDesktop * @param filter Whether tasks should be filtered by virtual desktop. **/ void setFilterByVirtualDesktop(bool filter); /** * Whether tasks should be filtered by screen. Defaults to @c false. * * Filtering by screen only happens if a screen number is set, even * if this returns @c true. * * @see setFilterByScreen * @see setScreen * @returns @c true if tasks should be filtered by screen. **/ bool filterByScreen() const; /** * Set whether tasks should be filtered by screen. * * Filtering by screen only happens if a screen number is set, even * if this is set to @c true. * * @see filterByScreen * @see setScreen * @param filter Whether tasks should be filtered by screen. **/ void setFilterByScreen(bool filter); /** * Whether tasks should be filtered by activity. Defaults to @c false. * * Filtering by activity only happens if an activity id is set, even * if this returns @c true. * * @see setFilterByActivity * @see setActivity * @returns @ctrue if tasks should be filtered by activity. **/ bool filterByActivity() const; /** * Set whether tasks should be filtered by activity. Defaults to * @c false. * * Filtering by virtual desktop only happens if an activity id is set, * even if this is set to @c true. * * @see filterByActivity * @see setActivity * @param filter Whether tasks should be filtered by activity. **/ void setFilterByActivity(bool filter); /** * Whether non-minimized tasks should be filtered. Defaults to * @c false. * * @see setFilterNotMinimized * @returns @c true if non-minimized tasks should be filtered. **/ bool filterNotMinimized() const; /** * Set whether non-minimized tasks should be filtered. * * @see filterNotMinimized * @param filter Whether non-minimized tasks should be filtered. **/ void setFilterNotMinimized(bool filter); /** - * Whether tasks which indicate they want to be omitted from 'task bars' - * should be filtered. Defaults to @c true. + * Whether tasks which should be omitted from 'task bars' should be + * filtered. Defaults to @c true. * * @see setFilterSkipTaskbar - * @returns @c true if tasks which want to skip the 'task bar' should be - * filtered. + * @returns @c true if tasks which should not be on the 'task bar' + * should be filtered. **/ bool filterSkipTaskbar() const; /** - * Set whether tasks which indicate they want to be omitted from 'task bars' - * should be filtered. + * Set whether tasks which should be omitted from 'task bars' should be + * filtered. * * @see filterSkipTaskbar - * @param filter Whether tasks which want to skip the 'task bar' should be - * filtered. + * @param filter Whether tasks whichs should not be on the 'task bar' + * should be filtered. **/ void setFilterSkipTaskbar(bool filter); /** - * Whether tasks which indicate they want to be omitted from 'pagers' - * should be filtered. Defaults to @c true. + * Whether tasks which should be omitted from 'pagers' should be + * filtered. Defaults to @c true. * * @see setFilterSkipPager - * @returns @c true if tasks which want to skip the 'pager' should be - * filtered. + * @returns @c true if tasks which should not be on the 'pager' should + * be filtered. **/ bool filterSkipPager() const; /** - * Set whether tasks which indicate they want to be omitted from 'pagers' - * should be filtered. + * Set whether tasks which should be omitted from 'pagers' should be + * filtered. * * @see filterSkipPager - * @param filter Whether tasks which want to skip the 'pager' should be - * filtered. + * @param filter Whether tasks which should not be on the 'pager' should + * be filtered. **/ void setFilterSkipPager(bool filter); + /** + * Whether tasks which demand attention skip filters by virtual desktop + * or activity. Defaults to @c true. + * + * @see setDemandingAttentionSkipsFilters + * @returns @c true if tasks which demand attention skip filters. + **/ + bool demandingAttentionSkipsFilters() const; + + /** + * Sets whether tasks which demand attention should bypass filters by + * virtual desktop or activity. + * + * @see demandingAttentionSkipsFilters + * @param skip Whether tasks which demand attention should skip filters. + **/ + void setDemandingAttentionSkipsFilters(bool skip); + Q_SIGNALS: void virtualDesktopChanged() const; void screenGeometryChanged() const; void activityChanged() const; void filterByVirtualDesktopChanged() const; void filterByScreenChanged() const; void filterByActivityChanged() const; void filterNotMinimizedChanged() const; void filterSkipTaskbarChanged() const; void filterSkipPagerChanged() const; + void demandingAttentionSkipsFiltersChanged() const; protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; QModelIndex mapIfaceToSource(const QModelIndex &index) const Q_DECL_OVERRIDE; private: class Private; QScopedPointer d; }; } #endif diff --git a/libtaskmanager/taskgroupingproxymodel.cpp b/libtaskmanager/taskgroupingproxymodel.cpp index 26870a0b..85e94e4a 100644 --- a/libtaskmanager/taskgroupingproxymodel.cpp +++ b/libtaskmanager/taskgroupingproxymodel.cpp @@ -1,1220 +1,1229 @@ /******************************************************************** 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 "taskgroupingproxymodel.h" #include "abstracttasksmodel.h" #include "tasktools.h" #include namespace TaskManager { class TaskGroupingProxyModel::Private { public: Private(TaskGroupingProxyModel *q); AbstractTasksModelIface *abstractTasksSourceModel = nullptr; TasksModel::GroupMode groupMode = TasksModel::GroupApplications; bool groupDemandingAttention = false; int windowTasksThreshold = -1; QVector> rowMap; QSet blacklistedAppIds; QSet blacklistedLauncherUrls; bool isGroup(int row); bool any(const QModelIndex &parent, int role); bool all(const QModelIndex &parent, int role); void sourceRowsAboutToBeInserted(const QModelIndex &parent, int first, int last); void sourceRowsInserted(const QModelIndex &parent, int start, int end); void sourceRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last); void sourceRowsRemoved(const QModelIndex &parent, int start, int end); void sourceModelAboutToBeReset(); void sourceModelReset(); void sourceDataChanged(QModelIndex topLeft, QModelIndex bottomRight, const QVector &roles = QVector()); void adjustMap(int anchor, int delta); void rebuildMap(); bool shouldGroupTasks(); void checkGrouping(bool silent = false); bool isBlacklisted(const QModelIndex &sourceIndex); bool tryToGroup(const QModelIndex &sourceIndex, bool silent = false); void formGroupFor(const QModelIndex &index); void breakGroupFor(const QModelIndex &index, bool silent = false); private: TaskGroupingProxyModel *q; }; TaskGroupingProxyModel::Private::Private(TaskGroupingProxyModel *q) : q(q) { } bool TaskGroupingProxyModel::Private::isGroup(int row) { if (row < 0 || row >= rowMap.count()) { return false; } return (rowMap.at(row).count() > 1); } bool TaskGroupingProxyModel::Private::any(const QModelIndex &parent, int role) { bool is = false; for (int i = 0; i < q->rowCount(parent); ++i) { if (parent.child(i, 0).data(role).toBool()) { return true; } } return is; } bool TaskGroupingProxyModel::Private::all(const QModelIndex &parent, int role) { bool is = true; for (int i = 0; i < q->rowCount(parent); ++i) { if (!parent.child(i, 0).data(role).toBool()) { return false; } } return is; } void TaskGroupingProxyModel::Private::sourceRowsAboutToBeInserted(const QModelIndex &parent, int first, int last) { Q_UNUSED(parent) Q_UNUSED(first) Q_UNUSED(last) } void TaskGroupingProxyModel::Private::sourceRowsInserted(const QModelIndex &parent, int start, int end) { // We only support flat source models. if (parent.isValid()) { return; } adjustMap(start, (end - start) + 1); bool shouldGroup = shouldGroupTasks(); // Can be slightly expensive; cache return value. for (int i = start; i <= end; ++i) { if (!shouldGroup || !tryToGroup(q->sourceModel()->index(i, 0))) { q->beginInsertRows(QModelIndex(), rowMap.count(), rowMap.count()); rowMap.append(QVector{i}); q->endInsertRows(); } } checkGrouping(); } void TaskGroupingProxyModel::Private::sourceRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last) { // We only support flat source models. if (parent.isValid()) { return; } for (int i = first; i <= last; ++i) { for (int j = 0; j < rowMap.count(); ++j) { const QVector &sourceRows = rowMap.at(j); const int mapIndex = sourceRows.indexOf(i); if (mapIndex != -1) { // Remove top-level item. if (sourceRows.count() == 1) { q->beginRemoveRows(QModelIndex(), j, j); rowMap.remove(j); // index() encodes parent row numbers in indices returned for group // members. endRemoveRows() is not aware of this scheme, and so won't // update any persistent indices with new row values. We're now going // to do it ourselves. foreach (const QModelIndex &idx, q->persistentIndexList()) { // internalId() for group members is parent row + 1, so the first // id after j is (j + 2). if (idx.internalId() > ((uint)j + 1)) { q->changePersistentIndex(idx, q->createIndex(idx.row(), 0, idx.internalId() - 1)); } } q->endRemoveRows(); // Dissolve group. } else if (sourceRows.count() == 2) { const QModelIndex parent = q->index(j, 0); q->beginRemoveRows(parent, 0, 1); rowMap[j].remove(mapIndex); // index() encodes parent row numbers in indices returned for group // members. endRemoveRows() is not aware of this scheme, and so won't // invalidate persistent indices for the members of the group we're // dissolving. We're now going to do it ourselves. foreach (const QModelIndex &idx, q->persistentIndexList()) { if (idx.internalId() == ((uint)j + 1)) { q->changePersistentIndex(idx, QModelIndex()); } } q->endRemoveRows(); // We're no longer a group parent. q->dataChanged(parent, parent); // Remove group member. } else { const QModelIndex parent = q->index(j, 0); q->beginRemoveRows(parent, mapIndex, mapIndex); rowMap[j].remove(mapIndex); q->endRemoveRows(); // Various roles of the parent evaluate child data, and the // child list has changed. q->dataChanged(parent, parent); } break; } } } } void TaskGroupingProxyModel::Private::sourceRowsRemoved(const QModelIndex &parent, int start, int end) { // We only support flat source models. if (parent.isValid()) { return; } adjustMap(start + 1, -((end - start) + 1)); checkGrouping(); } void TaskGroupingProxyModel::Private::sourceModelAboutToBeReset() { q->beginResetModel(); } void TaskGroupingProxyModel::Private::sourceModelReset() { rebuildMap(); q->endResetModel(); } void TaskGroupingProxyModel::Private::sourceDataChanged(QModelIndex topLeft, QModelIndex bottomRight, const QVector &roles) { for (int i = topLeft.row(); i <= bottomRight.row(); ++i) { const QModelIndex &sourceIndex = q->sourceModel()->index(i, 0); QModelIndex proxyIndex = q->mapFromSource(sourceIndex); if (!proxyIndex.isValid()) { return; } const QModelIndex parent = proxyIndex.parent(); // If a child item changes, its parent may need an update as well as many of // the data roles evaluate child data. See data(). // TODO: Some roles do not need to bubble up as they fall through to the first // child in data(); it _might_ be worth adding constraints here later. if (parent.isValid()) { q->dataChanged(parent, parent, roles); } // When Private::groupDemandingAttention is false, tryToGroup() exempts tasks // which demand attention from being grouped. Therefore if this task is no longer // demanding attention, we need to try grouping it now. if (!parent.isValid() && !groupDemandingAttention && roles.contains(AbstractTasksModel::IsDemandingAttention) && !sourceIndex.data(AbstractTasksModel::IsDemandingAttention).toBool()) { if (shouldGroupTasks() && tryToGroup(sourceIndex)) { q->beginRemoveRows(QModelIndex(), proxyIndex.row(), proxyIndex.row()); rowMap.remove(proxyIndex.row()); q->endRemoveRows(); } else { q->dataChanged(proxyIndex, proxyIndex, roles); } } else { q->dataChanged(proxyIndex, proxyIndex, roles); } } } void TaskGroupingProxyModel::Private::adjustMap(int anchor, int delta) { for (int i = 0; i < rowMap.count(); ++i) { bool changed = false; QVector sourceRows = rowMap.at(i); QMutableVectorIterator it(sourceRows); while (it.hasNext()) { it.next(); if (it.value() >= anchor) { it.setValue(it.value() + delta); changed = true; } } if (changed) { rowMap.replace(i, sourceRows); } } } void TaskGroupingProxyModel::Private::rebuildMap() { rowMap.clear(); const int rows = q->sourceModel()->rowCount(); rowMap.reserve(rows); for (int i = 0; i < rows; ++i) { rowMap.append(QVector{i}); } checkGrouping(true /* silent */); } bool TaskGroupingProxyModel::Private::shouldGroupTasks() { if (groupMode == TasksModel::GroupDisabled) { return false; } if (windowTasksThreshold != -1) { // We're going to check the number of window tasks in the source model // against the grouping threshold. In practice that means we're ignoring // launcher and startup tasks. Startup tasks because they're very short- // lived (i.e. forming/breaking groups as they come and go would be very // noisy) and launcher tasks because we expect consumers to budget for // them in the threshold they set. int windowTasksCount = 0; for (int i = 0; i < q->sourceModel()->rowCount(); ++i) { const QModelIndex &idx = q->sourceModel()->index(i, 0); if (idx.data(AbstractTasksModel::IsWindow).toBool()) { ++windowTasksCount; } } return (windowTasksCount > windowTasksThreshold); } return true; } void TaskGroupingProxyModel::Private::checkGrouping(bool silent) { if (shouldGroupTasks()) { for (int i = (rowMap.count()) - 1; i >= 0; --i) { if (isGroup(i)) { continue; } if (tryToGroup(q->sourceModel()->index(rowMap.at(i).constFirst(), 0), silent)) { q->beginRemoveRows(QModelIndex(), i, i); rowMap.remove(i); // Safe since we're iterating backwards. q->endRemoveRows(); } } } else { for (int i = (rowMap.count()) - 1; i >= 0; --i) { breakGroupFor(q->index(i, 0), silent); } } } bool TaskGroupingProxyModel::Private::isBlacklisted(const QModelIndex &sourceIndex) { // Check app id against blacklist. if (blacklistedAppIds.count() && blacklistedAppIds.contains(sourceIndex.data(AbstractTasksModel::AppId).toString())) { return true; } // Check launcher URL (sans query items) against blacklist. if (blacklistedLauncherUrls.count()) { const QUrl &launcherUrl = sourceIndex.data(AbstractTasksModel::LauncherUrl).toUrl(); const QString &launcherUrlString = launcherUrl.toString(QUrl::PrettyDecoded | QUrl::RemoveQuery); if (blacklistedLauncherUrls.contains(launcherUrlString)) { return true; } } return false; } bool TaskGroupingProxyModel::Private::tryToGroup(const QModelIndex &sourceIndex, bool silent) { // NOTE: We only group window tasks at this time. If this ever changes, the // implementation of data() will have to be adjusted significantly, as for // many roles it currently falls through to the first child item when dealing // with requests for the parent (e.g. IsWindow). if (!sourceIndex.data(AbstractTasksModel::IsWindow).toBool()) { return false; } // If Private::groupDemandingAttention is false and this task is demanding // attention, don't group it at this time. We'll instead try to group it once // it no longer demands attention (see sourceDataChanged()). if (!groupDemandingAttention && sourceIndex.data(AbstractTasksModel::IsDemandingAttention).toBool()) { return false; } // Blacklist checks. if (isBlacklisted(sourceIndex)) { return false; } // Meat of the matter: Try to add this source row to a sub-list with source rows // associated with the same application. for (int i = 0; i < rowMap.count(); ++i) { const QModelIndex &groupRep = q->sourceModel()->index(rowMap.at(i).constFirst(), 0); // Don't match a row with itself. if (sourceIndex == groupRep) { continue; } // Don't group windows with anything other than windows. if (!groupRep.data(AbstractTasksModel::IsWindow).toBool()) { continue; } if (appsMatch(sourceIndex, groupRep)) { const QModelIndex parent = q->index(i, 0); bool groupFormed = false; if (!silent) { const int newIndex = rowMap.at(i).count(); if (newIndex == 1) { groupFormed = true; q->beginInsertRows(parent, 0, 1); } else { q->beginInsertRows(parent, newIndex, newIndex); } } rowMap[i].append(sourceIndex.row()); if (!silent) { q->endInsertRows(); // If we turned a top-level item into a group parent, we need // to let consumers know. // TODO: It _might_ be worth optimizing this at some point by // adding a roles constaint (e.g. IsGroupParent, MimeType, ...); // see data(). if (groupFormed) { q->dataChanged(parent, parent); } } return true; } } return false; } void TaskGroupingProxyModel::Private::formGroupFor(const QModelIndex &index) { // Already in group or a group. if (index.parent().isValid() || isGroup(index.row())) { return; } // We need to grab a source index as we may invalidate the index passed // in through grouping. const QModelIndex &sourceTarget = q->mapToSource(index); for (int i = (rowMap.count() - 1); i >= 0; --i) { const QModelIndex &sourceIndex = q->sourceModel()->index(rowMap.at(i).constFirst(), 0); if (!appsMatch(sourceTarget, sourceIndex)) { continue; } if (tryToGroup(sourceIndex)) { q->beginRemoveRows(QModelIndex(), i, i); rowMap.remove(i); // Safe since we're iterating backwards. q->endRemoveRows(); } } } void TaskGroupingProxyModel::Private::breakGroupFor(const QModelIndex &index, bool silent) { const int row = index.row(); if (!isGroup(row)) { return; } // The first child will move up to the top level. QVector extraChildren = rowMap.at(row).mid(1); // NOTE: We're going to do remove+insert transactions instead of a // single reparenting move transaction to save on complexity in the // proxies above us. // TODO: This could technically be optimized, though it's very // unlikely to be ever worth it. if (!silent) { q->beginRemoveRows(index, 0, extraChildren.count()); } rowMap[row].resize(1); // index() encodes parent row numbers in indices returned for group // members. endRemoveRows() is not aware of this scheme, and so won't // invalidate persistent indices for the members of the group we're // dissolving. We're now going to do it ourselves. foreach (const QModelIndex &idx, q->persistentIndexList()) { if (idx.internalId() == ((uint)row + 1)) { q->changePersistentIndex(idx, QModelIndex()); } } if (!silent) { q->endRemoveRows(); // We're no longer a group parent. q->dataChanged(index, index); q->beginInsertRows(QModelIndex(), rowMap.count(), rowMap.count() + (extraChildren.count() - 1)); } for (int i = 0; i < extraChildren.count(); ++i) { rowMap.append(QVector{extraChildren.at(i)}); } if (!silent) { q->endInsertRows(); } } TaskGroupingProxyModel::TaskGroupingProxyModel(QObject *parent) : QAbstractProxyModel(parent) , d(new Private(this)) { } TaskGroupingProxyModel::~TaskGroupingProxyModel() { } QModelIndex TaskGroupingProxyModel::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column != 0) { return QModelIndex(); } if (parent.isValid() && row < d->rowMap.at(parent.row()).count()) { return createIndex(row, column, parent.row() + 1); } if (row < d->rowMap.count()) { return createIndex(row, column, (quintptr)0); } return QModelIndex(); } QModelIndex TaskGroupingProxyModel::parent(const QModelIndex &child) const { return (child.internalId() == 0) ? QModelIndex() : index(child.internalId() - 1, 0); } QModelIndex TaskGroupingProxyModel::mapFromSource(const QModelIndex &sourceIndex) const { if (!sourceIndex.isValid() || sourceIndex.model() != sourceModel()) { return QModelIndex(); } for (int i = 0; i < d->rowMap.count(); ++i) { const QVector &sourceRows = d->rowMap.at(i); const int childIndex = sourceRows.indexOf(sourceIndex.row()); const QModelIndex parent = index(i, 0); if (childIndex == 0) { // If the sub-list we found the source row in is larger than 1 (i.e. part // of a group, map to the logical child item instead of the parent item // the source row also stands in for. The parent is therefore unreachable // from mapToSource(). if (d->isGroup(i)) { return index(0, 0, parent); // Otherwise map to the top-level item. } else { return parent; } } else if (childIndex != -1) { return index(childIndex, 0, parent); } } return QModelIndex(); } QModelIndex TaskGroupingProxyModel::mapToSource(const QModelIndex &proxyIndex) const { if (!proxyIndex.isValid() || proxyIndex.model() != this || !sourceModel()) { return QModelIndex(); } const QModelIndex &parent = proxyIndex.parent(); if (parent.isValid()) { if (parent.row() < 0 || parent.row() >= d->rowMap.count()) { return QModelIndex(); } return sourceModel()->index(d->rowMap.at(parent.row()).at(proxyIndex.row()), 0); } else { // Group parents items therefore equate to the first child item; the source // row logically appears twice in the proxy. // mapFromSource() is not required to handle this well (consider proxies can // filter out rows, too) and opts to map to the child item, as the group parent // has its Qt::DisplayRole mangled by data(), and it's more useful for trans- // lating dataChanged() from the source model. return sourceModel()->index(d->rowMap.at(proxyIndex.row()).at(0), 0); } return QModelIndex(); } int TaskGroupingProxyModel::rowCount(const QModelIndex &parent) const { if (!sourceModel()) { return 0; } if (parent.isValid() && parent.model() == this) { // Don't return row count for top-level item at child row: Group members // never have further children of their own. if (parent.parent().isValid()) { return 0; } if (parent.row() < 0 || parent.row() >= d->rowMap.count()) { return 0; } const uint rowCount = d->rowMap.at(parent.row()).count(); // If this sub-list in the map only has one entry, it's a plain item, not // parent to a group. if (rowCount == 1) { return 0; } else { return rowCount; } } return d->rowMap.count(); } bool TaskGroupingProxyModel::hasChildren(const QModelIndex &parent) const { if ((parent.model() && parent.model() != this) || !sourceModel()) { return false; } return rowCount(parent); } int TaskGroupingProxyModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 1; } QVariant TaskGroupingProxyModel::data(const QModelIndex &proxyIndex, int role) const { if (!proxyIndex.isValid() || proxyIndex.model() != this || !sourceModel()) { return QVariant(); } const QModelIndex &parent = proxyIndex.parent(); const bool isGroup = (!parent.isValid() && d->isGroup(proxyIndex.row())); // For group parent items, this will map to the first child task. const QModelIndex &sourceIndex = mapToSource(proxyIndex); if (!sourceIndex.isValid()) { return QVariant(); } if (role == AbstractTasksModel::IsGroupable) { return !d->isBlacklisted(sourceIndex); } if (isGroup) { // For group parent items, DisplayRole is mapped to AppName of the first child. if (role == Qt::DisplayRole) { - return sourceIndex.data(AbstractTasksModel::AppName); + const QString &appName = sourceIndex.data(AbstractTasksModel::AppName).toString(); + + // Groups are formed by app id or launcher URL; neither requires + // AppName to be available. If it's not, fall back to the app id + /// rather than an empty string. + if (appName.isEmpty()) { + return sourceIndex.data(AbstractTasksModel::AppId); + } + + return appName; } else if (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; } else if (role == AbstractTasksModel::MimeType) { // FIXME: Legacy X11 stuff, but it's what we have for now. return QStringLiteral("windowsystem/multiple-winids"); } else if (role == AbstractTasksModel::MimeData) { // FIXME TODO: Implement. return QVariant(); } else if (role == AbstractTasksModel::IsGroupParent) { return true; } else if (role == AbstractTasksModel::IsActive) { return d->any(proxyIndex, AbstractTasksModel::IsActive); } else if (role == AbstractTasksModel::IsClosable) { return d->all(proxyIndex, AbstractTasksModel::IsClosable); } else if (role == AbstractTasksModel::IsMovable) { // Moving groups makes no sense. return false; } else if (role == AbstractTasksModel::IsResizable) { // Resizing groups makes no sense. return false; } else if (role == AbstractTasksModel::IsMaximizable) { return d->all(proxyIndex, AbstractTasksModel::IsMaximizable); } else if (role == AbstractTasksModel::IsMaximized) { return d->all(proxyIndex, AbstractTasksModel::IsMaximized); } else if (role == AbstractTasksModel::IsMinimizable) { return d->all(proxyIndex, AbstractTasksModel::IsMinimizable); } else if (role == AbstractTasksModel::IsMinimized) { return d->all(proxyIndex, AbstractTasksModel::IsMinimized); } else if (role == AbstractTasksModel::IsKeepAbove) { return d->all(proxyIndex, AbstractTasksModel::IsKeepAbove); } else if (role == AbstractTasksModel::IsKeepBelow) { return d->all(proxyIndex, AbstractTasksModel::IsKeepBelow); } else if (role == AbstractTasksModel::IsFullScreenable) { return d->all(proxyIndex, AbstractTasksModel::IsFullScreenable); } else if (role == AbstractTasksModel::IsFullScreen) { return d->all(proxyIndex, AbstractTasksModel::IsFullScreen); } else if (role == AbstractTasksModel::IsShadeable) { return d->all(proxyIndex, AbstractTasksModel::IsShadeable); } else if (role == AbstractTasksModel::IsShaded) { return d->all(proxyIndex, AbstractTasksModel::IsShaded); } else if (role == AbstractTasksModel::IsVirtualDesktopChangeable) { return d->all(proxyIndex, AbstractTasksModel::IsVirtualDesktopChangeable); } else if (role == AbstractTasksModel::VirtualDesktop) { // TODO: Nothing needs this for now and it would add complexity to // make it a list; skip it until needed. return QVariant(); } else if (role == AbstractTasksModel::ScreenGeometry) { // TODO: Nothing needs this for now and it would add complexity to // make it a list; skip it until needed. return QVariant(); } else if (role == AbstractTasksModel::Activities) { QStringList activities; for (int i = 0; i < rowCount(proxyIndex); ++i) { activities.append(proxyIndex.child(i, 0).data(AbstractTasksModel::Activities).toStringList()); } activities.removeDuplicates(); return activities; } else if (role == AbstractTasksModel::IsDemandingAttention) { return d->any(proxyIndex, AbstractTasksModel::IsDemandingAttention); } else if (role == AbstractTasksModel::SkipTaskbar) { return d->all(proxyIndex, AbstractTasksModel::SkipTaskbar); } } return sourceIndex.data(role); } void TaskGroupingProxyModel::setSourceModel(QAbstractItemModel *sourceModel) { if (sourceModel == QAbstractProxyModel::sourceModel()) { return; } beginResetModel(); if (QAbstractProxyModel::sourceModel()) { QAbstractProxyModel::sourceModel()->disconnect(this); } QAbstractProxyModel::setSourceModel(sourceModel); d->abstractTasksSourceModel = dynamic_cast(sourceModel); if (sourceModel) { d->rebuildMap(); connect(sourceModel, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int)), Qt::UniqueConnection); connect(sourceModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceRowsInserted(QModelIndex,int,int)), Qt::UniqueConnection); connect(sourceModel, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int)), Qt::UniqueConnection); connect(sourceModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceRowsRemoved(QModelIndex,int,int)), Qt::UniqueConnection); connect(sourceModel, SIGNAL(modelAboutToBeReset()), this, SLOT(sourceModelAboutToBeReset()), Qt::UniqueConnection); connect(sourceModel, SIGNAL(modelReset()), this, SLOT(sourceModelReset()), Qt::UniqueConnection); connect(sourceModel, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector)), this, SLOT(sourceDataChanged(QModelIndex,QModelIndex,QVector)), Qt::UniqueConnection); } else { d->rowMap.clear(); } endResetModel(); } TasksModel::GroupMode TaskGroupingProxyModel::groupMode() const { return d->groupMode; } void TaskGroupingProxyModel::setGroupMode(TasksModel::GroupMode mode) { if (d->groupMode != mode) { d->groupMode = mode; d->checkGrouping(); emit groupModeChanged(); } } bool TaskGroupingProxyModel::groupDemandingAttention() const { return d->groupDemandingAttention; } void TaskGroupingProxyModel::setGroupDemandingAttention(bool group) { if (d->groupDemandingAttention != group) { d->groupDemandingAttention = group; d->checkGrouping(); emit groupDemandingAttentionChanged(); } } int TaskGroupingProxyModel::windowTasksThreshold() const { return d->windowTasksThreshold; } void TaskGroupingProxyModel::setWindowTasksThreshold(int threshold) { if (d->windowTasksThreshold != threshold) { d->windowTasksThreshold = threshold; d->checkGrouping(); emit windowTasksThresholdChanged(); } } QStringList TaskGroupingProxyModel::blacklistedAppIds() const { return d->blacklistedAppIds.toList(); } void TaskGroupingProxyModel::setBlacklistedAppIds(const QStringList &list) { const QSet &set = QSet::fromList(list); if (d->blacklistedAppIds != set) { d->blacklistedAppIds = set; // checkGrouping() will gather and group up what's newly-allowed under the changed // blacklist. d->checkGrouping(); // Now break apart what we need to. for (int i = (d->rowMap.count() - 1); i >= 0; --i) { if (d->isGroup(i)) { const QModelIndex &groupRep = index(i, 0); if (set.contains(groupRep.data(AbstractTasksModel::AppId).toString())) { d->breakGroupFor(groupRep); // Safe since we're iterating backwards. } } } emit blacklistedAppIdsChanged(); } } QStringList TaskGroupingProxyModel::blacklistedLauncherUrls() const { return d->blacklistedLauncherUrls.toList(); } void TaskGroupingProxyModel::setBlacklistedLauncherUrls(const QStringList &list) { const QSet &set = QSet::fromList(list); if (d->blacklistedLauncherUrls != set) { d->blacklistedLauncherUrls = set; // checkGrouping() will gather and group up what's newly-allowed under the changed // blacklist. d->checkGrouping(); // Now break apart what we need to. for (int i = (d->rowMap.count() - 1); i >= 0; --i) { if (d->isGroup(i)) { const QModelIndex &groupRep = index(i, 0); const QUrl &launcherUrl = groupRep.data(AbstractTasksModel::LauncherUrl).toUrl(); const QString &launcherUrlString = launcherUrl.toString(QUrl::RemoveQuery | QUrl::RemoveQuery); if (set.contains(launcherUrlString)) { d->breakGroupFor(groupRep); // Safe since we're iterating backwards. } } } emit blacklistedLauncherUrlsChanged(); } } void TaskGroupingProxyModel::requestActivate(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestActivate(mapToSource(index)); } } void TaskGroupingProxyModel::requestNewInstance(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } d->abstractTasksSourceModel->requestNewInstance(mapToSource(index)); } void TaskGroupingProxyModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } d->abstractTasksSourceModel->requestOpenUrls(mapToSource(index), urls); } void TaskGroupingProxyModel::requestClose(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestClose(mapToSource(index)); } else { const int row = index.row(); for (int i = (rowCount(index) - 1); i >= 1; --i) { const QModelIndex &sourceChild = mapToSource(index.child(i, 0)); d->abstractTasksSourceModel->requestClose(sourceChild); } d->abstractTasksSourceModel->requestClose(mapToSource(TaskGroupingProxyModel::index(row, 0))); } } void TaskGroupingProxyModel::requestMove(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestMove(mapToSource(index)); } } void TaskGroupingProxyModel::requestResize(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestResize(mapToSource(index)); } } void TaskGroupingProxyModel::requestToggleMinimized(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestToggleMinimized(mapToSource(index)); } else { const bool goalState = !index.data(AbstractTasksModel::IsMinimized).toBool(); for (int i = 0; i < rowCount(index); ++i) { const QModelIndex &child = index.child(i, 0); if (child.data(AbstractTasksModel::IsMinimized).toBool() != goalState) { d->abstractTasksSourceModel->requestToggleMinimized(mapToSource(child)); } } } } void TaskGroupingProxyModel::requestToggleMaximized(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestToggleMaximized(mapToSource(index)); } else { const bool goalState = !index.data(AbstractTasksModel::IsMaximized).toBool(); for (int i = 0; i < rowCount(index); ++i) { const QModelIndex &child = index.child(i, 0); if (child.data(AbstractTasksModel::IsMaximized).toBool() != goalState) { d->abstractTasksSourceModel->requestToggleMaximized(mapToSource(child)); } } } } void TaskGroupingProxyModel::requestToggleKeepAbove(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestToggleKeepAbove(mapToSource(index)); } else { const bool goalState = !index.data(AbstractTasksModel::IsKeepAbove).toBool(); for (int i = 0; i < rowCount(index); ++i) { const QModelIndex &child = index.child(i, 0); if (child.data(AbstractTasksModel::IsKeepAbove).toBool() != goalState) { d->abstractTasksSourceModel->requestToggleKeepAbove(mapToSource(child)); } } } } void TaskGroupingProxyModel::requestToggleKeepBelow(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestToggleKeepBelow(mapToSource(index)); } else { const bool goalState = !index.data(AbstractTasksModel::IsKeepBelow).toBool(); for (int i = 0; i < rowCount(index); ++i) { const QModelIndex &child = index.child(i, 0); if (child.data(AbstractTasksModel::IsKeepBelow).toBool() != goalState) { d->abstractTasksSourceModel->requestToggleKeepBelow(mapToSource(child)); } } } } void TaskGroupingProxyModel::requestToggleFullScreen(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestToggleFullScreen(mapToSource(index)); } else { const bool goalState = !index.data(AbstractTasksModel::IsFullScreen).toBool(); for (int i = 0; i < rowCount(index); ++i) { const QModelIndex &child = index.child(i, 0); if (child.data(AbstractTasksModel::IsFullScreen).toBool() != goalState) { d->abstractTasksSourceModel->requestToggleFullScreen(mapToSource(child)); } } } } void TaskGroupingProxyModel::requestToggleShaded(const QModelIndex &index) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestToggleShaded(mapToSource(index)); } else { const bool goalState = !index.data(AbstractTasksModel::IsShaded).toBool(); for (int i = 0; i < rowCount(index); ++i) { const QModelIndex &child = index.child(i, 0); if (child.data(AbstractTasksModel::IsShaded).toBool() != goalState) { d->abstractTasksSourceModel->requestToggleShaded(mapToSource(child)); } } } } void TaskGroupingProxyModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestVirtualDesktop(mapToSource(index), desktop); } else { const int row = index.row(); for (int i = (rowCount(index) - 1); i >= 1; --i) { const QModelIndex &sourceChild = mapToSource(index.child(i, 0)); d->abstractTasksSourceModel->requestVirtualDesktop(sourceChild, desktop); } d->abstractTasksSourceModel->requestVirtualDesktop(mapToSource(TaskGroupingProxyModel::index(row, 0)), desktop); } } void TaskGroupingProxyModel::requestActivities(const QModelIndex &index, const QStringList &activities) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestActivities(mapToSource(index), activities); } else { const int row = index.row(); for (int i = (rowCount(index) - 1); i >= 1; --i) { const QModelIndex &sourceChild = mapToSource(index.child(i, 0)); d->abstractTasksSourceModel->requestActivities(sourceChild, activities); } d->abstractTasksSourceModel->requestActivities(mapToSource(TaskGroupingProxyModel::index(row, 0)), activities); } } void TaskGroupingProxyModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { d->abstractTasksSourceModel->requestPublishDelegateGeometry(mapToSource(index), geometry, delegate); } else { for (int i = 0; i < rowCount(index); ++i) { d->abstractTasksSourceModel->requestPublishDelegateGeometry(mapToSource(index.child(i, 0)), geometry, delegate); } } } void TaskGroupingProxyModel::requestToggleGrouping(const QModelIndex &index) { const QString &appId = index.data(AbstractTasksModel::AppId).toString(); const QUrl &launcherUrl = index.data(AbstractTasksModel::LauncherUrl).toUrl(); const QString &launcherUrlString = launcherUrl.toString(QUrl::RemoveQuery | QUrl::RemoveQuery); if (d->blacklistedAppIds.contains(appId) || d->blacklistedLauncherUrls.contains(launcherUrlString)) { d->blacklistedAppIds.remove(appId); d->blacklistedLauncherUrls.remove(launcherUrlString); if (d->groupMode != TasksModel::GroupDisabled) { d->formGroupFor(index.parent().isValid() ? index.parent() : index); } } else { d->blacklistedAppIds.insert(appId); d->blacklistedLauncherUrls.insert(launcherUrlString); if (d->groupMode != TasksModel::GroupDisabled) { d->breakGroupFor(index.parent().isValid() ? index.parent() : index); } } // Update IsGroupable data role for all relevant top-level items. We don't need to update // for group members since they've just been inserted -- it's logically impossible to // toggle grouping _on_ from a group member. for (int i = 0; i < d->rowMap.count(); ++i) { if (!d->isGroup(i)) { const QModelIndex &idx = TaskGroupingProxyModel::index(i, 0); if (idx.data(AbstractTasksModel::AppId).toString() == appId || launcherUrlsMatch(idx.data(AbstractTasksModel::LauncherUrl).toUrl(), launcherUrl, IgnoreQueryItems)) { dataChanged(idx, idx, QVector{AbstractTasksModel::IsGroupable}); } } } emit blacklistedAppIdsChanged(); emit blacklistedLauncherUrlsChanged(); } } #include "moc_taskgroupingproxymodel.cpp" diff --git a/libtaskmanager/xwindowtasksmodel.cpp b/libtaskmanager/xwindowtasksmodel.cpp index 43765241..de9a5782 100644 --- a/libtaskmanager/xwindowtasksmodel.cpp +++ b/libtaskmanager/xwindowtasksmodel.cpp @@ -1,1315 +1,1341 @@ /******************************************************************** 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 #include #include #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; static const NET::Properties2 windowInfoFlags2 = NET::WM2WindowClass | NET::WM2AllowedActions; class XWindowTasksModel::Private { public: Private(XWindowTasksModel *q); ~Private(); QVector windows; QSet transients; QHash transientsDemandingAttention; QHash windowInfoCache; QHash appDataCache; QHash delegateGeometries; 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); QUrl serviceUrl(int pid, const QString &type, const QStringList &cmdRemovals); KService::List servicesFromPid(int pid); QStringList activities(WId window); 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() { rulesConfig = KSharedConfig::openConfig(QStringLiteral("taskmanagerrulesrc")); configWatcher = new KDirWatch(q); foreach (const QString &location, QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)) { configWatcher->addFile(location + QLatin1String("/taskmanagerrulesrc")); } QObject::connect(configWatcher, &KDirWatch::dirty, [this] { rulesConfig->reparseConfiguration(); }); QObject::connect(configWatcher, &KDirWatch::created, [this] { rulesConfig->reparseConfiguration(); }); QObject::connect(configWatcher, &KDirWatch::deleted, [this] { rulesConfig->reparseConfiguration(); }); sycocaChangeTimer.setSingleShot(true); sycocaChangeTimer.setInterval(100); QObject::connect(&sycocaChangeTimer, &QTimer::timeout, q, [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}); } ); 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(); } } ); QObject::connect(KWindowSystem::self(), &KWindowSystem::windowAdded, q, [this](WId window) { addWindow(window); } ); QObject::connect(KWindowSystem::self(), &KWindowSystem::windowRemoved, q, [this](WId window) { removeWindow(window); } ); void (KWindowSystem::*myWindowChangeSignal)(WId window, NET::Properties properties, NET::Properties2 properties2) = &KWindowSystem::windowChanged; QObject::connect(KWindowSystem::self(), myWindowChangeSignal, 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); 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)) { QMutableHashIterator i(transientsDemandingAttention); WId leader = 0; while (i.hasNext()) { i.next(); if (i.value() == window) { if (leader == 0) { leader = i.key(); } i.remove(); } } if (leader != 0) { 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)) { WId oldLeader = info.transientFor(); QMutableHashIterator i(transientsDemandingAttention); while (i.hasNext()) { i.next(); if (i.value() == window) { i.remove(); oldLeader = i.key(); } } if (oldLeader != 0) { const WId leader = info.transientFor(); 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::WMName | NET::WMVisibleName | NET::WM2WindowClass | NET::WMPid) || properties2 & NET::WM2WindowClass) { wipeInfoCache = true; wipeAppDataCache = true; changedRoles << Qt::DisplayRole << Qt::DecorationRole << AppId << AppName << GenericName << LauncherUrl; } if ((properties & NET::WMIcon) && !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); } 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) { if (!windowInfoCache.contains(window)) { KWindowInfo *info = new KWindowInfo(window, windowInfoFlags, windowInfoFlags2); windowInfoCache.insert(window, info); return info; } return windowInfoCache.value(window); } AppData XWindowTasksModel::Private::appData(WId window) { if (!appDataCache.contains(window)) { 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; } return appDataCache.value(window); } 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)); 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) { QUrl url; const KWindowInfo *info = windowInfo(window); const QString &classClass = info->windowClassClass(); const QString &className = info->windowClassName(); KService::List services; bool triedPid = false; if (!(classClass.isEmpty() && className.isEmpty())) { int pid = NETWinInfo(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMPid, 0).pid(); // For KCModules, if we matched on window class, etc, we would end up matching // to kcmshell5 itself - but we are more than likely interested in the actual // control module. Therefore we obtain this via the commandline. This commandline // may contain "kdeinit4:" or "[kdeinit]", so we remove these first. if (classClass == "kcmshell5") { url = serviceUrl(pid, QStringLiteral("KCModule"), QStringList() << QStringLiteral("kdeinit5:") << QStringLiteral("[kdeinit]")); if (!url.isEmpty()) { return url; } } // Check to see if this wmClass matched a saved one ... KConfigGroup grp(rulesConfig, "Mapping"); KConfigGroup set(rulesConfig, "Settings"); // Some apps have different launchers depending upon command line ... QStringList matchCommandLineFirst = set.readEntry("MatchCommandLineFirst", QStringList()); if (!classClass.isEmpty() && matchCommandLineFirst.contains(classClass)) { triedPid = true; services = servicesFromPid(pid); } // Try to match using className also. if (!className.isEmpty() && matchCommandLineFirst.contains("::"+className)) { triedPid = true; services = servicesFromPid(pid); } // If the user has manually set a mapping, respect this first... QString mapped(grp.readEntry(classClass + "::" + className, QString())); if (mapped.endsWith(QLatin1String(".desktop"))) { url = QUrl(mapped); return url; } if (!classClass.isEmpty()) { if (mapped.isEmpty()) { mapped = grp.readEntry(classClass, QString()); if (mapped.endsWith(QLatin1String(".desktop"))) { url = QUrl(mapped); return url; } } // Some apps, such as Wine, cannot use className 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 (!classClass.isEmpty() && manualOnly.contains(classClass)) { return url; } KConfigGroup rewriteRulesGroup(rulesConfig, QStringLiteral("Rewrite Rules")); if (rewriteRulesGroup.hasGroup(classClass)) { KConfigGroup rewriteGroup(&rewriteRulesGroup, classClass); 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 = classClass; } else if (propertyConfig == QLatin1String("ClassName")) { matchProperty = className; } 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; } const QString rewrittenString = ruleGroup.readEntry(QStringLiteral("Target")).arg(actualMatch); services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ %2)").arg(rewrittenString, serviceSearchIdentifier)); if (!services.isEmpty()) { break; } } } } if (!mapped.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ DesktopEntryName)").arg(mapped)); } if (!mapped.isEmpty() && services.empty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Name)").arg(mapped)); } // To match other docks (docky, unity, etc.) attempt to match on DesktopEntryName first ... if (services.empty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ DesktopEntryName)").arg(classClass)); } // Try StartupWMClass. if (services.empty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ StartupWMClass)").arg(classClass)); } // Try 'Name' - unfortunately this can be translated, so has a good chance of failing! (As it does for KDE's own "System Settings" (even in English!!)) if (services.empty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Name)").arg(classClass)); } } // Ok, absolute *last* chance, try matching via pid (but only if we have not already tried this!) ... if (services.empty() && !triedPid) { services = servicesFromPid(pid); } } // 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 '*.classClass.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 classClass is 'dragonplayer' // - classClass cannot directly match the desktop file because of RDN // - classClass also cannot match the binary because of name mismatch // - in the following code *.classClass can match org.kde.dragonplayer though if (services.empty() || services.at(0)->desktopEntryName().isEmpty()) { auto matchingServices = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' ~~ DesktopEntryName)").arg(classClass)); QMutableListIterator it(matchingServices); while (it.hasNext()) { auto service = it.next(); if (!service->desktopEntryName().endsWith("." + classClass)) { 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.empty()) { QString path = services[0]->entryPath(); if (path.isEmpty()) { path = services[0]->exec(); } if (!path.isEmpty()) { url = QUrl::fromLocalFile(path); } } return url; } 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; - // FIXME Hard-coding 64x64 or SizeLarge is not scaling-aware. + // 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; } QUrl XWindowTasksModel::Private::serviceUrl(int pid, const QString &type, const QStringList &cmdRemovals = QStringList()) { if (pid == 0) { return QUrl(); } KSysGuard::Processes procs; procs.updateOrAddProcess(pid); KSysGuard::Process *proc = procs.getProcess(pid); QString cmdline = proc ? proc->command().simplified() : QString(); // proc->command has a trailing space??? if (cmdline.isEmpty()) { return QUrl(); } foreach (const QString & r, cmdRemovals) { cmdline.replace(r, QLatin1String("")); } KService::List services = KServiceTypeTrader::self()->query(type, QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdline)); if (services.empty()) { // Could not find with complete command line, so strip out path part ... int slash = cmdline.lastIndexOf('/', cmdline.indexOf(' ')); if (slash > 0) { services = KServiceTypeTrader::self()->query(type, QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdline.mid(slash + 1))); } if (services.empty()) { return QUrl(); } } if (!services.isEmpty()) { QString path = services[0]->entryPath(); if (!QDir::isAbsolutePath(path)) { QString absolutePath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kservices5/"+path); if (!absolutePath.isEmpty()) path = absolutePath; } if (QFile::exists(path)) { return QUrl::fromLocalFile(path); } } return QUrl(); } KService::List XWindowTasksModel::Private::servicesFromPid(int pid) { // Attempt to find using commandline... KService::List services; if (pid == 0) { return services; } KSysGuard::Processes procs; procs.updateOrAddProcess(pid); KSysGuard::Process *proc = procs.getProcess(pid); QString cmdline = proc ? proc->command().simplified() : QString(); // proc->command has a trailing space??? if (cmdline.isEmpty()) { return services; } const int firstSpace = cmdline.indexOf(' '); services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Exec)").arg(cmdline)); if (services.empty()) { // Could not find with complete commandline, so strip out path part... int 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.empty() && 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)); int 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.empty() && proc && !QStandardPaths::findExecutable(cmdline).isEmpty()) { // cmdline now exists without arguments if there were any services << QExplicitlySharedDataPointer(new KService(proc->name(), cmdline, QString())); } return services; } QStringList XWindowTasksModel::Private::activities(WId window) { NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), 0, NET::WM2Activities); const QString result(ni.activities()); if (!result.isEmpty() && result != QLatin1String("00000000-0000-0000-0000-000000000000")) { return result.split(','); } return QStringList(); } 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) : AbstractTasksModel(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->activities(window); } else if (role == IsDemandingAttention) { return d->demandsAttention(window); } else if (role == SkipTaskbar) { - return d->windowInfo(window)->hasState(NET::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); } else if (role == SkipPager) { return d->windowInfo(window)->hasState(NET::SkipPager); } 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; } const QUrl &url = d->appData(d->windows.at(index.row())).url; if (url.isValid()) { new KRun(url, 0, false, KStartupInfo::createNewStartupIdForTimestamp(QX11Info::appUserTime())); } } 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; } const QUrl &url = d->appData(d->windows.at(index.row())).url; const KService::Ptr service = KService::serviceByDesktopPath(url.toLocalFile()); if (service) { KRun::runApplication(*service, urls, nullptr, 0, {}, KStartupInfo::createNewStartupIdForTimestamp(QX11Info::appUserTime())); } } 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, 0); if (restore) { ni.setState(0, 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, 0); if (info->hasState(NET::StaysOnTop)) { ni.setState(0, 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, 0); if (info->hasState(NET::KeepBelow)) { ni.setState(0, 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, 0); if (info->hasState(NET::FullScreen)) { ni.setState(0, 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, 0); if (info->hasState(NET::Shaded)) { ni.setState(0, 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(), 0, 0); 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; } } diff --git a/shell/panelview.cpp b/shell/panelview.cpp index 953e42c0..57d5cd88 100644 --- a/shell/panelview.cpp +++ b/shell/panelview.cpp @@ -1,1174 +1,1175 @@ /* * Copyright 2013 Marco Martin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include "panelview.h" #include "shellcorona.h" #include "panelshadows_p.h" #include "panelconfigview.h" #include "screenpool.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if HAVE_X11 #include #include #include #endif static const int MINSIZE = 10; PanelView::PanelView(ShellCorona *corona, QScreen *targetScreen, QWindow *parent) : PlasmaQuick::ContainmentView(corona, parent), m_offset(0), m_maxLength(0), m_minLength(0), m_contentLength(0), m_distance(0), m_thickness(30), m_alignment(Qt::AlignLeft), m_corona(corona), m_visibilityMode(NormalPanel), m_background(0), m_shellSurface(nullptr) { if (targetScreen) { setPosition(targetScreen->geometry().center()); setScreenToFollow(targetScreen); setScreen(targetScreen); } setResizeMode(QuickViewSharedEngine::SizeRootObjectToView); setClearBeforeRendering(true); setColor(QColor(Qt::transparent)); setFlags(Qt::FramelessWindowHint|Qt::WindowDoesNotAcceptFocus); connect(&m_theme, &Plasma::Theme::themeChanged, this, &PanelView::themeChanged); m_positionPaneltimer.setSingleShot(true); m_positionPaneltimer.setInterval(150); connect(&m_positionPaneltimer, &QTimer::timeout, this, [this] () { restore(); positionPanel(); }); m_unhideTimer.setSingleShot(true); m_unhideTimer.setInterval(500); connect(&m_unhideTimer, &QTimer::timeout, this, &PanelView::restoreAutoHide); m_lastScreen = targetScreen; connect(this, SIGNAL(locationChanged(Plasma::Types::Location)), &m_positionPaneltimer, SLOT(start())); connect(this, SIGNAL(containmentChanged()), this, SLOT(containmentChanged())); if (!m_corona->kPackage().isValid()) { qWarning() << "Invalid home screen package"; } m_strutsTimer.setSingleShot(true); connect(&m_strutsTimer, &QTimer::timeout, this, &PanelView::updateStruts); qmlRegisterType(); rootContext()->setContextProperty(QStringLiteral("panel"), this); setSource(QUrl::fromLocalFile(m_corona->kPackage().filePath("views", QStringLiteral("Panel.qml")))); } PanelView::~PanelView() { if (containment()) { m_corona->requestApplicationConfigSync(); } } KConfigGroup PanelView::panelConfig(ShellCorona *corona, Plasma::Containment *containment, QScreen *screen) { if (!containment || !screen) { return KConfigGroup(); } KConfigGroup views(corona->applicationConfig(), "PlasmaViews"); views = KConfigGroup(&views, QStringLiteral("Panel %1").arg(containment->id())); if (containment->formFactor() == Plasma::Types::Vertical) { return KConfigGroup(&views, "Vertical" + QString::number(screen->size().height())); //treat everything else as horizontal } else { return KConfigGroup(&views, "Horizontal" + QString::number(screen->size().width())); } } KConfigGroup PanelView::config() const { return panelConfig(m_corona, containment(), m_screenToFollow); } void PanelView::maximize() { int length; if (containment()->formFactor() == Plasma::Types::Vertical) { length = m_screenToFollow->size().height(); } else { length = m_screenToFollow->size().width(); } setOffset(0); setMinimumLength(length); setMaximumLength(length); } Qt::Alignment PanelView::alignment() const { return m_alignment; } void PanelView::setAlignment(Qt::Alignment alignment) { if (m_alignment == alignment) { return; } m_alignment = alignment; config().writeEntry("alignment", (int)m_alignment); emit alignmentChanged(); positionPanel(); } int PanelView::offset() const { return m_offset; } void PanelView::setOffset(int offset) { if (m_offset == offset) { return; } if (formFactor() == Plasma::Types::Vertical) { if (offset + m_maxLength > m_screenToFollow->size().height()) { setMaximumLength( -m_offset + m_screenToFollow->size().height() ); } } else { if (offset + m_maxLength > m_screenToFollow->size().width()) { setMaximumLength( -m_offset + m_screenToFollow->size().width() ); } } m_offset = offset; config().writeEntry("offset", m_offset); positionPanel(); emit offsetChanged(); m_corona->requestApplicationConfigSync(); emit m_corona->availableScreenRegionChanged(); } int PanelView::thickness() const { return m_thickness; } void PanelView::setThickness(int value) { if (value == thickness()) { return; } m_thickness = value; emit thicknessChanged(); config().writeEntry("thickness", value); m_corona->requestApplicationConfigSync(); resizePanel(); } int PanelView::length() const { return qMax(1, m_contentLength); } void PanelView::setLength(int value) { if (value == m_contentLength) { return; } m_contentLength = value; resizePanel(); emit m_corona->availableScreenRegionChanged(); } int PanelView::maximumLength() const { return m_maxLength; } void PanelView::setMaximumLength(int length) { if (length == m_maxLength) { return; } if (m_minLength > length) { setMinimumLength(length); } config().writeEntry("maxLength", length); m_maxLength = length; emit maximumLengthChanged(); m_corona->requestApplicationConfigSync(); resizePanel(); } int PanelView::minimumLength() const { return m_minLength; } void PanelView::setMinimumLength(int length) { if (length == m_minLength) { return; } if (m_maxLength < length) { setMaximumLength(length); } config().writeEntry("minLength", length); m_minLength = length; emit minimumLengthChanged(); m_corona->requestApplicationConfigSync(); resizePanel(); } int PanelView::distance() const { return m_distance; } void PanelView::setDistance(int dist) { if (m_distance == dist) { return; } m_distance = dist; emit distanceChanged(); positionPanel(); } Plasma::FrameSvg::EnabledBorders PanelView::enabledBorders() const { return m_enabledBorders; } void PanelView::setVisibilityMode(PanelView::VisibilityMode mode) { if (m_visibilityMode == mode) { return; } m_visibilityMode = mode; disconnect(containment(), &Plasma::Applet::activated, this, &PanelView::showTemporarily); if (edgeActivated()) { connect(containment(), &Plasma::Applet::activated, this, &PanelView::showTemporarily); } if (config().isValid()) { config().writeEntry("panelVisibility", (int)mode); m_corona->requestApplicationConfigSync(); } visibilityModeToWayland(); updateStruts(); emit visibilityModeChanged(); restoreAutoHide(); } void PanelView::visibilityModeToWayland() { if (!m_shellSurface) { return; } KWayland::Client::PlasmaShellSurface::PanelBehavior behavior; switch (m_visibilityMode) { case NormalPanel: behavior = KWayland::Client::PlasmaShellSurface::PanelBehavior::AlwaysVisible; break; case AutoHide: behavior = KWayland::Client::PlasmaShellSurface::PanelBehavior::AutoHide; break; case LetWindowsCover: behavior = KWayland::Client::PlasmaShellSurface::PanelBehavior::WindowsCanCover; break; case WindowsGoBelow: behavior = KWayland::Client::PlasmaShellSurface::PanelBehavior::WindowsGoBelow; break; default: Q_UNREACHABLE(); return; } m_shellSurface->setPanelBehavior(behavior); } PanelView::VisibilityMode PanelView::visibilityMode() const { return m_visibilityMode; } void PanelView::positionPanel() { if (!containment()) { return; } KWindowEffects::SlideFromLocation slideLocation = KWindowEffects::NoEdge; switch (containment()->location()) { case Plasma::Types::TopEdge: containment()->setFormFactor(Plasma::Types::Horizontal); slideLocation = KWindowEffects::TopEdge; break; case Plasma::Types::LeftEdge: containment()->setFormFactor(Plasma::Types::Vertical); slideLocation = KWindowEffects::LeftEdge; break; case Plasma::Types::RightEdge: containment()->setFormFactor(Plasma::Types::Vertical); slideLocation = KWindowEffects::RightEdge; break; case Plasma::Types::BottomEdge: default: containment()->setFormFactor(Plasma::Types::Horizontal); slideLocation = KWindowEffects::BottomEdge; break; } const QPoint pos = geometryByDistance(m_distance).topLeft(); setPosition(pos); if (m_shellSurface) { m_shellSurface->setPosition(pos); } KWindowEffects::slideWindow(winId(), slideLocation, -1); } QRect PanelView::geometryByDistance(int distance) const { QScreen *s = m_screenToFollow; QPoint position; const QRect screenGeometry = s->geometry(); switch (containment()->location()) { case Plasma::Types::TopEdge: switch (m_alignment) { case Qt::AlignCenter: position = QPoint(QPoint(screenGeometry.center().x(), screenGeometry.top()) + QPoint(m_offset - width()/2, distance)); break; case Qt::AlignRight: position = QPoint(QPoint(screenGeometry.x() + screenGeometry.width(), screenGeometry.y()) - QPoint(m_offset + width(), distance)); break; case Qt::AlignLeft: default: position = QPoint(screenGeometry.topLeft() + QPoint(m_offset, distance)); } break; case Plasma::Types::LeftEdge: switch (m_alignment) { case Qt::AlignCenter: position = QPoint(QPoint(screenGeometry.left(), screenGeometry.center().y()) + QPoint(distance, m_offset - height()/2)); break; case Qt::AlignRight: position = QPoint(QPoint(screenGeometry.left(), screenGeometry.y() + screenGeometry.height()) - QPoint(distance, m_offset + height())); break; case Qt::AlignLeft: default: position = QPoint(screenGeometry.topLeft() + QPoint(distance, m_offset)); } break; case Plasma::Types::RightEdge: switch (m_alignment) { case Qt::AlignCenter: // Never use rect.right(); for historical reasons it returns left() + width() - 1; see http://doc.qt.io/qt-5/qrect.html#right position = QPoint(QPoint(screenGeometry.x() + screenGeometry.width(), screenGeometry.center().y()) - QPoint(thickness() + distance, 0) + QPoint(0, m_offset - height()/2)); break; case Qt::AlignRight: position = QPoint(QPoint(screenGeometry.x() + screenGeometry.width(), screenGeometry.y() + screenGeometry.height()) - QPoint(thickness() + distance, 0) - QPoint(0, m_offset + height())); break; case Qt::AlignLeft: default: position = QPoint(QPoint(screenGeometry.x() + screenGeometry.width(), screenGeometry.y()) - QPoint(thickness() + distance, 0) + QPoint(0, m_offset)); } break; case Plasma::Types::BottomEdge: default: switch (m_alignment) { case Qt::AlignCenter: position = QPoint(QPoint(screenGeometry.center().x(), screenGeometry.bottom() - thickness() - distance) + QPoint(m_offset - width()/2, 1)); break; case Qt::AlignRight: position = QPoint(screenGeometry.bottomRight() - QPoint(0, thickness() + distance) - QPoint(m_offset + width(), -1)); break; case Qt::AlignLeft: default: position = QPoint(screenGeometry.bottomLeft() - QPoint(0, thickness() + distance) + QPoint(m_offset, 1)); } } QRect ret = formFactor() == Plasma::Types::Vertical ? QRect(position, QSize(thickness(), height())) : QRect(position, QSize(width(), thickness())); ret = ret.intersected(screenGeometry); return ret; } void PanelView::resizePanel() { if (formFactor() == Plasma::Types::Vertical) { const int minSize = qMax(MINSIZE, m_minLength); const int maxSize = qMin(m_maxLength, m_screenToFollow->size().height() - m_offset); setMinimumSize(QSize(thickness(), minSize)); setMaximumSize(QSize(thickness(), maxSize)); resize(thickness(), qBound(minSize, m_contentLength, maxSize)); } else { const int minSize = qMax(MINSIZE, m_minLength); const int maxSize = qMin(m_maxLength, m_screenToFollow->size().width() - m_offset); setMinimumSize(QSize(minSize, thickness())); setMaximumSize(QSize(maxSize, thickness())); resize(qBound(minSize, m_contentLength, maxSize), thickness()); } //position will be updated implicitly from resizeEvent } void PanelView::restore() { if (!containment()) { return; } //defaults, may be altered by values written by the scripting in startup phase int defaultOffset = 0; int defaultThickness = 30; int defaultMaxLength = 0; int defaultMinLength = 0; int defaultAlignment = Qt::AlignLeft; setAlignment((Qt::Alignment)config().readEntry("alignment", defaultAlignment)); m_offset = config().readEntry("offset", defaultOffset); if (m_alignment != Qt::AlignCenter) { m_offset = qMax(0, m_offset); } setThickness(config().readEntry("thickness", defaultThickness)); setMinimumSize(QSize(-1, -1)); //FIXME: an invalid size doesn't work with QWindows setMaximumSize(m_screenToFollow->size()); if (containment()->formFactor() == Plasma::Types::Vertical) { defaultMaxLength = m_screenToFollow->size().height(); defaultMinLength = m_screenToFollow->size().height(); m_maxLength = config().readEntry("maxLength", defaultMaxLength); m_minLength = config().readEntry("minLength", defaultMinLength); const int maxSize = m_screenToFollow->size().height() - m_offset; m_maxLength = qBound(MINSIZE, m_maxLength, maxSize); m_minLength = qBound(MINSIZE, m_minLength, maxSize); //Horizontal } else { defaultMaxLength = m_screenToFollow->size().width(); defaultMinLength = m_screenToFollow->size().width(); m_maxLength = config().readEntry("maxLength", defaultMaxLength); m_minLength = config().readEntry("minLength", defaultMinLength); const int maxSize = m_screenToFollow->size().width() - m_offset; m_maxLength = qBound(MINSIZE, m_maxLength, maxSize); m_minLength = qBound(MINSIZE, m_minLength, maxSize); } setVisibilityMode((VisibilityMode)config().readEntry("panelVisibility", (int)NormalPanel)); resizePanel(); + positionPanel(); emit maximumLengthChanged(); emit minimumLengthChanged(); emit offsetChanged(); emit alignmentChanged(); } void PanelView::showConfigurationInterface(Plasma::Applet *applet) { if (!applet || !applet->containment()) { return; } Plasma::Containment *cont = qobject_cast(applet); if (m_panelConfigView && cont && cont == containment() && cont->isContainment()) { if (m_panelConfigView.data()->isVisible()) { m_panelConfigView.data()->hide(); } else { m_panelConfigView.data()->show(); KWindowSystem::setState(m_panelConfigView.data()->winId(), NET::SkipTaskbar | NET::SkipPager); } return; } else if (m_panelConfigView) { if (m_panelConfigView->applet() == applet) { m_panelConfigView->show(); m_panelConfigView->requestActivate(); return; } else { m_panelConfigView->hide(); m_panelConfigView->deleteLater(); } } if (cont && cont == containment() && cont->isContainment()) { m_panelConfigView = new PanelConfigView(cont, this); } else { m_panelConfigView = new PlasmaQuick::ConfigView(applet); } m_panelConfigView.data()->init(); m_panelConfigView.data()->show(); if (cont && cont == containment() && cont->isContainment()) { KWindowSystem::setState(m_panelConfigView.data()->winId(), NET::SkipTaskbar | NET::SkipPager); } } void PanelView::restoreAutoHide() { setAutoHideEnabled(edgeActivated() && (!containment() || (containment()->status() < Plasma::Types::RequiresAttentionStatus || containment()->status() == Plasma::Types::HiddenStatus) ) && !geometry().contains(QCursor::pos()) ); } void PanelView::setAutoHideEnabled(bool enabled) { #if HAVE_X11 if (KWindowSystem::isPlatformX11()) { xcb_connection_t *c = QX11Info::connection(); const QByteArray effectName = QByteArrayLiteral("_KDE_NET_WM_SCREEN_EDGE_SHOW"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); if (!atom) { return; } if (!enabled) { xcb_delete_property(c, winId(), atom->atom); return; } KWindowEffects::SlideFromLocation slideLocation = KWindowEffects::NoEdge; uint32_t value = 0; switch (location()) { case Plasma::Types::TopEdge: value = 0; slideLocation = KWindowEffects::TopEdge; break; case Plasma::Types::RightEdge: value = 1; slideLocation = KWindowEffects::RightEdge; break; case Plasma::Types::BottomEdge: value = 2; slideLocation = KWindowEffects::BottomEdge; break; case Plasma::Types::LeftEdge: value = 3; slideLocation = KWindowEffects::LeftEdge; break; case Plasma::Types::Floating: default: value = 4; break; } int hideType = 0; if (m_visibilityMode == LetWindowsCover) { hideType = 1; } value |= hideType << 8; xcb_change_property(c, XCB_PROP_MODE_REPLACE, winId(), atom->atom, XCB_ATOM_CARDINAL, 32, 1, &value); KWindowEffects::slideWindow(winId(), slideLocation, -1); } #endif } void PanelView::resizeEvent(QResizeEvent *ev) { updateMask(); updateEnabledBorders(); //don't setGeometry() to make really sure we aren't doing a resize loop const QPoint pos = geometryByDistance(m_distance).topLeft(); setPosition(pos); if (m_shellSurface) { m_shellSurface->setPosition(pos); } m_strutsTimer.start(STRUTSTIMERDELAY); PlasmaQuick::ContainmentView::resizeEvent(ev); } void PanelView::moveEvent(QMoveEvent *ev) { updateMask(); updateEnabledBorders(); m_strutsTimer.start(STRUTSTIMERDELAY); PlasmaQuick::ContainmentView::moveEvent(ev); } void PanelView::integrateScreen() { connect(m_screenToFollow.data(), &QScreen::geometryChanged, this, &PanelView::restore); themeChanged(); KWindowSystem::setOnAllDesktops(winId(), true); KWindowSystem::setType(winId(), NET::Dock); if (m_shellSurface) { m_shellSurface->setRole(KWayland::Client::PlasmaShellSurface::Role::Panel); m_shellSurface->setSkipTaskbar(true); } setVisibilityMode(m_visibilityMode); if (containment()) { containment()->reactToScreenChange(); } } void PanelView::showEvent(QShowEvent *event) { PanelShadows::self()->addWindow(this, enabledBorders()); PlasmaQuick::ContainmentView::showEvent(event); integrateScreen(); } void PanelView::setScreenToFollow(QScreen *screen) { if (screen == m_screenToFollow) { return; } /*connect(screen, &QObject::destroyed, this, [this]() { if (PanelView::screen()) { m_screenToFollow = PanelView::screen(); adaptToScreen(); } });*/ m_screenToFollow = screen; setScreen(screen); adaptToScreen(); } QScreen *PanelView::screenToFollow() const { return m_screenToFollow; } void PanelView::adaptToScreen() { emit screenToFollowChanged(m_screenToFollow); m_lastScreen = m_screenToFollow; if (!m_screenToFollow) { return; } integrateScreen(); showTemporarily(); m_positionPaneltimer.start(); } bool PanelView::event(QEvent *e) { if (edgeActivated()) { if (e->type() == QEvent::Enter) { m_unhideTimer.stop(); } else if (e->type() == QEvent::Leave) { m_unhideTimer.start(); } } /*Fitt's law: if the containment has margins, and the mouse cursor clicked * on the mouse edge, forward the click in the containment boundaries */ switch (e->type()) { case QEvent::MouseMove: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: { QMouseEvent *me = static_cast(e); //first, don't mess with position if the cursor is actually outside the view: //somebody is doing a click and drag that must not break when the cursor i outside if (geometry().contains(QCursor::pos())) { if (!containmentContainsPosition(me->windowPos())) { auto me2 = new QMouseEvent(me->type(), positionAdjustedForContainment(me->windowPos()), positionAdjustedForContainment(me->windowPos()), positionAdjustedForContainment(me->windowPos()) + position(), me->button(), me->buttons(), me->modifiers()); QCoreApplication::postEvent(this, me2); return true; } } else { // discard event if current mouse position is outside the panel return true; } break; } case QEvent::Enter: case QEvent::Leave: // QtQuick < 5.6 issue: // QEvent::Leave is triggered on MouseButtonPress Qt::LeftButton break; case QEvent::Wheel: { QWheelEvent *we = static_cast(e); if (!containmentContainsPosition(we->pos())) { auto we2 = new QWheelEvent(positionAdjustedForContainment(we->pos()), positionAdjustedForContainment(we->pos()) + position(), we->pixelDelta(), we->angleDelta(), we->delta(), we->orientation(), we->buttons(), we->modifiers(), we->phase()); QCoreApplication::postEvent(this, we2); return true; } break; } case QEvent::DragEnter: { QDragEnterEvent *de = static_cast(e); if (!containmentContainsPosition(de->pos())) { auto de2 = new QDragEnterEvent(positionAdjustedForContainment(de->pos()).toPoint(), de->possibleActions(), de->mimeData(), de->mouseButtons(), de->keyboardModifiers()); QCoreApplication::postEvent(this, de2); return true; } break; } //DragLeave just works case QEvent::DragLeave: break; case QEvent::DragMove: { QDragMoveEvent *de = static_cast(e); if (!containmentContainsPosition(de->pos())) { auto de2 = new QDragMoveEvent(positionAdjustedForContainment(de->pos()).toPoint(), de->possibleActions(), de->mimeData(), de->mouseButtons(), de->keyboardModifiers()); QCoreApplication::postEvent(this, de2); return true; } break; } case QEvent::Drop: { QDropEvent *de = static_cast(e); if (!containmentContainsPosition(de->pos())) { auto de2 = new QDropEvent(positionAdjustedForContainment(de->pos()).toPoint(), de->possibleActions(), de->mimeData(), de->mouseButtons(), de->keyboardModifiers()); QCoreApplication::postEvent(this, de2); return true; } break; } case QEvent::Hide: { if (m_panelConfigView && m_panelConfigView.data()->isVisible()) { m_panelConfigView.data()->hide(); } break; } case QEvent::PlatformSurface: if (auto pe = dynamic_cast(e)) { switch (pe->surfaceEventType()) { case QPlatformSurfaceEvent::SurfaceCreated: setupWaylandIntegration(); break; case QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed: delete m_shellSurface; m_shellSurface = nullptr; PanelShadows::self()->removeWindow(this); break; } } break; default: break; } return ContainmentView::event(e); } bool PanelView::containmentContainsPosition(const QPointF &point) const { QQuickItem *containmentItem = containment()->property("_plasma_graphicObject").value(); if (!containmentItem) { return false; } return QRectF(containmentItem->mapToScene(QPoint(0,0)), QSizeF(containmentItem->width(), containmentItem->height())).contains(point); } QPointF PanelView::positionAdjustedForContainment(const QPointF &point) const { QQuickItem *containmentItem = containment()->property("_plasma_graphicObject").value(); if (!containmentItem) { return point; } QRectF containmentRect(containmentItem->mapToScene(QPoint(0,0)), QSizeF(containmentItem->width(), containmentItem->height())); return QPointF(qBound(containmentRect.left() + 2, point.x(), containmentRect.right() - 2), qBound(containmentRect.top() + 2, point.y(), containmentRect.bottom() - 2)); } void PanelView::updateMask() { if (KWindowSystem::compositingActive()) { setMask(QRegion()); } else { if (!m_background) { m_background = new Plasma::FrameSvg(this); m_background->setImagePath(QStringLiteral("widgets/panel-background")); } m_background->setEnabledBorders(enabledBorders()); m_background->resizeFrame(size()); setMask(m_background->mask()); } } bool PanelView::canSetStrut() const { #if HAVE_X11 if (!QX11Info::isPlatformX11()) { return true; } // read the wm name, need to do this every time which means a roundtrip unfortunately // but WM might have changed NETRootInfo rootInfo(QX11Info::connection(), NET::Supported | NET::SupportingWMCheck); if (qstricmp(rootInfo.wmName(), "KWin") == 0) { // KWin since 5.7 can handle this fine, so only exclude for other window managers return true; } const QRect thisScreen = screen()->geometry(); const int numScreens = corona()->numScreens(); if (numScreens < 2) { return true; } //Extended struts against a screen edge near to another screen are really harmful, so windows maximized under the panel is a lesser pain //TODO: force "windows can cover" in those cases? foreach (int id, m_corona->screenIds()) { if (id == containment()->screen()) { continue; } const QRect otherScreen = corona()->screenGeometry(id); if (!otherScreen.isValid()) { continue; } switch (location()) { case Plasma::Types::TopEdge: if (otherScreen.bottom() <= thisScreen.top()) { return false; } break; case Plasma::Types::BottomEdge: if (otherScreen.top() >= thisScreen.bottom()) { return false; } break; case Plasma::Types::RightEdge: if (otherScreen.left() >= thisScreen.right()) { return false; } break; case Plasma::Types::LeftEdge: if (otherScreen.right() <= thisScreen.left()) { return false; } break; default: return false; } } return true; #else return true; #endif } void PanelView::updateStruts() { if (!containment() || !m_screenToFollow) { return; } NETExtendedStrut strut; if (m_visibilityMode == NormalPanel) { const QRect thisScreen = m_screenToFollow->geometry(); // QScreen::virtualGeometry() is very unreliable (Qt 5.5) const QRect wholeScreen = QRect(QPoint(0, 0), m_screenToFollow->virtualSize()); if (!canSetStrut()) { KWindowSystem::setExtendedStrut(winId(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); return; } // extended struts are to the combined screen geoms, not the single screen int leftOffset = thisScreen.x(); int rightOffset = wholeScreen.right() - thisScreen.right(); int bottomOffset = wholeScreen.bottom() - thisScreen.bottom(); // qDebug() << "screen l/r/b/t offsets are:" << leftOffset << rightOffset << bottomOffset << topOffset << location(); int topOffset = thisScreen.top(); switch (location()) { case Plasma::Types::TopEdge: strut.top_width = thickness() + topOffset; strut.top_start = x(); strut.top_end = x() + width() - 1; // qDebug() << "setting top edge to" << strut.top_width << strut.top_start << strut.top_end; break; case Plasma::Types::BottomEdge: strut.bottom_width = thickness() + bottomOffset; strut.bottom_start = x(); strut.bottom_end = x() + width() - 1; // qDebug() << "setting bottom edge to" << strut.bottom_width << strut.bottom_start << strut.bottom_end; break; case Plasma::Types::RightEdge: strut.right_width = thickness() + rightOffset; strut.right_start = y(); strut.right_end = y() + height() - 1; // qDebug() << "setting right edge to" << strut.right_width << strut.right_start << strut.right_end; break; case Plasma::Types::LeftEdge: strut.left_width = thickness() + leftOffset; strut.left_start = y(); strut.left_end = y() + height() - 1; // qDebug() << "setting left edge to" << strut.left_width << strut.left_start << strut.left_end; break; default: //qDebug() << "where are we?"; break; } } KWindowSystem::setExtendedStrut(winId(), strut.left_width, strut.left_start, strut.left_end, strut.right_width, strut.right_start, strut.right_end, strut.top_width, strut.top_start, strut.top_end, strut.bottom_width, strut.bottom_start, strut.bottom_end); } void PanelView::themeChanged() { KWindowEffects::enableBlurBehind(winId(), true); KWindowEffects::enableBackgroundContrast(winId(), m_theme.backgroundContrastEnabled(), m_theme.backgroundContrast(), m_theme.backgroundIntensity(), m_theme.backgroundSaturation()); updateMask(); } void PanelView::containmentChanged() { restore(); connect(containment(), SIGNAL(statusChanged(Plasma::Types::ItemStatus)), SLOT(statusChanged(Plasma::Types::ItemStatus))); connect(containment(), &Plasma::Applet::appletDeleted, this, [this] { //containment()->destroyed() is true only when the user deleted it //so the config is to be thrown away, not during shutdown if (containment()->destroyed()) { KConfigGroup views(m_corona->applicationConfig(), "PlasmaViews"); for (auto grp : views.groupList()) { if (grp.contains(QRegExp("Panel " + QString::number(containment()->id()) + "$"))) { qDebug() << "Panel" << containment()->id() << "removed by user"; views.deleteGroup(grp); } views.sync(); } } }); } void PanelView::statusChanged(Plasma::Types::ItemStatus status) { if (status == Plasma::Types::NeedsAttentionStatus) { showTemporarily(); } else if (status == Plasma::Types::AcceptingInputStatus) { KWindowSystem::forceActiveWindow(winId()); } else { restoreAutoHide(); } } void PanelView::showTemporarily() { setAutoHideEnabled(false); QTimer * t = new QTimer(this); t->setSingleShot(true); t->setInterval(3000); connect(t, &QTimer::timeout, this, &PanelView::restoreAutoHide); connect(t, &QTimer::timeout, t, &QObject::deleteLater); t->start(); } void PanelView::screenDestroyed(QObject* ) { // NOTE: this is overriding the screen destroyed slot, we need to do this because // otherwise Qt goes mental and starts moving our panels. See: // https://codereview.qt-project.org/#/c/88351/ // if(screen == this->m_screenToFollow) { // DO NOTHING, panels are moved by ::readaptToScreen // } } void PanelView::setupWaylandIntegration() { if (m_shellSurface) { // already setup return; } if (ShellCorona *c = qobject_cast(corona())) { using namespace KWayland::Client; PlasmaShell *interface = c->waylandPlasmaShellInterface(); if (!interface) { return; } Surface *s = Surface::fromWindow(this); if (!s) { return; } m_shellSurface = interface->createSurface(s, this); } } bool PanelView::edgeActivated() const { return m_visibilityMode == PanelView::AutoHide || m_visibilityMode == LetWindowsCover; } void PanelView::updateEnabledBorders() { Plasma::FrameSvg::EnabledBorders borders = Plasma::FrameSvg::AllBorders; switch (location()) { case Plasma::Types::TopEdge: borders &= ~Plasma::FrameSvg::TopBorder; break; case Plasma::Types::LeftEdge: borders &= ~Plasma::FrameSvg::LeftBorder; break; case Plasma::Types::RightEdge: borders &= ~Plasma::FrameSvg::RightBorder; break; case Plasma::Types::BottomEdge: borders &= ~Plasma::FrameSvg::BottomBorder; break; default: break; } if (x() <= m_screenToFollow->geometry().x()) { borders &= ~Plasma::FrameSvg::LeftBorder; } if (x() + width() >= m_screenToFollow->geometry().x() + m_screenToFollow->geometry().width()) { borders &= ~Plasma::FrameSvg::RightBorder; } if (y() <= m_screenToFollow->geometry().y()) { borders &= ~Plasma::FrameSvg::TopBorder; } if (y() + height() >= m_screenToFollow->geometry().y() + m_screenToFollow->geometry().height()) { borders &= ~Plasma::FrameSvg::BottomBorder; } if (m_enabledBorders != borders) { PanelShadows::self()->setEnabledBorders(this, borders); m_enabledBorders = borders; emit enabledBordersChanged(); } } #include "moc_panelview.cpp"