diff --git a/libtaskmanager/CMakeLists.txt b/libtaskmanager/CMakeLists.txt index c92567f6d..d65ec43fb 100644 --- a/libtaskmanager/CMakeLists.txt +++ b/libtaskmanager/CMakeLists.txt @@ -1,116 +1,117 @@ add_subdirectory(declarative) if(BUILD_TESTING) add_subdirectory(autotests) endif() set(taskmanager_LIB_SRCS abstracttasksmodel.cpp abstracttasksproxymodeliface.cpp abstractwindowtasksmodel.cpp activityinfo.cpp concatenatetasksproxymodel.cpp flattentaskgroupsproxymodel.cpp launchertasksmodel.cpp startuptasksmodel.cpp taskfilterproxymodel.cpp taskgroupingproxymodel.cpp tasksmodel.cpp tasktools.cpp virtualdesktopinfo.cpp waylandtasksmodel.cpp windowtasksmodel.cpp ) if (X11_FOUND) set(taskmanager_LIB_SRCS ${taskmanager_LIB_SRCS} xwindowsystemeventbatcher.cpp xwindowtasksmodel.cpp ) endif() add_library(taskmanager ${taskmanager_LIB_SRCS}) add_library(PW::LibTaskManager ALIAS taskmanager) generate_export_header(taskmanager) target_include_directories(taskmanager PUBLIC "$" "$") target_link_libraries(taskmanager PUBLIC Qt5::Core Qt5::Gui Qt5::Quick KF5::ItemModels PRIVATE Qt5::DBus KF5::Activities KF5::ConfigCore + KF5::I18n KF5::KIOCore KF5::KIOWidgets KF5::ProcessCore KF5::WaylandClient KF5::WindowSystem ) if (X11_FOUND) target_link_libraries(taskmanager PRIVATE Qt5::X11Extras KF5::IconThemes) endif() set_target_properties(taskmanager PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 6 EXPORT_NAME LibTaskManager) install(TARGETS taskmanager EXPORT libtaskmanagerLibraryTargets ${KDE_INSTALL_TARGETS_DEFAULT_ARGS} ) install(FILES abstracttasksmodel.h abstracttasksmodeliface.h abstracttasksproxymodeliface.h abstractwindowtasksmodel.h activityinfo.h concatenatetasksproxymodel.h flattentaskgroupsproxymodel.h launchertasksmodel.h startuptasksmodel.h taskfilterproxymodel.h taskgroupingproxymodel.h tasksmodel.h tasktools.h virtualdesktopinfo.h waylandtasksmodel.h windowtasksmodel.h ${CMAKE_CURRENT_BINARY_DIR}/taskmanager_export.h DESTINATION ${KDE_INSTALL_INCLUDEDIR}/taskmanager COMPONENT Devel ) if (X11_FOUND) install(FILES xwindowtasksmodel.h DESTINATION ${KDE_INSTALL_INCLUDEDIR}/taskmanager COMPONENT Devel ) endif() write_basic_config_version_file(${CMAKE_CURRENT_BINARY_DIR}/LibTaskManagerConfigVersion.cmake VERSION "${PROJECT_VERSION}" COMPATIBILITY AnyNewerVersion) set(CMAKECONFIG_INSTALL_DIR ${KDE_INSTALL_LIBDIR}/cmake/LibTaskManager) configure_package_config_file(LibTaskManagerConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/LibTaskManagerConfig.cmake" INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/LibTaskManagerConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/LibTaskManagerConfigVersion.cmake DESTINATION ${CMAKECONFIG_INSTALL_DIR}) install(EXPORT libtaskmanagerLibraryTargets NAMESPACE PW:: DESTINATION ${CMAKECONFIG_INSTALL_DIR} FILE LibTaskManagerLibraryTargets.cmake ) install(FILES taskmanagerrulesrc DESTINATION ${KDE_INSTALL_CONFDIR}) diff --git a/libtaskmanager/abstracttasksmodel.cpp b/libtaskmanager/abstracttasksmodel.cpp index 4952e0bc7..7d5e62c2d 100644 --- a/libtaskmanager/abstracttasksmodel.cpp +++ b/libtaskmanager/abstracttasksmodel.cpp @@ -1,135 +1,140 @@ /******************************************************************** 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 "abstracttasksmodel.h" #include namespace TaskManager { AbstractTasksModel::AbstractTasksModel(QObject *parent) : QAbstractListModel(parent) { } AbstractTasksModel::~AbstractTasksModel() { } QHash AbstractTasksModel::roleNames() const { QHash roles = QAbstractItemModel::roleNames(); QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("AdditionalRoles")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } return roles; } QModelIndex AbstractTasksModel::index(int row, int column, const QModelIndex &parent) const { return hasIndex(row, column, parent) ? createIndex(row, column, nullptr) : QModelIndex(); } void AbstractTasksModel::requestActivate(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestNewInstance(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { Q_UNUSED(index) Q_UNUSED(urls) } void AbstractTasksModel::requestClose(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestMove(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestResize(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestToggleMinimized(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestToggleMaximized(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestToggleKeepAbove(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestToggleKeepBelow(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestToggleFullScreen(const QModelIndex &index) { Q_UNUSED(index) } void AbstractTasksModel::requestToggleShaded(const QModelIndex &index) { Q_UNUSED(index) } -void AbstractTasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) +void AbstractTasksModel::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) +{ + Q_UNUSED(index) + Q_UNUSED(desktops) +} + +void AbstractTasksModel::requestNewVirtualDesktop(const QModelIndex &index) { Q_UNUSED(index) - Q_UNUSED(desktop) } void AbstractTasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { Q_UNUSED(index) Q_UNUSED(activities) } void AbstractTasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { Q_UNUSED(index) Q_UNUSED(geometry) Q_UNUSED(delegate) } } diff --git a/libtaskmanager/abstracttasksmodel.h b/libtaskmanager/abstracttasksmodel.h index ad12655b5..320a2e8b6 100644 --- a/libtaskmanager/abstracttasksmodel.h +++ b/libtaskmanager/abstracttasksmodel.h @@ -1,287 +1,301 @@ /******************************************************************** 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 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. */ + WinIdList, /**< NOTE: On Wayland, these ids are only useful within the same process. On X11, they are global window ids. */ 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. */ HasLauncher, /**< A launcher exists for this task. Only implemented by TasksModel, not by either the single-type or munging tasks models. */ IsGroupParent, /**< This is a parent item for a group of child tasks. */ ChildCount, /**< The number of tasks in this group. */ 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). */ + IsVirtualDesktopsChangeable, /**< requestVirtualDesktop (see below) available. */ + VirtualDesktops, /**< Virtual desktops 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 should not be shown in a 'task bar' user interface. */ SkipPager, /**< Task should not to be shown in a 'pager' user interface. */ AppPid, /**< Application Process ID. This is provided best-effort, and may not be what you expect: For window tasks owned by processes started from e.g. kwin_wayland, it would be the process id of kwin itself. DO NOT use this for destructive actions such as closing the application. The intended use case is to try and (smartly) gather more information about the task when needed. */ }; Q_ENUM(AdditionalRoles) explicit AbstractTasksModel(QObject *parent = nullptr); ~AbstractTasksModel() override; QHash roleNames() const override; 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. **/ 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. **/ 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. **/ void requestOpenUrls(const QModelIndex &index, const QList &urls) override; /** * Request the task at the given index be closed. * * This base implementation does nothing. * * @param index An index in this tasks model. **/ 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. **/ 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. **/ 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. **/ 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. **/ 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. **/ 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. **/ 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. **/ 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. **/ void requestToggleShaded(const QModelIndex &index) override; /** - * Request moving the task at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktops, + * leaving any other desktops. * - * This is meant for tasks that have an associated window, and may be - * a no-op when there is no window. + * On Wayland, virtual desktop ids are QStrings. On X11, they are uint >0. * - * This base implementation does nothing. + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. * - * @param index An index in this tasks model. - * @param desktop A virtual desktop number. + * On X11, a window can only be on one or all virtual desktops. Therefore, only the + * first list entry is actually used. + * + * On X11, the id 0 has a special meaning: The window is entered on all virtual + * desktops in the session. + * + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids. + **/ + void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) override; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. + * + * @param index An index in this window tasks model. **/ - void requestVirtualDesktop(const QModelIndex &index, qint32 desktop) override; + void requestNewVirtualDesktop(const QModelIndex &index) 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. **/ 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. **/ void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; }; } #endif diff --git a/libtaskmanager/abstracttasksmodeliface.h b/libtaskmanager/abstracttasksmodeliface.h index 788110177..d4d6fc8ae 100644 --- a/libtaskmanager/abstracttasksmodeliface.h +++ b/libtaskmanager/abstracttasksmodeliface.h @@ -1,203 +1,219 @@ /******************************************************************** 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 ABSTRACTTASKSMODELIFACE_H #define ABSTRACTTASKSMODELIFACE_H #include #include "taskmanager_export.h" namespace TaskManager { /** * @short Pure virtual method interface for tasks model implementations. * * This is the pure virtual method interface implemented by AbstractTasksModel, * as well as other model classes in this library which cannot inherit from * AbstractTasksModel. * * @author Eike Hein **/ class TASKMANAGER_EXPORT AbstractTasksModelIface { public: virtual ~AbstractTasksModelIface() {} /** * Request activation of the task at the given index. Implementing 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. * * @param index An index in this tasks model. **/ virtual void requestActivate(const QModelIndex &index) = 0; /** * Request an additional instance of the application backing the task at * the given index. * * @param index An index in this tasks model. **/ virtual void requestNewInstance(const QModelIndex &index) = 0; /** * Requests to open the given URLs with the application backing the task * at the given index. * * @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) = 0; /** * Request the task at the given index be closed. * * @param index An index in this tasks model. **/ virtual void requestClose(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestMove(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestResize(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestToggleMinimized(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestToggleMaximized(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestToggleKeepAbove(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestToggleKeepBelow(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestToggleFullScreen(const QModelIndex &index) = 0; /** * 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. * * @param index An index in this tasks model. **/ virtual void requestToggleShaded(const QModelIndex &index) = 0; /** - * Request moving the task at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktops, + * leaving any other desktops. * - * This is meant for tasks that have an associated window, and may be - * a no-op when there is no window. + * On Wayland, virtual desktop ids are QStrings. On X11, they are uint >0. * - * @param index An index in this tasks model. - * @param desktop A virtual desktop number. + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. + * + * On X11, a window can only be on one or all virtual desktops. Therefore, only the + * first list entry is actually used. + * + * On X11, the id 0 has a special meaning: The window is entered on all virtual + * desktops in the session. + * + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids. + **/ + virtual void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) = 0; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. + * + * @param index An index in this window tasks model. **/ - virtual void requestVirtualDesktop(const QModelIndex &index, qint32 desktop = -1) = 0; + virtual void requestNewVirtualDesktop(const QModelIndex &index) = 0; /** * Request moving the task at the given index to the specified virtual * activities. * * This is meant for tasks that have an associated window, and may be * a no-op when there is no window. * * @param index An index in this tasks model. * @param activities The new list of activities. **/ virtual void requestActivities(const QModelIndex &index, const QStringList &activities) = 0; /** * 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. * * FIXME: Doesn't deal with the long-standing problem of multiple * delegates in multiple applets. * * @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) = 0; }; } #endif diff --git a/libtaskmanager/abstracttasksproxymodeliface.cpp b/libtaskmanager/abstracttasksproxymodeliface.cpp index 2f85d0813..2ece29301 100644 --- a/libtaskmanager/abstracttasksproxymodeliface.cpp +++ b/libtaskmanager/abstracttasksproxymodeliface.cpp @@ -1,239 +1,252 @@ /******************************************************************** Copyright 2016 David Edmundson 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 "abstracttasksproxymodeliface.h" #include #include namespace TaskManager { void AbstractTasksProxyModelIface::requestActivate(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestActivate(sourceIndex); } } void AbstractTasksProxyModelIface::requestNewInstance(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestNewInstance(sourceIndex); } } void AbstractTasksProxyModelIface::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestOpenUrls(sourceIndex, urls); } } void AbstractTasksProxyModelIface::requestClose(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestClose(sourceIndex); } } void AbstractTasksProxyModelIface::requestMove(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestMove(sourceIndex); } } void AbstractTasksProxyModelIface::requestResize(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestResize(sourceIndex); } } void AbstractTasksProxyModelIface::requestToggleMinimized(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestToggleMinimized(sourceIndex); } } void AbstractTasksProxyModelIface::requestToggleMaximized(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestToggleMaximized(sourceIndex); } } void AbstractTasksProxyModelIface::requestToggleKeepAbove(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestToggleKeepAbove(sourceIndex); } } void AbstractTasksProxyModelIface::requestToggleKeepBelow(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestToggleKeepBelow(sourceIndex); } } void AbstractTasksProxyModelIface::requestToggleFullScreen(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestToggleFullScreen(sourceIndex); } } void AbstractTasksProxyModelIface::requestToggleShaded(const QModelIndex &index) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestToggleShaded(sourceIndex); } } -void AbstractTasksProxyModelIface::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) +void AbstractTasksProxyModelIface::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { - const_cast(m)->requestVirtualDesktop(sourceIndex, desktop); + const_cast(m)->requestVirtualDesktops(sourceIndex, desktops); + } +} + +void AbstractTasksProxyModelIface::requestNewVirtualDesktop(const QModelIndex &index) +{ + if (!index.isValid()) { + return; + } + + const QModelIndex &sourceIndex = mapIfaceToSource(index); + const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); + + if (m) { + const_cast(m)->requestNewVirtualDesktop(sourceIndex); } } void AbstractTasksProxyModelIface::requestActivities(const QModelIndex &index, const QStringList &activities) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestActivities(sourceIndex, activities); } } - void AbstractTasksProxyModelIface::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { if (!index.isValid()) { return; } const QModelIndex &sourceIndex = mapIfaceToSource(index); const AbstractTasksModelIface *m = dynamic_cast(sourceIndex.model()); if (m) { const_cast(m)->requestPublishDelegateGeometry(sourceIndex, geometry, delegate); } } } diff --git a/libtaskmanager/abstracttasksproxymodeliface.h b/libtaskmanager/abstracttasksproxymodeliface.h index 84467b900..810329bb9 100644 --- a/libtaskmanager/abstracttasksproxymodeliface.h +++ b/libtaskmanager/abstracttasksproxymodeliface.h @@ -1,209 +1,225 @@ /******************************************************************** 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 ABSTRACTTASKSPROXYMODELIFACE_H #define ABSTRACTTASKSPROXYMODELIFACE_H #include #include "taskmanager_export.h" #include "abstracttasksmodeliface.h" namespace TaskManager { /** * @short Pure method interface for tasks model implementations. * * This is the pure method interface implemented by AbstractTasksModel, * as well as other model classes in this library which cannot inherit from * AbstractTasksModel. * * @author Eike Hein **/ class TASKMANAGER_EXPORT AbstractTasksProxyModelIface : public AbstractTasksModelIface { public: ~AbstractTasksProxyModelIface() override {} /** * Request activation of the task at the given index. Implementing 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. * * @param index An index in this tasks model. **/ void requestActivate(const QModelIndex &index) override; /** * Request an additional instance of the application backing the task * at the given index. * * @param index An index in this tasks model. **/ void requestNewInstance(const QModelIndex &index) override; /** * Requests to open the given URLs with the application backing the task * at the given index. * * @param index An index in this tasks model. * @param urls The URLs to be passed to the application. **/ void requestOpenUrls(const QModelIndex &index, const QList &urls) override; /** * Request the task at the given index be closed. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ void requestToggleShaded(const QModelIndex &index) override; /** - * Request moving the task at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktops, + * leaving any other desktops. * - * This is meant for tasks that have an associated window, and may be - * a no-op when there is no window. + * On Wayland, virtual desktop ids are QStrings. On X11, they are uint >0. * - * @param index An index in this tasks model. - * @param desktop A virtual desktop number. + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. + * + * On X11, a window can only be on one or all virtual desktops. Therefore, only the + * first list entry is actually used. + * + * On X11, the id 0 has a special meaning: The window is entered on all virtual + * desktops in the session. + * + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids. + **/ + void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) override; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. + * + * @param index An index in this window tasks model. **/ - void requestVirtualDesktop(const QModelIndex &index, qint32 desktop = -1) override; + void requestNewVirtualDesktop(const QModelIndex &index) 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. * * @param index An index in this tasks model. * @param activities The new list of activities. **/ 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. * * @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. **/ void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; protected: /* * Map the passed QModelIndex to the source model index * so that AbstractTasksModelIface methods can be passed on * Subclasses should override this. */ virtual QModelIndex mapIfaceToSource(const QModelIndex &index) const = 0; }; } #endif diff --git a/libtaskmanager/launchertasksmodel.cpp b/libtaskmanager/launchertasksmodel.cpp index defcd8aea..b31e9b74c 100644 --- a/libtaskmanager/launchertasksmodel.cpp +++ b/libtaskmanager/launchertasksmodel.cpp @@ -1,607 +1,609 @@ /******************************************************************** 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 "launchertasksmodel.h" #include "tasktools.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if HAVE_X11 #include #endif #include "launchertasksmodel_p.h" namespace TaskManager { typedef QSet ActivitiesSet; template inline bool isOnAllActivities(const ActivitiesCollection &activities) { return activities.isEmpty() || activities.contains(NULL_UUID); } class Q_DECL_HIDDEN LauncherTasksModel::Private { public: Private(LauncherTasksModel *q); KActivities::Consumer activitiesConsumer; QList launchersOrder; QHash activitiesForLauncher; inline void setActivitiesForLauncher(const QUrl &url, const ActivitiesSet &activities) { if (activities.size() == activitiesConsumer.activities().size()) { activitiesForLauncher[url] = { NULL_UUID }; } else { activitiesForLauncher[url] = activities; } } QHash appDataCache; QTimer sycocaChangeTimer; void init(); AppData appData(const QUrl &url); bool requestAddLauncherToActivities(const QUrl &_url, const QStringList &activities); bool requestRemoveLauncherFromActivities(const QUrl &_url, const QStringList &activities); private: LauncherTasksModel *q; }; LauncherTasksModel::Private::Private(LauncherTasksModel *q) : q(q) { } void LauncherTasksModel::Private::init() { sycocaChangeTimer.setSingleShot(true); sycocaChangeTimer.setInterval(100); QObject::connect(&sycocaChangeTimer, &QTimer::timeout, q, [this]() { if (!launchersOrder.count()) { return; } appDataCache.clear(); // Emit changes of all roles satisfied from app data cache. q->dataChanged(q->index(0, 0), q->index(launchersOrder.count() - 1, 0), QVector{Qt::DisplayRole, Qt::DecorationRole, AbstractTasksModel::AppId, AbstractTasksModel::AppName, AbstractTasksModel::GenericName, AbstractTasksModel::LauncherUrl, AbstractTasksModel::LauncherUrlWithoutIcon}); } ); 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(); } } ); } AppData LauncherTasksModel::Private::appData(const QUrl &url) { const auto &it = appDataCache.constFind(url); if (it != appDataCache.constEnd()) { return *it; } const AppData &data = appDataFromUrl(url, QIcon::fromTheme(QLatin1String("unknown"))); appDataCache.insert(url, data); return data; } bool LauncherTasksModel::Private::requestAddLauncherToActivities(const QUrl &_url, const QStringList &_activities) { // isValid() for the passed-in URL might return true if it was // constructed in TolerantMode, but we want to reject invalid URLs. QUrl url(_url.toString(), QUrl::StrictMode); const auto activities = ActivitiesSet::fromList(_activities); if (url.isEmpty() || !url.isValid()) { return false; } if (url.isLocalFile() && KDesktopFile::isDesktopFile(url.toLocalFile())) { KDesktopFile f(url.toLocalFile()); const KService::Ptr service = KService::serviceByStorageId(f.fileName()); // Resolve to non-absolute menuId-based URL if possible. if (service) { const QString &menuId = service->menuId(); if (!menuId.isEmpty()) { url = QUrl(QStringLiteral("applications:") + menuId); } } } // Merge duplicates int row = -1; foreach(const QUrl &launcher, launchersOrder) { ++row; if (launcherUrlsMatch(url, launcher, IgnoreQueryItems)) { ActivitiesSet newActivities; // Use the key we established equivalence to ('launcher'). if (!activitiesForLauncher.contains(launcher)) { // If we don't have the activities assigned to this url // for some reason newActivities = activities; } else { if (isOnAllActivities(activities)) { // If the new list is empty, or has a null uuid, this // launcher should be on all activities newActivities = ActivitiesSet { NULL_UUID }; } else if (isOnAllActivities(activitiesForLauncher[launcher])) { // If we have been on all activities before, and we have // been asked to be on a specific one, lets make an // exception - we will set the activities to exactly // what we have been asked newActivities = activities; } else { newActivities += activities; newActivities += activitiesForLauncher[launcher]; } } if (newActivities != activitiesForLauncher[launcher]) { setActivitiesForLauncher(launcher, newActivities); emit q->dataChanged( q->index(row, 0), q->index(row, 0)); emit q->launcherListChanged(); return true; } return false; } } // This is a new one const auto count = launchersOrder.count(); q->beginInsertRows(QModelIndex(), count, count); setActivitiesForLauncher(url, activities); launchersOrder.append(url); q->endInsertRows(); emit q->launcherListChanged(); return true; } bool LauncherTasksModel::Private::requestRemoveLauncherFromActivities(const QUrl &url, const QStringList &activities) { for (int row = 0; row < launchersOrder.count(); ++row) { const QUrl &launcher = launchersOrder.at(row); if (launcherUrlsMatch(url, launcher, IgnoreQueryItems) || launcherUrlsMatch(url, appData(launcher).url, IgnoreQueryItems)) { const auto currentActivities = activitiesForLauncher[url]; ActivitiesSet newActivities; bool remove = false; bool update = false; if (isOnAllActivities(currentActivities)) { // We are currently on all activities. // Should we go away, or just remove from the current one? if (isOnAllActivities(activities)) { remove = true; } else { for (const auto& activity: activitiesConsumer.activities()) { if (!activities.contains(activity)) { newActivities << activity; } else { update = true; } } } } else if (isOnAllActivities(activities)) { remove = true; } else { // We weren't on all activities, just remove those that // we were on for (const auto& activity: currentActivities) { if (!activities.contains(activity)) { newActivities << activity; } } if (newActivities.isEmpty()) { remove = true; } else { update = true; } } if (remove) { q->beginRemoveRows(QModelIndex(), row, row); launchersOrder.removeAt(row); activitiesForLauncher.remove(url); appDataCache.remove(launcher); q->endRemoveRows(); } else if (update) { setActivitiesForLauncher(url, newActivities); emit q->dataChanged( q->index(row, 0), q->index(row, 0)); } if (remove || update) { emit q->launcherListChanged(); return true; } } } return false; } LauncherTasksModel::LauncherTasksModel(QObject *parent) : AbstractTasksModel(parent) , d(new Private(this)) { d->init(); } LauncherTasksModel::~LauncherTasksModel() { } QVariant LauncherTasksModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->launchersOrder.count()) { return QVariant(); } const QUrl &url = d->launchersOrder.at(index.row()); const AppData &data = d->appData(url); if (role == Qt::DisplayRole) { return data.name; } else if (role == Qt::DecorationRole) { return data.icon; } else if (role == AppId) { return data.id; } else if (role == AppName) { return data.name; } else if (role == GenericName) { return data.genericName; } else if (role == LauncherUrl) { // Take resolved URL from cache. return data.url; } else if (role == LauncherUrlWithoutIcon) { // Take resolved URL from cache. QUrl url = data.url; if (url.hasQuery()) { QUrlQuery query(url); query.removeQueryItem(QLatin1String("iconData")); url.setQuery(query); } return url; } else if (role == IsLauncher) { return true; + } else if (role == IsVirtualDesktopsChangeable) { + return false; } else if (role == IsOnAllVirtualDesktops) { return true; } else if (role == Activities) { return QStringList(d->activitiesForLauncher[url].toList()); } return QVariant(); } int LauncherTasksModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->launchersOrder.count(); } QStringList LauncherTasksModel::launcherList() const { // Serializing the launchers QStringList result; for (const auto &launcher: d->launchersOrder) { const auto &activities = d->activitiesForLauncher[launcher]; QString serializedLauncher; if (isOnAllActivities(activities)) { serializedLauncher = launcher.toString(); } else { serializedLauncher = "[" + d->activitiesForLauncher[launcher].toList().join(",") + "]\n" + launcher.toString(); } result << serializedLauncher; } return result; } void LauncherTasksModel::setLauncherList(const QStringList &serializedLaunchers) { // Clearing everything QList newLaunchersOrder; QHash newActivitiesForLauncher; // Loading the activity to launchers map QHash> launchersForActivitiesCandidates; for (const auto& serializedLauncher: serializedLaunchers) { QStringList _activities; QUrl url; std::tie(url, _activities) = deserializeLauncher(serializedLauncher); auto activities = ActivitiesSet::fromList(_activities); // Is url is not valid, ignore it if (!url.isValid()) continue; // If we have a null uuid, it means we are on all activities // and we should contain only the null uuid if (isOnAllActivities(activities)) { activities = { NULL_UUID }; } else { // Filter out invalid activities const auto allActivities = d->activitiesConsumer.activities(); ActivitiesSet validActivities; for (const auto& activity: activities) { if (allActivities.contains(activity)) { validActivities << activity; } } if (validActivities.isEmpty()) { // If all activities that had this launcher are // removed, we are killing the launcher as well continue; } activities = validActivities; } // Is the url a duplicate? const auto location = std::find_if(newLaunchersOrder.begin(), newLaunchersOrder.end(), [&url] (const QUrl &item) { return launcherUrlsMatch(url, item, IgnoreQueryItems); }); if (location != newLaunchersOrder.end()) { // It is a duplicate url = *location; } else { // It is not a duplicate, we need to add it // to the list of registered launchers newLaunchersOrder << url; } if (!newActivitiesForLauncher.contains(url)) { // This is the first time we got this url newActivitiesForLauncher[url] = activities; } else if (newActivitiesForLauncher[url].contains(NULL_UUID)) { // Do nothing, we are already on all activities } else if (activities.contains(NULL_UUID)) { newActivitiesForLauncher[url] = { NULL_UUID }; } else { // We are not on all activities, append the new ones newActivitiesForLauncher[url] += activities; } } if (newLaunchersOrder != d->launchersOrder || newActivitiesForLauncher != d->activitiesForLauncher) { // Common case optimization: If the list changed but its size // did not (e.g. due to reordering by a user of this model), // just clear the caches and announce new data instead of // resetting. if (newLaunchersOrder.count() == d->launchersOrder.count()) { d->appDataCache.clear(); std::swap(newLaunchersOrder, d->launchersOrder); std::swap(newActivitiesForLauncher, d->activitiesForLauncher); emit dataChanged( index(0, 0), index(d->launchersOrder.count() - 1, 0)); } else { beginResetModel(); std::swap(newLaunchersOrder, d->launchersOrder); std::swap(newActivitiesForLauncher, d->activitiesForLauncher); d->appDataCache.clear(); endResetModel(); } emit launcherListChanged(); } } bool LauncherTasksModel::requestAddLauncher(const QUrl &url) { return d->requestAddLauncherToActivities(url, { NULL_UUID }); } bool LauncherTasksModel::requestRemoveLauncher(const QUrl &url) { return d->requestRemoveLauncherFromActivities(url, { NULL_UUID }); } bool LauncherTasksModel::requestAddLauncherToActivity(const QUrl &url, const QString &activity) { return d->requestAddLauncherToActivities(url, { activity }); } bool LauncherTasksModel::requestRemoveLauncherFromActivity(const QUrl &url, const QString &activity) { return d->requestRemoveLauncherFromActivities(url, { activity }); } QStringList LauncherTasksModel::launcherActivities(const QUrl &_url) const { const auto position = launcherPosition(_url); if (position == -1) { // If we do not have this launcher, return an empty list return {}; } else { const auto url = d->launchersOrder.at(position); // If the launcher is on all activities, return a null uuid return d->activitiesForLauncher.contains(url) ? d->activitiesForLauncher[url].toList() : QStringList { NULL_UUID }; } } int LauncherTasksModel::launcherPosition(const QUrl &url) const { for (int i = 0; i < d->launchersOrder.count(); ++i) { if (launcherUrlsMatch(url, d->launchersOrder.at(i), IgnoreQueryItems)) { return i; } } return -1; } void LauncherTasksModel::requestActivate(const QModelIndex &index) { requestNewInstance(index); } void LauncherTasksModel::requestNewInstance(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->launchersOrder.count()) { return; } runApp(d->appData(d->launchersOrder.at(index.row()))); } void LauncherTasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->launchersOrder.count() || urls.isEmpty()) { return; } const QUrl &url = d->launchersOrder.at(index.row()); quint32 timeStamp = 0; #if HAVE_X11 if (KWindowSystem::isPlatformX11()) { timeStamp = QX11Info::appUserTime(); } #endif KService::Ptr service; if (url.scheme() == QLatin1String("applications")) { service = KService::serviceByMenuId(url.path()); } else if (url.scheme() == QLatin1String("preferred")) { service = KService::serviceByStorageId(defaultApplication(url)); } else { service = KService::serviceByDesktopPath(url.toLocalFile()); } if (!service || !service->isApplication()) { return; } KRun::runApplication(*service, urls, nullptr, KRun::RunFlags(), QString(), KStartupInfo::createNewStartupIdForTimestamp(timeStamp)); KActivities::ResourceInstance::notifyAccessed(QUrl(QStringLiteral("applications:") + service->storageId()), QStringLiteral("org.kde.libtaskmanager")); } } diff --git a/libtaskmanager/startuptasksmodel.cpp b/libtaskmanager/startuptasksmodel.cpp index 595ad7c43..6a5401ced 100644 --- a/libtaskmanager/startuptasksmodel.cpp +++ b/libtaskmanager/startuptasksmodel.cpp @@ -1,289 +1,291 @@ /******************************************************************** 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 "startuptasksmodel.h" #include #include #include #include #include #include #include #include #include namespace TaskManager { class Q_DECL_HIDDEN StartupTasksModel::Private { public: Private(StartupTasksModel *q); KDirWatch* configWatcher = nullptr; KStartupInfo *startupInfo = nullptr; QVector startups; QHash startupData; QHash launcherUrls; void init(); void loadConfig(); QUrl launcherUrl(const KStartupInfoData &data); private: StartupTasksModel *q; }; StartupTasksModel::Private::Private(StartupTasksModel *q) : q(q) { } void StartupTasksModel::Private::init() { configWatcher = new KDirWatch(q); configWatcher->addFile(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QLatin1String("/klaunchrc")); QObject::connect(configWatcher, &KDirWatch::dirty, [this] { loadConfig(); }); QObject::connect(configWatcher, &KDirWatch::created, [this] { loadConfig(); }); QObject::connect(configWatcher, &KDirWatch::deleted, [this] { loadConfig(); }); loadConfig(); } void StartupTasksModel::Private::loadConfig() { const KConfig _c("klaunchrc"); KConfigGroup c(&_c, "FeedbackStyle"); if (!c.readEntry("TaskbarButton", true)) { delete startupInfo; startupInfo = nullptr; q->beginResetModel(); startups.clear(); startupData.clear(); q->endResetModel(); return; } if (!startupInfo) { startupInfo = new KStartupInfo(KStartupInfo::CleanOnCantDetect, q); QObject::connect(startupInfo, &KStartupInfo::gotNewStartup, q, [this](const KStartupInfoId &id, const KStartupInfoData &data) { if (startups.contains(id)) { return; } const QString appId = data.applicationId(); const QString bin = data.bin(); foreach(const KStartupInfoData &known, startupData) { // Reject if we already have a startup notification for this app. if (known.applicationId() == appId && known.bin() == bin) { return; } } const int count = startups.count(); q->beginInsertRows(QModelIndex(), count, count); startups.append(id); startupData.insert(id.id(), data); launcherUrls.insert(id.id(), launcherUrl(data)); q->endInsertRows(); } ); QObject::connect(startupInfo, &KStartupInfo::gotRemoveStartup, q, [this](const KStartupInfoId &id) { // The order in which startups are cancelled and corresponding // windows appear is not reliable. Add some grace time to make // an overlap more likely, giving a proxy some time to arbitrate // between the two. QTimer::singleShot(500, [this, id]() { const int row = startups.indexOf(id); if (row != -1) { q->beginRemoveRows(QModelIndex(), row, row); startups.removeAt(row); startupData.remove(id.id()); launcherUrls.remove(id.id()); q->endRemoveRows(); } } ); } ); QObject::connect(startupInfo, &KStartupInfo::gotStartupChange, q, [this](const KStartupInfoId &id, const KStartupInfoData &data) { const int row = startups.indexOf(id); if (row != -1) { startupData.insert(id.id(), data); launcherUrls.insert(id.id(), launcherUrl(data)); QModelIndex idx = q->index(row); emit q->dataChanged(idx, idx); } } ); } c = KConfigGroup(&_c, "TaskbarButtonSettings"); startupInfo->setTimeout(c.readEntry("Timeout", 5)); } QUrl StartupTasksModel::Private::launcherUrl(const KStartupInfoData &data) { QUrl launcherUrl; KService::List services; QString appId = data.applicationId(); // Try to match via desktop filename ... if (!appId.isEmpty() && appId.endsWith(QLatin1String(".desktop"))) { if (appId.startsWith(QLatin1String("/"))) { // Even if we have an absolute path, try resolving to a service first (Bug 385594) KService::Ptr service = KService::serviceByDesktopPath(appId); if (!service) { // No luck, just return it verbatim launcherUrl = QUrl::fromLocalFile(appId); return launcherUrl; } // Fall-through to menuId() handling below services = {service}; } else { if (appId.endsWith(QLatin1String(".desktop"))) { appId = appId.mid(appId.length() - 8); } services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ DesktopEntryName)").arg(appId)); } } const QString wmClass = data.WMClass(); // Try StartupWMClass. if (services.empty() && !wmClass.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ StartupWMClass)").arg(wmClass)); } const QString name = data.findName(); // Try via name ... if (services.empty() && !name.isEmpty()) { services = KServiceTypeTrader::self()->query(QStringLiteral("Application"), QStringLiteral("exist Exec and ('%1' =~ Name)").arg(name)); } if (!services.empty()) { const QString &menuId = services.at(0)->menuId(); // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (!menuId.isEmpty()) { return QUrl(QStringLiteral("applications:") + menuId); } QString path = services.at(0)->entryPath(); if (path.isEmpty()) { path = services.at(0)->exec(); } if (!path.isEmpty()) { launcherUrl = QUrl::fromLocalFile(path); } } return launcherUrl; } StartupTasksModel::StartupTasksModel(QObject *parent) : AbstractTasksModel(parent) , d(new Private(this)) { d->init(); } StartupTasksModel::~StartupTasksModel() { } QVariant StartupTasksModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->startups.count()) { return QVariant(); } const QByteArray &id = d->startups.at(index.row()).id(); if (!d->startupData.contains(id)) { return QVariant(); } const KStartupInfoData &data = d->startupData.value(id); if (role == Qt::DisplayRole) { return data.findName(); } else if (role == Qt::DecorationRole) { return QIcon::fromTheme(data.findIcon(), QIcon::fromTheme(QLatin1String("unknown"))); } else if (role == AppId) { QString idFromPath = QUrl::fromLocalFile(data.applicationId()).fileName(); if (idFromPath.endsWith(QLatin1String(".desktop"))) { idFromPath = idFromPath.left(idFromPath.length() - 8); } return idFromPath; } else if (role == AppName) { return data.findName(); } else if (role == LauncherUrl || role == LauncherUrlWithoutIcon) { return d->launcherUrls.value(id); } else if (role == IsStartup) { return true; - } else if (role == VirtualDesktop) { - return data.desktop(); + } else if (role == IsVirtualDesktopsChangeable) { + return false; + } else if (role == VirtualDesktops) { + return QVariantList() << QVariant(data.desktop()); } else if (role == IsOnAllVirtualDesktops) { return (data.desktop() == 0); } return QVariant(); } int StartupTasksModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->startups.count(); } void StartupTasksModel::requestNewInstance(const QModelIndex &index) { Q_UNUSED(index) // FIXME Implement. } } diff --git a/libtaskmanager/taskfilterproxymodel.cpp b/libtaskmanager/taskfilterproxymodel.cpp index 49afe5538..071c1a238 100644 --- a/libtaskmanager/taskfilterproxymodel.cpp +++ b/libtaskmanager/taskfilterproxymodel.cpp @@ -1,320 +1,315 @@ /******************************************************************** 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" #include "launchertasksmodel_p.h" namespace TaskManager { class Q_DECL_HIDDEN TaskFilterProxyModel::Private { public: Private(TaskFilterProxyModel *q); AbstractTasksModelIface *sourceTasksModel = nullptr; - uint virtualDesktop = 0; + QVariant virtualDesktop; 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; }; TaskFilterProxyModel::Private::Private(TaskFilterProxyModel *) { } 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 +QVariant TaskFilterProxyModel::virtualDesktop() const { return d->virtualDesktop; } -void TaskFilterProxyModel::setVirtualDesktop(uint virtualDesktop) +void TaskFilterProxyModel::setVirtualDesktop(const QVariant &desktop) { - if (d->virtualDesktop != virtualDesktop) { - d->virtualDesktop = virtualDesktop; + if (d->virtualDesktop != desktop) { + d->virtualDesktop = desktop; 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::acceptsRow(int sourceRow) const { const QModelIndex &sourceIdx = sourceModel()->index(sourceRow, 0); if (!sourceIdx.isValid()) { return false; } // 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 (d->filterByVirtualDesktop && !d->virtualDesktop.isNull()) { if (!sourceIdx.data(AbstractTasksModel::IsOnAllVirtualDesktops).toBool() && (!d->demandingAttentionSkipsFilters || !sourceIdx.data(AbstractTasksModel::IsDemandingAttention).toBool())) { - const QVariant &virtualDesktop = sourceIdx.data(AbstractTasksModel::VirtualDesktop); + const QVariantList &virtualDesktops = sourceIdx.data(AbstractTasksModel::VirtualDesktops).toList(); - if (!virtualDesktop.isNull()) { - bool ok = false; - const uint i = virtualDesktop.toUInt(&ok); - - if (ok && i != d->virtualDesktop) { - return false; - } + if (!virtualDesktops.isEmpty() && !virtualDesktops.contains(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 (!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(NULL_UUID) && !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; } bool TaskFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { Q_UNUSED(sourceParent) return acceptsRow(sourceRow); } } diff --git a/libtaskmanager/taskfilterproxymodel.h b/libtaskmanager/taskfilterproxymodel.h index b54bad521..62e119dac 100644 --- a/libtaskmanager/taskfilterproxymodel.h +++ b/libtaskmanager/taskfilterproxymodel.h @@ -1,304 +1,303 @@ /******************************************************************** 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(QVariant 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 = nullptr); ~TaskFilterProxyModel() override; 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). + * The id of the virtual desktop used in filtering by virtual + * desktop. Usually set to the id of the current virtual desktop. + * Defaults to empty. * * @see setVirtualDesktop * @returns the number of the virtual desktop used in filtering. **/ - uint virtualDesktop() const; + QVariant virtualDesktop() const; /** - * Set the number of the virtual desktop to use in filtering by virtual + * Set the id 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. + * If set to an empty id, filtering by virtual desktop is disabled. * * @see virtualDesktop - * @param virtualDesktop A virtual desktop number. + * @param desktop A virtual desktop id (QString on Wayland; uint >0 on X11). **/ - void setVirtualDesktop(uint virtualDesktop); + void setVirtualDesktop(const QVariant &desktop = QVariant()); /** * 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 should be omitted from 'task bars' should be * filtered. Defaults to @c true. * * @see setFilterSkipTaskbar * @returns @c true if tasks which should not be on the 'task bar' * should be filtered. **/ bool filterSkipTaskbar() const; /** * Set whether tasks which should be omitted from 'task bars' should be * filtered. * * @see filterSkipTaskbar * @param filter Whether tasks whichs should not be on the 'task bar' * should be filtered. **/ void setFilterSkipTaskbar(bool filter); /** * Whether tasks which should be omitted from 'pagers' should be * filtered. Defaults to @c true. * * @see setFilterSkipPager * @returns @c true if tasks which should not be on the 'pager' should * be filtered. **/ bool filterSkipPager() const; /** * Set whether tasks which should be omitted from 'pagers' should be * filtered. * * @see filterSkipPager * @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); /** * Returns whether the filter model accepts this source row. * * @param int A row in the source model. */ bool acceptsRow(int sourceRow) const; 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 override; private: class Private; QScopedPointer d; }; } #endif diff --git a/libtaskmanager/taskgroupingproxymodel.cpp b/libtaskmanager/taskgroupingproxymodel.cpp index ab84978ba..8ef632206 100644 --- a/libtaskmanager/taskgroupingproxymodel.cpp +++ b/libtaskmanager/taskgroupingproxymodel.cpp @@ -1,1214 +1,1241 @@ /******************************************************************** 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 Q_DECL_HIDDEN TaskGroupingProxyModel::Private { public: Private(TaskGroupingProxyModel *q); ~Private(); 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) { } TaskGroupingProxyModel::Private::~Private() { qDeleteAll(rowMap); } 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(new 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); delete rowMap.takeAt(j); 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); 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()); delete rowMap.takeAt(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) { QVector *sourceRows = rowMap.at(i); QMutableVectorIterator it(*sourceRows); while (it.hasNext()) { it.next(); if (it.value() >= anchor) { it.setValue(it.value() + delta); } } } } void TaskGroupingProxyModel::Private::rebuildMap() { qDeleteAll(rowMap); rowMap.clear(); const int rows = q->sourceModel()->rowCount(); rowMap.reserve(rows); for (int i = 0; i < rows; ++i) { rowMap.append(new 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); delete rowMap.takeAt(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::LauncherUrlWithoutIcon).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); if (!silent) { const int newIndex = rowMap.at(i)->count(); if (newIndex == 1) { q->beginInsertRows(parent, 0, 1); } else { q->beginInsertRows(parent, newIndex, newIndex); } } rowMap[i]->append(sourceIndex.row()); if (!silent) { q->endInsertRows(); 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); delete rowMap.takeAt(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); 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(new 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, d->rowMap.at(parent.row())); } if (row < d->rowMap.count()) { return createIndex(row, column, nullptr); } return QModelIndex(); } QModelIndex TaskGroupingProxyModel::parent(const QModelIndex &child) const { if (child.internalPointer() == nullptr) { return QModelIndex(); } else { const int parentRow = d->rowMap.indexOf(static_cast *>(child.internalPointer())); if (parentRow != -1) { return index(parentRow, 0); } // If we were asked to find the parent for an internalPointer we can't // locate, we have corrupted data: This should not happen. Q_ASSERT(parentRow != -1); } return QModelIndex(); } 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) { 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) { + } else if (role == AbstractTasksModel::WinIdList) { QVariantList winIds; for (int i = 0; i < rowCount(proxyIndex); ++i) { - winIds.append(proxyIndex.child(i, 0).data(AbstractTasksModel::LegacyWinIdList).toList()); + winIds.append(proxyIndex.child(i, 0).data(AbstractTasksModel::WinIdList).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::ChildCount) { return rowCount(proxyIndex); } 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) { - // Returns the lowest virtual desktop id among all children of the - // group. - int virtualDesktop = INT_MAX; + } else if (role == AbstractTasksModel::IsVirtualDesktopsChangeable) { + return d->all(proxyIndex, AbstractTasksModel::IsVirtualDesktopsChangeable); + } else if (role == AbstractTasksModel::VirtualDesktops) { + QStringList desktops; for (int i = 0; i < rowCount(proxyIndex); ++i) { - const int childVirtualDesktop = proxyIndex.child(i, 0).data(AbstractTasksModel::VirtualDesktop).toInt(); - - if (childVirtualDesktop < virtualDesktop) { - virtualDesktop = childVirtualDesktop; - } + desktops.append(proxyIndex.child(i, 0).data(AbstractTasksModel::VirtualDesktops).toStringList()); } - return virtualDesktop; + desktops.removeDuplicates(); + return desktops; } 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. Once it is, do it similarly // to the AbstractTasksModel::VirtualDesktop case. 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::LauncherUrlWithoutIcon).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) +void TaskGroupingProxyModel::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) { if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { return; } if (index.parent().isValid() || !d->isGroup(index.row())) { - d->abstractTasksSourceModel->requestVirtualDesktop(mapToSource(index), desktop); + d->abstractTasksSourceModel->requestVirtualDesktops(mapToSource(index), desktops); } else { - const int row = index.row(); + QVector groupChildren; - for (int i = (rowCount(index) - 1); i >= 1; --i) { - const QModelIndex &sourceChild = mapToSource(index.child(i, 0)); - d->abstractTasksSourceModel->requestVirtualDesktop(sourceChild, desktop); + const int childCount = rowCount(index); + + groupChildren.reserve(childCount); + + for (int i = (childCount - 1); i >= 0; --i) { + groupChildren.append(mapToSource(index.child(i, 0))); + } + + for (const QModelIndex &idx : groupChildren) { + d->abstractTasksSourceModel->requestVirtualDesktops(idx, desktops); + } + } +} + +void TaskGroupingProxyModel::requestNewVirtualDesktop(const QModelIndex &index) +{ + if (!d->abstractTasksSourceModel || !index.isValid() || index.model() != this) { + return; + } + + if (index.parent().isValid() || !d->isGroup(index.row())) { + d->abstractTasksSourceModel->requestNewVirtualDesktop(mapToSource(index)); + } else { + QVector groupChildren; + + const int childCount = rowCount(index); + + groupChildren.reserve(childCount); + + for (int i = (childCount - 1); i >= 0; --i) { + groupChildren.append(mapToSource(index.child(i, 0))); } - d->abstractTasksSourceModel->requestVirtualDesktop(mapToSource(TaskGroupingProxyModel::index(row, 0)), - desktop); + for (const QModelIndex &idx : groupChildren) { + d->abstractTasksSourceModel->requestNewVirtualDesktop(idx); + } } } 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(); + QVector groupChildren; - for (int i = (rowCount(index) - 1); i >= 1; --i) { - const QModelIndex &sourceChild = mapToSource(index.child(i, 0)); - d->abstractTasksSourceModel->requestActivities(sourceChild, activities); + const int childCount = rowCount(index); + + groupChildren.reserve(childCount); + + for (int i = (childCount - 1); i >= 0; --i) { + groupChildren.append(mapToSource(index.child(i, 0))); } - d->abstractTasksSourceModel->requestActivities(mapToSource(TaskGroupingProxyModel::index(row, 0)), - activities); + for (const QModelIndex &idx : groupChildren) { + d->abstractTasksSourceModel->requestActivities(idx, 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::LauncherUrlWithoutIcon).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::LauncherUrlWithoutIcon).toUrl(), launcherUrl, IgnoreQueryItems)) { dataChanged(idx, idx, QVector{AbstractTasksModel::IsGroupable}); } } } emit blacklistedAppIdsChanged(); emit blacklistedLauncherUrlsChanged(); } } #include "moc_taskgroupingproxymodel.cpp" diff --git a/libtaskmanager/taskgroupingproxymodel.h b/libtaskmanager/taskgroupingproxymodel.h index 8d0c36345..6089bc59a 100644 --- a/libtaskmanager/taskgroupingproxymodel.h +++ b/libtaskmanager/taskgroupingproxymodel.h @@ -1,397 +1,413 @@ /******************************************************************** 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 TASKGROUPINGPROXYMODEL_H #define TASKGROUPINGPROXYMODEL_H #include #include "abstracttasksmodeliface.h" #include "tasksmodel.h" #include "taskmanager_export.h" namespace TaskManager { /** * @short A proxy tasks model for grouping tasks, forming a tree. * * This proxy model groups tasks in its source tasks model, forming a tree * of tasks. Gouping behavior is influenced by various properties set on * the proxy model instance. * * @author Eike Hein **/ class TASKMANAGER_EXPORT TaskGroupingProxyModel : public QAbstractProxyModel, public AbstractTasksModelIface { Q_OBJECT Q_PROPERTY(TasksModel::GroupMode groupMode READ groupMode WRITE setGroupMode NOTIFY groupModeChanged) Q_PROPERTY(bool groupDemandingAttention READ groupDemandingAttention WRITE setGroupDemandingAttention NOTIFY groupDemandingAttentionChanged) Q_PROPERTY(int windowTasksThreshold READ windowTasksThreshold WRITE setWindowTasksThreshold NOTIFY windowTasksThresholdChanged) Q_PROPERTY(QStringList blacklistedAppIds READ blacklistedAppIds WRITE setBlacklistedAppIds NOTIFY blacklistedAppIdsChanged) Q_PROPERTY(QStringList blacklistedLauncherUrls READ blacklistedLauncherUrls WRITE setBlacklistedLauncherUrls NOTIFY blacklistedLauncherUrlsChanged) public: explicit TaskGroupingProxyModel(QObject *parent = nullptr); ~TaskGroupingProxyModel() override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &child) const override; QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &proxyIndex, int role) const override; void setSourceModel(QAbstractItemModel *sourceModel) override; /** * Returns the current group mode, i.e. the criteria by which tasks should * be grouped. * * Defaults to TasksModel::GroupApplication, which groups tasks backed by * the same application. * * If the group mode is TasksModel::GroupDisabled, no grouping is done. * * @see TasksModel * @see setGroupMode * @returns the active group mode. **/ TasksModel::GroupMode groupMode() const; /** * Sets the group mode, i.e. the criteria by which tasks should be grouped. * * The group mode can be set to TasksModel::GroupDisabled to disable grouping * entirely, breaking apart any existing groups. * * @see TasksModel * @see groupMode * @param mode A TasksModel group mode. **/ void setGroupMode(TasksModel::GroupMode mode); /** * Whether new tasks which demand attention * (AbstractTasksModel::IsDemandingAttention) should be grouped immediately, * or only once they have stopped demanding attention. Defaults to @c false. * * @see setGroupDemandingAttention * @returns whether tasks which demand attention are grouped immediately. **/ bool groupDemandingAttention() const; /** * Sets whether new tasks which demand attention * (AbstractTasksModel::IsDemandingAttention) should be grouped immediately, * or only once they have stopped demanding attention. * * @see groupDemandingAttention * @param group Whether tasks with demand attention should be grouped immediately. **/ void setGroupDemandingAttention(bool group); /** * As window tasks (AbstractTasksModel::IsWindow) come and go in the source * model, groups will be formed when this threshold value is exceeded, and * broken apart when it matches or falls below. * * Defaults to @c -1, which means grouping is done regardless of the number * of window tasks in the source model. * * @see setWindowTasksThreshold * @return the threshold number of source window tasks used in grouping * decisions. **/ int windowTasksThreshold() const; /** * Sets the number of source model window tasks (AbstractTasksModel::IsWindow) * above which groups will be formed, and at or below which groups will be broken * apart. * * If set to -1, grouping will be done regardless of the number of window tasks * in the source model. * * @see windowTasksThreshold * @param threshold A threshold number of source window tasks used in grouping * decisions. **/ void setWindowTasksThreshold(int threshold); /** * A blacklist of app ids (AbstractTasksModel::AppId) that is consulted before * grouping a task. If a task's app id is found on the blacklist, it is not * grouped. * * The default app id blacklist is empty. * * @see setBlacklistedAppIds * @returns the blacklist of app ids consulted before grouping a task. **/ QStringList blacklistedAppIds() const; /** * Sets the blacklist of app ids (AbstractTasksModel::AppId) that is consulted * before grouping a task. If a task's app id is found on the blacklist, it is * not grouped. * * When set, groups will be formed and broken apart as necessary. * * @see blacklistedAppIds * @param list a blacklist of app ids to be consulted before grouping a task. **/ void setBlacklistedAppIds(const QStringList &list); /** * A blacklist of launcher URLs (AbstractTasksModel::LauncherUrl) that is * consulted before grouping a task. If a task's launcher URL is found on the * blacklist, it is not grouped. * * The default launcher URL blacklist is empty. * * @see setBlacklistedLauncherUrls * @returns the blacklist of launcher URLs consulted before grouping a task. **/ QStringList blacklistedLauncherUrls() const; /** * Sets the blacklist of launcher URLs (AbstractTasksModel::LauncherUrl) that * is consulted before grouping a task. If a task's launcher URL is found on * the blacklist, it is not grouped. * * When set, groups will be formed and broken apart as necessary. * * @see blacklistedLauncherUrls * @param list a blacklist of launcher URLs to be consulted before grouping a task. **/ void setBlacklistedLauncherUrls(const QStringList &list); /** * 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. * * @param index An index in this tasks model. **/ void requestActivate(const QModelIndex &index) override; /** * Request an additional instance of the application backing the task * at the given index. * * @param index An index in this tasks model. **/ void requestNewInstance(const QModelIndex &index) override; /** * Requests to open the given URLs with the application backing the task * at the given index. * * @param index An index in this tasks model. * @param urls The URLs to be passed to the application. **/ void requestOpenUrls(const QModelIndex &index, const QList &urls) override; /** * Request the task at the given index be closed. * * @param index An index in this tasks model. **/ 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. **/ 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. * * @param index An index in this tasks model. **/ 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. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. * * @param index An index in this tasks model. **/ 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. **/ 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. * * @param index An index in this tasks model. **/ void requestToggleShaded(const QModelIndex &index) override; /** - * Request moving the task at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktops, + * leaving any other desktops. * - * This is meant for tasks that have an associated window, and may be - * a no-op when there is no window. + * On Wayland, virtual desktop ids are QStrings. On X11, they are uint >0. * - * @param index An index in this tasks model. - * @param desktop A virtual desktop number. + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. + * + * On X11, a window can only be on one or all virtual desktops. Therefore, only the + * first list entry is actually used. + * + * On X11, the id 0 has a special meaning: The window is entered on all virtual + * desktops in the session. + * + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids. + **/ + void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) override; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. + * + * @param index An index in this window tasks model. **/ - void requestVirtualDesktop(const QModelIndex &index, qint32 desktop) override; + void requestNewVirtualDesktop(const QModelIndex &index) 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. **/ 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. * * If the task at the given index is a group parent, the geometry is * set for all of its children. If the task at the given index is a * group member, the geometry is set for all of its siblings. * * @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. **/ void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; /** * Request toggling whether the task at the given index, along with any * tasks matching its kind, should be grouped or not. Task groups will be * formed or broken apart as needed, along with affecting future grouping * decisions as new tasks appear in the source model. * * As grouping is toggled for a task, updates are made to the blacklisted* * properties of the model instance. * * @see blacklistedAppIds * @see blacklistedLauncherUrls * * @param index An index in this tasks model. **/ void requestToggleGrouping(const QModelIndex &index); Q_SIGNALS: void groupModeChanged() const; void groupDemandingAttentionChanged() const; void windowTasksThresholdChanged() const; void blacklistedAppIdsChanged() const; void blacklistedLauncherUrlsChanged() const; private: class Private; QScopedPointer d; Q_PRIVATE_SLOT(d, void sourceRowsAboutToBeInserted(const QModelIndex &parent, int first, int last)) Q_PRIVATE_SLOT(d, void sourceRowsInserted(const QModelIndex &parent, int start, int end)) Q_PRIVATE_SLOT(d, void sourceRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)) Q_PRIVATE_SLOT(d, void sourceRowsRemoved(const QModelIndex &parent, int start, int end)) Q_PRIVATE_SLOT(d, void sourceModelAboutToBeReset()) Q_PRIVATE_SLOT(d, void sourceModelReset()) Q_PRIVATE_SLOT(d, void sourceDataChanged(QModelIndex,QModelIndex,QVector)) }; } #endif diff --git a/libtaskmanager/tasksmodel.cpp b/libtaskmanager/tasksmodel.cpp index ffb43d523..261b371be 100644 --- a/libtaskmanager/tasksmodel.cpp +++ b/libtaskmanager/tasksmodel.cpp @@ -1,1877 +1,1938 @@ /******************************************************************** Copyright 2016 Eike Hein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "tasksmodel.h" #include "activityinfo.h" #include "concatenatetasksproxymodel.h" #include "flattentaskgroupsproxymodel.h" #include "taskfilterproxymodel.h" #include "taskgroupingproxymodel.h" #include "tasktools.h" +#include "virtualdesktopinfo.h" #include "launchertasksmodel.h" #include "startuptasksmodel.h" #include "windowtasksmodel.h" #include "launchertasksmodel_p.h" #include #include #include #include namespace TaskManager { class Q_DECL_HIDDEN TasksModel::Private { public: Private(TasksModel *q); ~Private(); static int instanceCount; static WindowTasksModel* windowTasksModel; static StartupTasksModel* startupTasksModel; LauncherTasksModel* launcherTasksModel = nullptr; ConcatenateTasksProxyModel* concatProxyModel = nullptr; TaskFilterProxyModel* filterProxyModel = nullptr; TaskGroupingProxyModel* groupingProxyModel = nullptr; FlattenTaskGroupsProxyModel* flattenGroupsProxyModel = nullptr; AbstractTasksModelIface *abstractTasksSourceModel = nullptr; bool anyTaskDemandsAttention = false; int launcherCount = 0; - int virtualDesktop = -1; - int screen = -1; - QString activity; SortMode sortMode = SortAlpha; bool separateLaunchers = true; bool launchInPlace = false; bool launchersEverSet = false; bool launcherSortingDirty = false; bool launcherCheckNeeded = false; QList sortedPreFilterRows; QVector sortRowInsertQueue; bool sortRowInsertQueueStale = false; QHash activityTaskCounts; + static VirtualDesktopInfo *virtualDesktopInfo; + static int virtualDesktopInfoUsers; static ActivityInfo* activityInfo; static int activityInfoUsers; bool groupInline = false; int groupingWindowTasksThreshold = -1; bool usedByQml = false; bool componentComplete = false; void initModels(); void initLauncherTasksModel(); void updateAnyTaskDemandsAttention(); void updateManualSortMap(); void consolidateManualSortMapForGroup(const QModelIndex &groupingProxyIndex); void updateGroupInline(); QModelIndex preFilterIndex(const QModelIndex &sourceIndex) const; void updateActivityTaskCounts(); void forceResort(); bool lessThan(const QModelIndex &left, const QModelIndex &right, bool sortOnlyLaunchers = false) const; private: TasksModel *q; }; class TasksModel::TasksModelLessThan { public: inline TasksModelLessThan(const QAbstractItemModel *s, TasksModel *p, bool sortOnlyLaunchers) : sourceModel(s), tasksModel(p), sortOnlyLaunchers(sortOnlyLaunchers) {} inline bool operator()(int r1, int r2) const { QModelIndex i1 = sourceModel->index(r1, 0); QModelIndex i2 = sourceModel->index(r2, 0); return tasksModel->d->lessThan(i1, i2, sortOnlyLaunchers); } private: const QAbstractItemModel *sourceModel; const TasksModel *tasksModel; bool sortOnlyLaunchers; }; int TasksModel::Private::instanceCount = 0; WindowTasksModel* TasksModel::Private::windowTasksModel = nullptr; StartupTasksModel* TasksModel::Private::startupTasksModel = nullptr; +VirtualDesktopInfo* TasksModel::Private::virtualDesktopInfo = nullptr; +int TasksModel::Private::virtualDesktopInfoUsers = 0; ActivityInfo* TasksModel::Private::activityInfo = nullptr; int TasksModel::Private::activityInfoUsers = 0; TasksModel::Private::Private(TasksModel *q) : q(q) { ++instanceCount; } TasksModel::Private::~Private() { --instanceCount; if (sortMode == SortActivity) { --activityInfoUsers; } if (!instanceCount) { delete windowTasksModel; windowTasksModel = nullptr; delete startupTasksModel; startupTasksModel = nullptr; + delete virtualDesktopInfo; + virtualDesktopInfo = nullptr; delete activityInfo; activityInfo = nullptr; } } void TasksModel::Private::initModels() { // NOTE: Overview over the entire model chain assembled here: // WindowTasksModel, StartupTasksModel, LauncherTasksModel // -> concatProxyModel concatenates them into a single list. // -> filterProxyModel filters by state (e.g. virtual desktop). // -> groupingProxyModel groups by application (we go from flat list to tree). // -> flattenGroupsProxyModel (optionally, if groupInline == true) flattens groups out. // -> TasksModel collapses (top-level) items into task lifecycle abstraction; sorts. if (!windowTasksModel) { windowTasksModel = new WindowTasksModel(); } QObject::connect(windowTasksModel, &QAbstractItemModel::rowsInserted, q, [this]() { if (sortMode == SortActivity) { updateActivityTaskCounts(); } } ); QObject::connect(windowTasksModel, &QAbstractItemModel::rowsRemoved, q, [this]() { if (sortMode == SortActivity) { updateActivityTaskCounts(); forceResort(); } } ); QObject::connect(windowTasksModel, &QAbstractItemModel::dataChanged, q, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { Q_UNUSED(topLeft) Q_UNUSED(bottomRight) if (sortMode == SortActivity && roles.contains(AbstractTasksModel::Activities)) { updateActivityTaskCounts(); } if (roles.contains(AbstractTasksModel::IsActive)) { emit q->activeTaskChanged(); } // In manual sort mode, updateManualSortMap() may consult the sortRowInsertQueue // for new tasks to sort in. Hidden tasks remain in the queue to potentially sort // them later, when they are are actually revealed to the user. // This is particularly useful in concert with taskmanagerrulesrc's SkipTaskbar // key, which is used to hide window tasks which update from bogus to useful // window metadata early in startup. The role change then coincides with positive // app identication, which is when updateManualSortMap() becomes able to sort the // task adjacent to its launcher when required to do so. if (sortMode == SortManual && roles.contains(AbstractTasksModel::SkipTaskbar)) { updateManualSortMap(); } } ); if (!startupTasksModel) { startupTasksModel = new StartupTasksModel(); } concatProxyModel = new ConcatenateTasksProxyModel(q); concatProxyModel->addSourceModel(windowTasksModel); concatProxyModel->addSourceModel(startupTasksModel); // If we're in manual sort mode, we need to seed the sort map on pending row // insertions. QObject::connect(concatProxyModel, &QAbstractItemModel::rowsAboutToBeInserted, q, [this](const QModelIndex &parent, int start, int end) { Q_UNUSED(parent) if (sortMode != SortManual) { return; } const int delta = (end - start) + 1; QMutableListIterator it(sortedPreFilterRows); while (it.hasNext()) { it.next(); if (it.value() >= start) { it.setValue(it.value() + delta); } } for (int i = start; i <= end; ++i) { sortedPreFilterRows.append(i); if (!separateLaunchers) { if (sortRowInsertQueueStale) { sortRowInsertQueue.clear(); sortRowInsertQueueStale = false; } sortRowInsertQueue.append(sortedPreFilterRows.count() - 1); } } } ); // If we're in manual sort mode, we need to update the sort map on row insertions. QObject::connect(concatProxyModel, &QAbstractItemModel::rowsInserted, q, [this](const QModelIndex &parent, int start, int end) { Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) if (sortMode == SortManual) { updateManualSortMap(); } } ); // If we're in manual sort mode, we need to update the sort map after row removals. QObject::connect(concatProxyModel, &QAbstractItemModel::rowsRemoved, q, [this](const QModelIndex &parent, int first, int last) { Q_UNUSED(parent) if (sortMode != SortManual) { return; } if (sortRowInsertQueueStale) { sortRowInsertQueue.clear(); sortRowInsertQueueStale = false; } for (int i = first; i <= last; ++i) { sortedPreFilterRows.removeOne(i); } const int delta = (last - first) + 1; QMutableListIterator it(sortedPreFilterRows); while (it.hasNext()) { it.next(); if (it.value() > last) { it.setValue(it.value() - delta); } } } ); filterProxyModel = new TaskFilterProxyModel(q); filterProxyModel->setSourceModel(concatProxyModel); QObject::connect(filterProxyModel, &TaskFilterProxyModel::virtualDesktopChanged, q, &TasksModel::virtualDesktopChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::screenGeometryChanged, q, &TasksModel::screenGeometryChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::activityChanged, q, &TasksModel::activityChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterByVirtualDesktopChanged, q, &TasksModel::filterByVirtualDesktopChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterByScreenChanged, q, &TasksModel::filterByScreenChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterByActivityChanged, q, &TasksModel::filterByActivityChanged); QObject::connect(filterProxyModel, &TaskFilterProxyModel::filterNotMinimizedChanged, q, &TasksModel::filterNotMinimizedChanged); groupingProxyModel = new TaskGroupingProxyModel(q); groupingProxyModel->setSourceModel(filterProxyModel); QObject::connect(groupingProxyModel, &TaskGroupingProxyModel::groupModeChanged, q, &TasksModel::groupModeChanged); QObject::connect(groupingProxyModel, &TaskGroupingProxyModel::blacklistedAppIdsChanged, q, &TasksModel::groupingAppIdBlacklistChanged); QObject::connect(groupingProxyModel, &TaskGroupingProxyModel::blacklistedLauncherUrlsChanged, q, &TasksModel::groupingLauncherUrlBlacklistChanged); QObject::connect(groupingProxyModel, &QAbstractItemModel::rowsInserted, q, [this](const QModelIndex &parent, int first, int last) { if (parent.isValid()) { if (sortMode == SortManual) { consolidateManualSortMapForGroup(parent); } // Existence of a group means everything below this has already been done. return; } bool demandsAttentionUpdateNeeded = false; for (int i = first; i <= last; ++i) { const QModelIndex &sourceIndex = groupingProxyModel->index(i, 0); const QString &appId = sourceIndex.data(AbstractTasksModel::AppId).toString(); if (sourceIndex.data(AbstractTasksModel::IsDemandingAttention).toBool()) { demandsAttentionUpdateNeeded = true; } // When we get a window we have a startup for, cause the startup to be re-filtered. if (sourceIndex.data(AbstractTasksModel::IsWindow).toBool()) { const QString &appName = sourceIndex.data(AbstractTasksModel::AppName).toString(); for (int i = 0; i < filterProxyModel->rowCount(); ++i) { QModelIndex filterIndex = filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsStartup).toBool()) { continue; } if ((!appId.isEmpty() && appId == filterIndex.data(AbstractTasksModel::AppId).toString()) || (!appName.isEmpty() && appName == filterIndex.data(AbstractTasksModel::AppName).toString())) { filterProxyModel->dataChanged(filterIndex, filterIndex); } } } // When we get a window or startup we have a launcher for, cause the launcher to be re-filtered. if (sourceIndex.data(AbstractTasksModel::IsWindow).toBool() || sourceIndex.data(AbstractTasksModel::IsStartup).toBool()) { for (int i = 0; i < filterProxyModel->rowCount(); ++i) { const QModelIndex &filterIndex = filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsLauncher).toBool()) { continue; } if (appsMatch(sourceIndex, filterIndex)) { filterProxyModel->dataChanged(filterIndex, filterIndex); } } } } if (!anyTaskDemandsAttention && demandsAttentionUpdateNeeded) { updateAnyTaskDemandsAttention(); } } ); QObject::connect(groupingProxyModel, &QAbstractItemModel::rowsAboutToBeRemoved, q, [this](const QModelIndex &parent, int first, int last) { // We can ignore group members. if (parent.isValid()) { return; } for (int i = first; i <= last; ++i) { const QModelIndex &sourceIndex = groupingProxyModel->index(i, 0); // When a window or startup task is removed, we have to trigger a re-filter of // our launchers to (possibly) pop them back in. // NOTE: An older revision of this code compared the window and startup tasks // to the launchers to figure out which launchers should be re-filtered. This // was fine until we discovered that certain applications (e.g. Google Chrome) // change their window metadata specifically during tear-down, sometimes // breaking TaskTools::appsMatch (it's a race) and causing the associated // launcher to remain hidden. Therefore we now consider any top-level window or // startup task removal a trigger to re-filter all launchers. We don't do this // in response to the window metadata changes (even though it would be strictly // more correct, as then-ending identity match-up was what caused the launcher // to be hidden) because we don't want the launcher and window/startup task to // briefly co-exist in the model. if (!launcherCheckNeeded && launcherTasksModel && (sourceIndex.data(AbstractTasksModel::IsWindow).toBool() || sourceIndex.data(AbstractTasksModel::IsStartup).toBool())) { launcherCheckNeeded = true; } } } ); QObject::connect(filterProxyModel, &QAbstractItemModel::rowsRemoved, q, [this](const QModelIndex &parent, int first, int last) { Q_UNUSED(parent) Q_UNUSED(first) Q_UNUSED(last) if (launcherCheckNeeded) { for (int i = 0; i < filterProxyModel->rowCount(); ++i) { const QModelIndex &idx = filterProxyModel->index(i, 0); if (idx.data(AbstractTasksModel::IsLauncher).toBool()) { filterProxyModel->dataChanged(idx, idx); } } launcherCheckNeeded = false; } // One of the removed tasks might have been demanding attention, but // we can't check the state after the window has been closed already, // so we always have to do a full update. if (anyTaskDemandsAttention) { updateAnyTaskDemandsAttention(); } } ); // Update anyTaskDemandsAttention on source data changes. QObject::connect(groupingProxyModel, &QAbstractItemModel::dataChanged, q, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { Q_UNUSED(bottomRight) // We can ignore group members. if (topLeft.parent().isValid()) { return; } if (roles.isEmpty() || roles.contains(AbstractTasksModel::IsDemandingAttention)) { updateAnyTaskDemandsAttention(); } if (roles.isEmpty() || roles.contains(AbstractTasksModel::AppId)) { for (int i = topLeft.row(); i <= bottomRight.row(); ++i) { const QModelIndex &sourceIndex = groupingProxyModel->index(i, 0); // When a window task changes identity to one we have a launcher for, cause // the launcher to be re-filtered. if (sourceIndex.data(AbstractTasksModel::IsWindow).toBool()) { for (int i = 0; i < filterProxyModel->rowCount(); ++i) { const QModelIndex &filterIndex = filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsLauncher).toBool()) { continue; } if (appsMatch(sourceIndex, filterIndex)) { filterProxyModel->dataChanged(filterIndex, filterIndex); } } } } } } ); // Update anyTaskDemandsAttention on source model resets. QObject::connect(groupingProxyModel, &QAbstractItemModel::modelReset, q, [this]() { updateAnyTaskDemandsAttention(); } ); } void TasksModel::Private::updateAnyTaskDemandsAttention() { bool taskFound = false; for (int i = 0; i < groupingProxyModel->rowCount(); ++i) { if (groupingProxyModel->index(i, 0).data(AbstractTasksModel::IsDemandingAttention).toBool()) { taskFound = true; break; } } if (taskFound != anyTaskDemandsAttention) { anyTaskDemandsAttention = taskFound; q->anyTaskDemandsAttentionChanged(); } } void TasksModel::Private::initLauncherTasksModel() { if (launcherTasksModel) { return; } launcherTasksModel = new LauncherTasksModel(q); QObject::connect(launcherTasksModel, &LauncherTasksModel::launcherListChanged, q, &TasksModel::launcherListChanged); QObject::connect(launcherTasksModel, &LauncherTasksModel::launcherListChanged, q, &TasksModel::updateLauncherCount); // TODO: On the assumptions that adding/removing launchers is a rare event and // the HasLaunchers data role is rarely used, this refreshes it for all rows in // the model. If those assumptions are proven wrong later, this could be // optimized to only refresh non-launcher rows matching the inserted or about- // to-be-removed launcherTasksModel rows using TaskTools::appsMatch(). QObject::connect(launcherTasksModel, &LauncherTasksModel::launcherListChanged, q, [this]() { q->dataChanged(q->index(0, 0), q->index(q->rowCount() - 1, 0), QVector{AbstractTasksModel::HasLauncher}); } ); // data() implements AbstractTasksModel::HasLauncher by checking with // TaskTools::appsMatch, which evaluates ::AppId and ::LauncherUrlWithoutIcon. QObject::connect(q, &QAbstractItemModel::dataChanged, q, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { if (roles.contains(AbstractTasksModel::AppId) || roles.contains(AbstractTasksModel::LauncherUrlWithoutIcon)) { for (int i = topLeft.row(); i <= bottomRight.row(); ++i) { const QModelIndex &index = q->index(i, 0); if (!index.data(AbstractTasksModel::IsLauncher).toBool()) { q->dataChanged(index, index, QVector{AbstractTasksModel::HasLauncher}); } } } } ); concatProxyModel->addSourceModel(launcherTasksModel); } void TasksModel::Private::updateManualSortMap() { // Empty map; full sort. if (sortedPreFilterRows.isEmpty()) { sortedPreFilterRows.reserve(concatProxyModel->rowCount()); for (int i = 0; i < concatProxyModel->rowCount(); ++i) { sortedPreFilterRows.append(i); } // Full sort. TasksModelLessThan lt(concatProxyModel, q, false); std::stable_sort(sortedPreFilterRows.begin(), sortedPreFilterRows.end(), lt); // Consolidate sort map entries for groups. if (q->groupMode() != GroupDisabled) { for (int i = 0; i < groupingProxyModel->rowCount(); ++i) { const QModelIndex &groupingIndex = groupingProxyModel->index(i, 0); if (groupingIndex.data(AbstractTasksModel::IsGroupParent).toBool()) { consolidateManualSortMapForGroup(groupingIndex); } } } return; } // Existing map; check whether launchers need sorting by launcher list position. if (separateLaunchers) { // Sort only launchers. TasksModelLessThan lt(concatProxyModel, q, true); std::stable_sort(sortedPreFilterRows.begin(), sortedPreFilterRows.end(), lt); // Otherwise process any entries in the insert queue and move them intelligently // in the sort map. } else { QMutableVectorIterator i(sortRowInsertQueue); while (i.hasNext()) { i.next(); const int row = i.value(); const QModelIndex &idx = concatProxyModel->index(sortedPreFilterRows.at(row), 0); // If a window task is currently hidden, we may want to keep it in the queue // to sort it in later once it gets revealed. // This is important in concert with taskmanagerrulesrc's SkipTaskbar key, which // is used to hide window tasks which update from bogus to useful window metadata // early in startup. Once the task no longer uses bogus metadata listed in the // config key, its SkipTaskbar role changes to false, and then is it possible to // sort the task adjacent to its launcher in the code below. if (idx.data(AbstractTasksModel::IsWindow).toBool() && idx.data(AbstractTasksModel::SkipTaskbar).toBool()) { // Since we're going to keep a row in the queue for now, make sure to // mark the queue as stale so it's cleared on appends or row removals // when they follow this sorting attempt. This frees us from having to // update the indices in the queue to keep them valid. // This means windowing system changes such as the opening or closing // of a window task which happen during the time period that a window // task has known bogus metadata, can upset what we're trying to // achieve with this exception. However, due to the briefness of the // time period and usage patterns, this is improbable, making this // likely good enough. If it turns out not to be, this decision may be // revisited later. sortRowInsertQueueStale = true; break; } else { i.remove(); } bool moved = false; // Try to move the task up to its right-most app sibling, unless this // is us sorting in a launcher list for the first time. if (launchersEverSet && !idx.data(AbstractTasksModel::IsLauncher).toBool()) { for (int i = (row - 1); i >= 0; --i) { const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); // Once we got a match, check if the filter model accepts the potential // sibling. We don't want to sort new tasks in next to tasks it will // filter out once it sees it anyway. if (appsMatch(concatProxyIndex, idx) && filterProxyModel->acceptsRow(concatProxyIndex.row())) { sortedPreFilterRows.move(row, i + 1); moved = true; break; } } } int insertPos = 0; // If unsuccessful or skipped, and the new task is a launcher, put after // the rightmost launcher or launcher-backed task in the map, or failing // that at the start of the map. if (!moved && idx.data(AbstractTasksModel::IsLauncher).toBool()) { for (int i = 0; i < row; ++i) { const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); if (concatProxyIndex.data(AbstractTasksModel::IsLauncher).toBool() || launcherTasksModel->launcherPosition(concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()) != -1) { insertPos = i + 1; } else { break; } } sortedPreFilterRows.move(row, insertPos); moved = true; } // If we sorted in a launcher and it's the first time we're sorting in a // launcher list, move existing windows to the launcher position now. if (moved && !launchersEverSet) { for (int i = (sortedPreFilterRows.count() - 1); i >= 0; --i) { const QModelIndex &concatProxyIndex = concatProxyModel->index(sortedPreFilterRows.at(i), 0); if (!concatProxyIndex.data(AbstractTasksModel::IsLauncher).toBool() && idx.data(AbstractTasksModel::LauncherUrlWithoutIcon) == concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon)) { sortedPreFilterRows.move(i, insertPos); if (insertPos > i) { --insertPos; } } } } } } } void TasksModel::Private::consolidateManualSortMapForGroup(const QModelIndex &groupingProxyIndex) { // Consolidates sort map entries for a group's items to be contiguous // after the group's first item and the same order as in groupingProxyModel. const int childCount = groupingProxyModel->rowCount(groupingProxyIndex); if (!childCount) { return; } const QModelIndex &leader = groupingProxyIndex.child(0, 0); const QModelIndex &preFilterLeader = filterProxyModel->mapToSource(groupingProxyModel->mapToSource(leader)); // We're moving the trailing children to the sort map position of // the first child, so we're skipping the first child. for (int i = 1; i < childCount; ++i) { const QModelIndex &child = groupingProxyIndex.child(i, 0); const QModelIndex &preFilterChild = filterProxyModel->mapToSource(groupingProxyModel->mapToSource(child)); const int leaderPos = sortedPreFilterRows.indexOf(preFilterLeader.row()); const int childPos = sortedPreFilterRows.indexOf(preFilterChild.row()); const int insertPos = (leaderPos + i) + ((leaderPos + i) > childPos ? -1 : 0); sortedPreFilterRows.move(childPos, insertPos); } } void TasksModel::Private::updateGroupInline() { if (usedByQml && !componentComplete) { return; } bool hadSourceModel = (q->sourceModel() != nullptr); if (q->groupMode() != GroupDisabled && groupInline) { if (flattenGroupsProxyModel) { return; } // Exempting tasks which demand attention from grouping is not // necessary when all group children are shown inline anyway // and would interfere with our sort-tasks-together goals. groupingProxyModel->setGroupDemandingAttention(true); // Likewise, ignore the window tasks threshold when making // grouping decisions. groupingProxyModel->setWindowTasksThreshold(-1); flattenGroupsProxyModel = new FlattenTaskGroupsProxyModel(q); flattenGroupsProxyModel->setSourceModel(groupingProxyModel); abstractTasksSourceModel = flattenGroupsProxyModel; q->setSourceModel(flattenGroupsProxyModel); if (sortMode == SortManual) { forceResort(); } } else { if (hadSourceModel && !flattenGroupsProxyModel) { return; } groupingProxyModel->setGroupDemandingAttention(false); groupingProxyModel->setWindowTasksThreshold(groupingWindowTasksThreshold); abstractTasksSourceModel = groupingProxyModel; q->setSourceModel(groupingProxyModel); delete flattenGroupsProxyModel; flattenGroupsProxyModel = nullptr; if (hadSourceModel && sortMode == SortManual) { forceResort(); } } // Minor optimization: We only make these connections after we populate for // the first time to avoid some churn. if (!hadSourceModel) { QObject::connect(q, &QAbstractItemModel::rowsInserted, q, &TasksModel::updateLauncherCount, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::rowsRemoved, q, &TasksModel::updateLauncherCount, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::modelReset, q, &TasksModel::updateLauncherCount, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::rowsInserted, q, &TasksModel::countChanged, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::rowsRemoved, q, &TasksModel::countChanged, Qt::UniqueConnection); QObject::connect(q, &QAbstractItemModel::modelReset, q, &TasksModel::countChanged, Qt::UniqueConnection); } } QModelIndex TasksModel::Private::preFilterIndex(const QModelIndex &sourceIndex) const { // Only in inline grouping mode, we have an additional proxy layer. if (flattenGroupsProxyModel) { return filterProxyModel->mapToSource(groupingProxyModel->mapToSource(flattenGroupsProxyModel->mapToSource(sourceIndex))); } else { return filterProxyModel->mapToSource(groupingProxyModel->mapToSource(sourceIndex)); } } void TasksModel::Private::updateActivityTaskCounts() { // Collects the number of window tasks on each activity. activityTaskCounts.clear(); if (!windowTasksModel || !activityInfo) { return; } foreach(const QString &activity, activityInfo->runningActivities()) { activityTaskCounts.insert(activity, 0); } for (int i = 0; i < windowTasksModel->rowCount(); ++i) { const QModelIndex &windowIndex = windowTasksModel->index(i, 0); const QStringList &activities = windowIndex.data(AbstractTasksModel::Activities).toStringList(); if (activities.isEmpty()) { QMutableHashIterator i(activityTaskCounts); while (i.hasNext()) { i.next(); i.setValue(i.value() + 1); } } else { foreach(const QString &activity, activities) { ++activityTaskCounts[activity]; } } } } void TasksModel::Private::forceResort() { // HACK: This causes QSortFilterProxyModel to run all rows through // our lessThan() implementation again. q->setDynamicSortFilter(false); q->setDynamicSortFilter(true); } bool TasksModel::Private::lessThan(const QModelIndex &left, const QModelIndex &right, bool sortOnlyLaunchers) const { // Launcher tasks go first. // When launchInPlace is enabled, startup and window tasks are sorted // as the launchers they replace (see also move()). if (separateLaunchers) { if (left.data(AbstractTasksModel::IsLauncher).toBool() && right.data(AbstractTasksModel::IsLauncher).toBool()) { return (left.row() < right.row()); } else if (left.data(AbstractTasksModel::IsLauncher).toBool() && !right.data(AbstractTasksModel::IsLauncher).toBool()) { if (launchInPlace) { const int leftPos = q->launcherPosition(left.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); const int rightPos = q->launcherPosition(right.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); if (rightPos != -1) { return (leftPos < rightPos); } } return true; } else if (!left.data(AbstractTasksModel::IsLauncher).toBool() && right.data(AbstractTasksModel::IsLauncher).toBool()) { if (launchInPlace) { const int leftPos = q->launcherPosition(left.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); const int rightPos = q->launcherPosition(right.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); if (leftPos != -1) { return (leftPos < rightPos); } } return false; } else if (launchInPlace) { const int leftPos = q->launcherPosition(left.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); const int rightPos = q->launcherPosition(right.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()); if (leftPos != -1 && rightPos != -1) { return (leftPos < rightPos); } else if (leftPos != -1 && rightPos == -1) { return true; } else if (leftPos == -1 && rightPos != -1) { return false; } } } // If told to stop after launchers we fall through to the existing map if it exists. if (sortOnlyLaunchers && !sortedPreFilterRows.isEmpty()) { return (sortedPreFilterRows.indexOf(left.row()) < sortedPreFilterRows.indexOf(right.row())); } // Sort other cases by sort mode. switch (sortMode) { case SortVirtualDesktop: { - const QVariant &leftDesktopVariant = left.data(AbstractTasksModel::VirtualDesktop); - bool leftOk = false; - const int leftDesktop = leftDesktopVariant.toInt(&leftOk); + const bool leftAll = left.data(AbstractTasksModel::IsOnAllVirtualDesktops).toBool(); + const bool rightAll = right.data(AbstractTasksModel::IsOnAllVirtualDesktops).toBool(); - const QVariant &rightDesktopVariant = right.data(AbstractTasksModel::VirtualDesktop); - bool rightOk = false; - const int rightDesktop = rightDesktopVariant.toInt(&rightOk); + if (leftAll && !rightAll) { + return true; + } else if (rightAll && !leftAll) { + return true; + } + + const QVariantList &leftDesktops = left.data(AbstractTasksModel::VirtualDesktops).toList(); + QVariant leftDesktop; + int leftDesktopPos = virtualDesktopInfo->numberOfDesktops(); + + for (const QVariant &desktop : leftDesktops) { + const int desktopPos = virtualDesktopInfo->position(desktop); + + if (desktopPos < leftDesktopPos) { + leftDesktop = desktop; + leftDesktopPos = desktopPos; + } + } - if (leftOk && rightOk && (leftDesktop != rightDesktop)) { - return (leftDesktop < rightDesktop); - } else if (leftOk && !rightOk) { + const QVariantList &rightDesktops = right.data(AbstractTasksModel::VirtualDesktops).toList(); + QVariant rightDesktop; + int rightDesktopPos = virtualDesktopInfo->numberOfDesktops(); + + for (const QVariant &desktop : rightDesktops) { + const int desktopPos = virtualDesktopInfo->position(desktop); + + if (desktopPos < rightDesktopPos) { + rightDesktop = desktop; + rightDesktopPos = desktopPos; + } + } + + if (!leftDesktop.isNull() && !rightDesktop.isNull() && (leftDesktop != rightDesktop)) { + return (virtualDesktopInfo->position(leftDesktop) < virtualDesktopInfo->position(rightDesktop)); + } else if (!leftDesktop.isNull() && rightDesktop.isNull()) { return false; - } else if (!leftOk && rightOk) { + } else if (leftDesktop.isNull() && !rightDesktop.isNull()) { return true; } + + return false; } case SortActivity: { // updateActivityTaskCounts() counts the number of window tasks on each // activity. This will sort tasks by comparing a cumulative score made // up of the task counts for each acvtivity a task is assigned to, and // otherwise fall through to alphabetical sorting. int leftScore = -1; int rightScore = -1; const QStringList &leftActivities = left.data(AbstractTasksModel::Activities).toStringList(); if (!leftActivities.isEmpty()) { foreach(const QString& activity, leftActivities) { leftScore += activityTaskCounts[activity]; } } const QStringList &rightActivities = right.data(AbstractTasksModel::Activities).toStringList(); if (!rightActivities.isEmpty()) { foreach(const QString& activity, rightActivities) { rightScore += activityTaskCounts[activity]; } } if (leftScore == -1 || rightScore == -1) { const int sumScore = std::accumulate(activityTaskCounts.constBegin(), activityTaskCounts.constEnd(), 0); if (leftScore == -1) { leftScore = sumScore; } if (rightScore == -1) { rightScore = sumScore; } } if (leftScore != rightScore) { return (leftScore > rightScore); } } // Fall through to source order if sorting is disabled or manual, or alphabetical by app name otherwise. + // This marker comment makes gcc/clang happy: + // fall through default: { if (sortMode == SortDisabled) { return (left.row() < right.row()); } else { // The overall goal of alphabetic sorting is to sort tasks belonging to the // same app together, while sorting the resulting sets alphabetically among // themselves by the app name. The following code tries to achieve this by // going for AppName first, and falling back to DisplayRole - which for // window-type tasks generally contains the window title - if AppName is // not available. When comparing tasks with identical resulting sort strings, // we sort them by the source model order (i.e. insertion/creation). Older // versions of this code compared tasks by a concatenation of AppName and // DisplayRole at all times, but always sorting by the window title does more // than our goal description - and can cause tasks within an app's set to move // around when window titles change, which is a nuisance for users (especially // in case of tabbed apps that have the window title reflect the active tab, // e.g. web browsers). To recap, the common case is "sort by AppName, then // insertion order", only swapping out AppName for DisplayRole (i.e. window // title) when necessary. QString leftSortString = left.data(AbstractTasksModel::AppName).toString(); if (leftSortString.isEmpty()) { leftSortString = left.data(Qt::DisplayRole).toString(); } QString rightSortString = right.data(AbstractTasksModel::AppName).toString(); if (rightSortString.isEmpty()) { rightSortString = right.data(Qt::DisplayRole).toString(); } const int sortResult = leftSortString.localeAwareCompare(rightSortString); // If the string are identical fall back to source model (creation/append) order. if (sortResult == 0) { return (left.row() < right.row()); } return (sortResult < 0); } } } } TasksModel::TasksModel(QObject *parent) : QSortFilterProxyModel(parent) , d(new Private(this)) { d->initModels(); // Start sorting. sort(0); // Private::updateGroupInline() sets our source model, populating the model. We // delay running this until the QML runtime had a chance to call our implementation // of QQmlParserStatus::classBegin(), setting Private::usedByQml to true. If used // by QML, Private::updateGroupInline() will abort if the component is not yet // complete, instead getting called through QQmlParserStatus::componentComplete() // only after all properties have been set. This avoids delegate churn in Qt Quick // views using the model. If not used by QML, Private::updateGroupInline() will run // directly. QTimer::singleShot(0, this, [this]() { d->updateGroupInline(); }); } TasksModel::~TasksModel() { } QHash TasksModel::roleNames() const { if (d->windowTasksModel) { return d->windowTasksModel->roleNames(); } return QHash(); } int TasksModel::rowCount(const QModelIndex &parent) const { return QSortFilterProxyModel::rowCount(parent); } QVariant TasksModel::data(const QModelIndex &proxyIndex, int role) const { if (role == AbstractTasksModel::HasLauncher && proxyIndex.isValid() && proxyIndex.row() < rowCount()) { if (proxyIndex.data(AbstractTasksModel::IsLauncher).toBool()) { return true; } else { if (!d->launcherTasksModel) { return false; } for (int i = 0; i < d->launcherTasksModel->rowCount(); ++i) { const QModelIndex &launcherIndex = d->launcherTasksModel->index(i, 0); if (appsMatch(proxyIndex, launcherIndex)) { return true; } } return false; } - } else if (rowCount(proxyIndex) && role == AbstractTasksModel::LegacyWinIdList) { + } else if (rowCount(proxyIndex) && role == AbstractTasksModel::WinIdList) { QVariantList winIds; for (int i = 0; i < rowCount(proxyIndex); ++i) { - winIds.append(proxyIndex.child(i, 0).data(AbstractTasksModel::LegacyWinIdList).toList()); + winIds.append(proxyIndex.child(i, 0).data(AbstractTasksModel::WinIdList).toList()); } return winIds; } return QSortFilterProxyModel::data(proxyIndex, role); } void TasksModel::updateLauncherCount() { if (!d->launcherTasksModel) { return; } int count = 0; for (int i = 0; i < rowCount(); ++i) { if (index(i, 0).data(AbstractTasksModel::IsLauncher).toBool()) { ++count; } } if (d->launcherCount != count) { d->launcherCount = count; emit launcherCountChanged(); } } int TasksModel::launcherCount() const { return d->launcherCount; } bool TasksModel::anyTaskDemandsAttention() const { return d->anyTaskDemandsAttention; } -int TasksModel::virtualDesktop() const +QVariant TasksModel::virtualDesktop() const { return d->filterProxyModel->virtualDesktop(); } -void TasksModel::setVirtualDesktop(int virtualDesktop) +void TasksModel::setVirtualDesktop(const QVariant &desktop) { - d->filterProxyModel->setVirtualDesktop(virtualDesktop); + d->filterProxyModel->setVirtualDesktop(desktop); } QRect TasksModel::screenGeometry() const { return d->filterProxyModel->screenGeometry(); } void TasksModel::setScreenGeometry(const QRect &geometry) { d->filterProxyModel->setScreenGeometry(geometry); } QString TasksModel::activity() const { return d->filterProxyModel->activity(); } void TasksModel::setActivity(const QString &activity) { d->filterProxyModel->setActivity(activity); } bool TasksModel::filterByVirtualDesktop() const { return d->filterProxyModel->filterByVirtualDesktop(); } void TasksModel::setFilterByVirtualDesktop(bool filter) { d->filterProxyModel->setFilterByVirtualDesktop(filter); } bool TasksModel::filterByScreen() const { return d->filterProxyModel->filterByScreen(); } void TasksModel::setFilterByScreen(bool filter) { d->filterProxyModel->setFilterByScreen(filter); } bool TasksModel::filterByActivity() const { return d->filterProxyModel->filterByActivity(); } void TasksModel::setFilterByActivity(bool filter) { d->filterProxyModel->setFilterByActivity(filter); } bool TasksModel::filterNotMinimized() const { return d->filterProxyModel->filterNotMinimized(); } void TasksModel::setFilterNotMinimized(bool filter) { d->filterProxyModel->setFilterNotMinimized(filter); } TasksModel::SortMode TasksModel::sortMode() const { return d->sortMode; } void TasksModel::setSortMode(SortMode mode) { if (d->sortMode != mode) { if (mode == SortManual) { d->updateManualSortMap(); } else if (d->sortMode == SortManual) { d->sortedPreFilterRows.clear(); } + if (mode == SortVirtualDesktop) { + if (!d->virtualDesktopInfo) { + d->virtualDesktopInfo = new VirtualDesktopInfo(); + } + + ++d->virtualDesktopInfoUsers; + + setSortRole(AbstractTasksModel::VirtualDesktops); + } else if (d->sortMode == SortVirtualDesktop) { + --d->virtualDesktopInfoUsers; + + if (!d->virtualDesktopInfoUsers) { + delete d->virtualDesktopInfo; + d->virtualDesktopInfo = nullptr; + } + + setSortRole(Qt::DisplayRole); + } + if (mode == SortActivity) { if (!d->activityInfo) { d->activityInfo = new ActivityInfo(); } ++d->activityInfoUsers; d->updateActivityTaskCounts(); setSortRole(AbstractTasksModel::Activities); } else if (d->sortMode == SortActivity) { --d->activityInfoUsers; if (!d->activityInfoUsers) { delete d->activityInfo; d->activityInfo = nullptr; } d->activityTaskCounts.clear(); setSortRole(Qt::DisplayRole); } d->sortMode = mode; d->forceResort(); emit sortModeChanged(); } } bool TasksModel::separateLaunchers() const { return d->separateLaunchers; } void TasksModel::setSeparateLaunchers(bool separate) { if (d->separateLaunchers != separate) { d->separateLaunchers = separate; d->updateManualSortMap(); d->forceResort(); emit separateLaunchersChanged(); } } bool TasksModel::launchInPlace() const { return d->launchInPlace; } void TasksModel::setLaunchInPlace(bool launchInPlace) { if (d->launchInPlace != launchInPlace) { d->launchInPlace = launchInPlace; d->forceResort(); emit launchInPlaceChanged(); } } TasksModel::GroupMode TasksModel::groupMode() const { if (!d->groupingProxyModel) { return GroupDisabled; } return d->groupingProxyModel->groupMode(); } void TasksModel::setGroupMode(GroupMode mode) { if (d->groupingProxyModel) { if (mode == GroupDisabled && d->flattenGroupsProxyModel) { d->flattenGroupsProxyModel->setSourceModel(nullptr); } d->groupingProxyModel->setGroupMode(mode); d->updateGroupInline(); } } bool TasksModel::groupInline() const { return d->groupInline; } void TasksModel::setGroupInline(bool groupInline) { if (d->groupInline != groupInline) { d->groupInline = groupInline; d->updateGroupInline(); emit groupInlineChanged(); } } int TasksModel::groupingWindowTasksThreshold() const { return d->groupingWindowTasksThreshold; } void TasksModel::setGroupingWindowTasksThreshold(int threshold) { if (d->groupingWindowTasksThreshold != threshold) { d->groupingWindowTasksThreshold = threshold; if (!d->groupInline && d->groupingProxyModel) { d->groupingProxyModel->setWindowTasksThreshold(threshold); } emit groupingWindowTasksThresholdChanged(); } } QStringList TasksModel::groupingAppIdBlacklist() const { if (!d->groupingProxyModel) { return QStringList(); } return d->groupingProxyModel->blacklistedAppIds(); } void TasksModel::setGroupingAppIdBlacklist(const QStringList &list) { if (d->groupingProxyModel) { d->groupingProxyModel->setBlacklistedAppIds(list); } } QStringList TasksModel::groupingLauncherUrlBlacklist() const { if (!d->groupingProxyModel) { return QStringList(); } return d->groupingProxyModel->blacklistedLauncherUrls(); } void TasksModel::setGroupingLauncherUrlBlacklist(const QStringList &list) { if (d->groupingProxyModel) { d->groupingProxyModel->setBlacklistedLauncherUrls(list); } } QStringList TasksModel::launcherList() const { if (d->launcherTasksModel) { return d->launcherTasksModel->launcherList(); } return QStringList(); } void TasksModel::setLauncherList(const QStringList &launchers) { d->initLauncherTasksModel(); d->launcherTasksModel->setLauncherList(launchers); d->launchersEverSet = true; } bool TasksModel::requestAddLauncher(const QUrl &url) { d->initLauncherTasksModel(); bool added = d->launcherTasksModel->requestAddLauncher(url); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks to // their launcher position now. if (added && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return added; } bool TasksModel::requestRemoveLauncher(const QUrl &url) { if (d->launcherTasksModel) { bool removed = d->launcherTasksModel->requestRemoveLauncher(url); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks no // longer backed by a launcher out of the launcher area. if (removed && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return removed; } return false; } bool TasksModel::requestAddLauncherToActivity(const QUrl &url, const QString &activity) { d->initLauncherTasksModel(); bool added = d->launcherTasksModel->requestAddLauncherToActivity(url, activity); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks to // their launcher position now. if (added && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return added; } bool TasksModel::requestRemoveLauncherFromActivity(const QUrl &url, const QString &activity) { if (d->launcherTasksModel) { bool removed = d->launcherTasksModel->requestRemoveLauncherFromActivity(url, activity); // If using manual and launch-in-place sorting with separate launchers, // we need to trigger a sort map update to move any window tasks no // longer backed by a launcher out of the launcher area. if (removed && d->sortMode == SortManual && (d->launchInPlace || !d->separateLaunchers)) { d->updateManualSortMap(); d->forceResort(); } return removed; } return false; } QStringList TasksModel::launcherActivities(const QUrl &url) { if (d->launcherTasksModel) { return d->launcherTasksModel->launcherActivities(url); } return {}; } int TasksModel::launcherPosition(const QUrl &url) const { if (d->launcherTasksModel) { return d->launcherTasksModel->launcherPosition(url); } return -1; } void TasksModel::requestActivate(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestActivate(mapToSource(index)); } } void TasksModel::requestNewInstance(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestNewInstance(mapToSource(index)); } } void TasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestOpenUrls(mapToSource(index), urls); } } void TasksModel::requestClose(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestClose(mapToSource(index)); } } void TasksModel::requestMove(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestMove(mapToSource(index)); } } void TasksModel::requestResize(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestResize(mapToSource(index)); } } void TasksModel::requestToggleMinimized(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleMinimized(mapToSource(index)); } } void TasksModel::requestToggleMaximized(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleMaximized(mapToSource(index)); } } void TasksModel::requestToggleKeepAbove(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleKeepAbove(mapToSource(index)); } } void TasksModel::requestToggleKeepBelow(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleKeepBelow(mapToSource(index)); } } void TasksModel::requestToggleFullScreen(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleFullScreen(mapToSource(index)); } } void TasksModel::requestToggleShaded(const QModelIndex &index) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestToggleShaded(mapToSource(index)); } } -void TasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) +void TasksModel::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) +{ + if (index.isValid() && index.model() == this) { + d->abstractTasksSourceModel->requestVirtualDesktops(mapToSource(index), desktops); + } +} + +void TasksModel::requestNewVirtualDesktop(const QModelIndex &index) { if (index.isValid() && index.model() == this) { - d->abstractTasksSourceModel->requestVirtualDesktop(mapToSource(index), desktop); + d->abstractTasksSourceModel->requestNewVirtualDesktop(mapToSource(index)); } } void TasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { if (index.isValid() && index.model() == this) { d->groupingProxyModel->requestActivities(mapToSource(index), activities); } } void TasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { if (index.isValid() && index.model() == this) { d->abstractTasksSourceModel->requestPublishDelegateGeometry(mapToSource(index), geometry, delegate); } } void TasksModel::requestToggleGrouping(const QModelIndex &index) { if (index.isValid() && index.model() == this) { const QModelIndex &target = (d->flattenGroupsProxyModel ? d->flattenGroupsProxyModel->mapToSource(mapToSource(index)) : mapToSource(index)); d->groupingProxyModel->requestToggleGrouping(target); } } bool TasksModel::move(int row, int newPos, const QModelIndex &parent) { if (d->sortMode != SortManual || row == newPos || newPos < 0 || newPos >= rowCount(parent)) { return false; } const QModelIndex &idx = index(row, 0); bool isLauncherMove = false; // Figure out if we're moving a launcher so we can run barrier checks. if (idx.isValid()) { if (idx.data(AbstractTasksModel::IsLauncher).toBool()) { isLauncherMove = true; // When using launch-in-place sorting, launcher-backed window tasks act as launchers. } else if ((d->launchInPlace || !d->separateLaunchers) && idx.data(AbstractTasksModel::IsWindow).toBool()) { const QUrl &launcherUrl = idx.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); const int launcherPos = launcherPosition(launcherUrl); if (launcherPos != -1) { isLauncherMove = true; } } } else { return false; } if (d->separateLaunchers) { const int firstTask = (d->launcherTasksModel ? (d->launchInPlace ? d->launcherTasksModel->rowCount() : launcherCount()) : 0); // Don't allow launchers to be moved past the last launcher. if (isLauncherMove && newPos >= firstTask) { return false; } // Don't allow tasks to be moved into the launchers. if (!isLauncherMove && newPos < firstTask) { return false; } } // Treat flattened-out groups as single items. if (d->flattenGroupsProxyModel) { QModelIndex groupingRowIndex = d->flattenGroupsProxyModel->mapToSource(mapToSource(index(row, 0))); const QModelIndex &groupingRowIndexParent = groupingRowIndex.parent(); QModelIndex groupingNewPosIndex = d->flattenGroupsProxyModel->mapToSource(mapToSource(index(newPos, 0))); const QModelIndex &groupingNewPosIndexParent = groupingNewPosIndex.parent(); // Disallow moves within a flattened-out group (TODO: for now, anyway). if (groupingRowIndexParent.isValid() && (groupingRowIndexParent == groupingNewPosIndex || groupingRowIndexParent == groupingNewPosIndexParent)) { return false; } int offset = 0; int extraChildCount = 0; if (groupingRowIndexParent.isValid()) { offset = groupingRowIndex.row(); extraChildCount = d->groupingProxyModel->rowCount(groupingRowIndexParent) - 1; groupingRowIndex = groupingRowIndexParent; } if (groupingNewPosIndexParent.isValid()) { int extra = d->groupingProxyModel->rowCount(groupingNewPosIndexParent) - 1; if (newPos > row) { newPos += extra; newPos -= groupingNewPosIndex.row(); groupingNewPosIndex = groupingNewPosIndexParent.child(extra, 0); } else { newPos -= groupingNewPosIndex.row(); groupingNewPosIndex = groupingNewPosIndexParent; } } beginMoveRows(QModelIndex(), (row - offset), (row - offset) + extraChildCount, QModelIndex(), (newPos > row) ? newPos + 1 : newPos); row = d->sortedPreFilterRows.indexOf(d->filterProxyModel->mapToSource(d->groupingProxyModel->mapToSource(groupingRowIndex)).row()); newPos = d->sortedPreFilterRows.indexOf(d->filterProxyModel->mapToSource(d->groupingProxyModel->mapToSource(groupingNewPosIndex)).row()); // Update sort mappings. d->sortedPreFilterRows.move(row, newPos); if (groupingRowIndexParent.isValid()) { d->consolidateManualSortMapForGroup(groupingRowIndexParent); } endMoveRows(); } else { beginMoveRows(parent, row, row, parent, (newPos > row) ? newPos + 1 : newPos); // Translate to sort map indices. const QModelIndex &groupingRowIndex = mapToSource(index(row, 0, parent)); const QModelIndex &preFilterRowIndex = d->preFilterIndex(groupingRowIndex); row = d->sortedPreFilterRows.indexOf(preFilterRowIndex.row()); newPos = d->sortedPreFilterRows.indexOf(d->preFilterIndex(mapToSource(index(newPos, 0, parent))).row()); // Update sort mapping. d->sortedPreFilterRows.move(row, newPos); // If we moved a group parent, consolidate sort map for children. if (!parent.isValid() && groupMode() != GroupDisabled && d->groupingProxyModel->rowCount(groupingRowIndex)) { d->consolidateManualSortMapForGroup(groupingRowIndex); } endMoveRows(); } // Resort. d->forceResort(); if (!d->separateLaunchers && isLauncherMove) { const QModelIndex &idx = d->concatProxyModel->index(d->sortedPreFilterRows.at(newPos), 0); const QUrl &launcherUrl = idx.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); // Move launcher for launcher-backed task along with task if launchers // are not being kept separate. // We don't need to resort again because the launcher is implictly hidden // at this time. if (!idx.data(AbstractTasksModel::IsLauncher).toBool()) { const int launcherPos = d->launcherTasksModel->launcherPosition(launcherUrl); const QModelIndex &launcherIndex = d->launcherTasksModel->index(launcherPos, 0); const int sortIndex = d->sortedPreFilterRows.indexOf(d->concatProxyModel->mapFromSource(launcherIndex).row()); d->sortedPreFilterRows.move(sortIndex, newPos); // Otherwise move matching windows to after the launcher task (they are // currently hidden but might be on another virtual desktop). } else { for (int i = (d->sortedPreFilterRows.count() - 1); i >= 0; --i) { const QModelIndex &concatProxyIndex = d->concatProxyModel->index(d->sortedPreFilterRows.at(i), 0); if (launcherUrl == concatProxyIndex.data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl()) { d->sortedPreFilterRows.move(i, newPos); if (newPos > i) { --newPos; } } } } } // Setup for syncLaunchers(). d->launcherSortingDirty = isLauncherMove; return true; } void TasksModel::syncLaunchers() { // Writes the launcher order exposed through the model back to the launcher // tasks model, committing any move() operations to persistent state. if (!d->launcherTasksModel || !d->launcherSortingDirty) { return; } QMap sortedShownLaunchers; QStringList sortedHiddenLaunchers; foreach(const QString &launcherUrlStr, launcherList()) { int row = -1; QStringList activities; QUrl launcherUrl; std::tie(launcherUrl, activities) = deserializeLauncher(launcherUrlStr); for (int i = 0; i < rowCount(); ++i) { const QUrl &rowLauncherUrl = index(i, 0).data(AbstractTasksModel::LauncherUrlWithoutIcon).toUrl(); if (launcherUrlsMatch(launcherUrl, rowLauncherUrl, IgnoreQueryItems)) { row = i; break; } } if (row != -1) { sortedShownLaunchers.insert(row, launcherUrlStr); } else { sortedHiddenLaunchers << launcherUrlStr; } } // Prep sort map for source model data changes. if (d->sortMode == SortManual) { QVector sortMapIndices; QVector preFilterRows; for (int i = 0; i < d->launcherTasksModel->rowCount(); ++i) { const QModelIndex &launcherIndex = d->launcherTasksModel->index(i, 0); const QModelIndex &concatIndex = d->concatProxyModel->mapFromSource(launcherIndex); sortMapIndices << d->sortedPreFilterRows.indexOf(concatIndex.row()); preFilterRows << concatIndex.row(); } // We're going to write back launcher model entries in the sort // map in concat model order, matching the reordered launcher list // we're about to pass down. std::sort(sortMapIndices.begin(), sortMapIndices.end()); for (int i = 0; i < sortMapIndices.count(); ++i) { d->sortedPreFilterRows.replace(sortMapIndices.at(i), preFilterRows.at(i)); } } setLauncherList(sortedShownLaunchers.values() + sortedHiddenLaunchers); d->launcherSortingDirty = false; } QModelIndex TasksModel::activeTask() const { for (int i = 0; i < rowCount(); ++i) { const QModelIndex &idx = index(i, 0); if (idx.data(AbstractTasksModel::IsActive).toBool()) { if (groupMode() != GroupDisabled && rowCount(idx)) { for (int j = 0; j < rowCount(idx); ++j) { const QModelIndex &child = idx.child(j, 0); if (child.data(AbstractTasksModel::IsActive).toBool()) { return child; } } } else { return idx; } } } return QModelIndex(); } QModelIndex TasksModel::makeModelIndex(int row, int childRow) const { if (row < 0 || row >= rowCount()) { return QModelIndex(); } if (childRow == -1) { return index(row, 0); } else { const QModelIndex &parent = index(row, 0); if (childRow < rowCount(parent)) { return parent.child(childRow, 0); } } return QModelIndex(); } QPersistentModelIndex TasksModel::makePersistentModelIndex(int row, int childCount) const { return QPersistentModelIndex(makeModelIndex(row, childCount)); } void TasksModel::classBegin() { d->usedByQml = true; } void TasksModel::componentComplete() { d->componentComplete = true; // Sets our source model, populating the model. d->updateGroupInline(); } bool TasksModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { // All our filtering occurs at the top-level; anything below always // goes through. if (sourceParent.isValid()) { return true; } const QModelIndex &sourceIndex = sourceModel()->index(sourceRow, 0); // In inline grouping mode, filter out group parents. if (d->groupInline && d->flattenGroupsProxyModel && sourceIndex.data(AbstractTasksModel::IsGroupParent).toBool()) { return false; } const QString &appId = sourceIndex.data(AbstractTasksModel::AppId).toString(); const QString &appName = sourceIndex.data(AbstractTasksModel::AppName).toString(); // Filter startup tasks we already have a window task for. if (sourceIndex.data(AbstractTasksModel::IsStartup).toBool()) { for (int i = 0; i < d->filterProxyModel->rowCount(); ++i) { const QModelIndex &filterIndex = d->filterProxyModel->index(i, 0); if (!filterIndex.data(AbstractTasksModel::IsWindow).toBool()) { continue; } if ((!appId.isEmpty() && appId == filterIndex.data(AbstractTasksModel::AppId).toString()) || (!appName.isEmpty() && appName == filterIndex.data(AbstractTasksModel::AppName).toString())) { return false; } } } // Filter launcher tasks we already have a startup or window task for (that // got through filtering). if (sourceIndex.data(AbstractTasksModel::IsLauncher).toBool()) { for (int i = 0; i < d->filterProxyModel->rowCount(); ++i) { const QModelIndex &filteredIndex = d->filterProxyModel->index(i, 0); if (!filteredIndex.data(AbstractTasksModel::IsWindow).toBool() && !filteredIndex.data(AbstractTasksModel::IsStartup).toBool()) { continue; } if (appsMatch(sourceIndex, filteredIndex)) { return false; } } } return true; } bool TasksModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { // In manual sort mode, sort by map. if (d->sortMode == SortManual) { return (d->sortedPreFilterRows.indexOf(d->preFilterIndex(left).row()) < d->sortedPreFilterRows.indexOf(d->preFilterIndex(right).row())); } return d->lessThan(left, right); } } diff --git a/libtaskmanager/tasksmodel.h b/libtaskmanager/tasksmodel.h index fef0924b7..1b71e6eef 100644 --- a/libtaskmanager/tasksmodel.h +++ b/libtaskmanager/tasksmodel.h @@ -1,865 +1,880 @@ /******************************************************************** 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 TASKSMODEL_H #define TASKSMODEL_H #include #include #include "abstracttasksmodeliface.h" #include "taskmanager_export.h" namespace TaskManager { /** * @short A unified tasks model. * * This model presents tasks sourced from supplied launcher URLs, startup * notification data and window data retrieved from the windowing server * the host process is connected to. The underlying windowing system is * abstracted away. * * The source data is abstracted into a unified lifecycle for tasks * suitable for presentation in a user interface. * * Matching startup and window tasks replace launcher tasks. Startup * tasks are omitted when matching window tasks exist. Tasks that desire * not to be shown in a user interface are omitted. * * Tasks may be filtered, sorted or grouped by setting properties on the * model. * * Tasks may be interacted with by calling methods on the model. * * @author Eike Hein **/ class TASKMANAGER_EXPORT TasksModel : public QSortFilterProxyModel, public AbstractTasksModelIface, public QQmlParserStatus { Q_OBJECT Q_INTERFACES(QQmlParserStatus) Q_PROPERTY(int count READ rowCount NOTIFY countChanged) Q_PROPERTY(int launcherCount READ launcherCount NOTIFY launcherCountChanged) Q_PROPERTY(QStringList launcherList READ launcherList WRITE setLauncherList NOTIFY launcherListChanged) Q_PROPERTY(bool anyTaskDemandsAttention READ anyTaskDemandsAttention NOTIFY anyTaskDemandsAttentionChanged) - Q_PROPERTY(int virtualDesktop READ virtualDesktop WRITE setVirtualDesktop NOTIFY virtualDesktopChanged) + Q_PROPERTY(QVariant 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(SortMode sortMode READ sortMode WRITE setSortMode NOTIFY sortModeChanged) Q_PROPERTY(bool separateLaunchers READ separateLaunchers WRITE setSeparateLaunchers NOTIFY separateLaunchersChanged) Q_PROPERTY(bool launchInPlace READ launchInPlace WRITE setLaunchInPlace NOTIFY launchInPlaceChanged) Q_PROPERTY(GroupMode groupMode READ groupMode WRITE setGroupMode NOTIFY groupModeChanged) Q_PROPERTY(bool groupInline READ groupInline WRITE setGroupInline NOTIFY groupInlineChanged) Q_PROPERTY(int groupingWindowTasksThreshold READ groupingWindowTasksThreshold WRITE setGroupingWindowTasksThreshold NOTIFY groupingWindowTasksThresholdChanged) Q_PROPERTY(QStringList groupingAppIdBlacklist READ groupingAppIdBlacklist WRITE setGroupingAppIdBlacklist NOTIFY groupingAppIdBlacklistChanged) Q_PROPERTY(QStringList groupingLauncherUrlBlacklist READ groupingLauncherUrlBlacklist WRITE setGroupingLauncherUrlBlacklist NOTIFY groupingLauncherUrlBlacklistChanged) Q_PROPERTY(QModelIndex activeTask READ activeTask NOTIFY activeTaskChanged) public: enum SortMode { SortDisabled = 0, /**< No sorting is done. */ SortManual, /**< Tasks can be moved with move() and syncLaunchers(). */ SortAlpha, /**< Tasks are sorted alphabetically, by AbstractTasksModel::AppName and Qt::DisplayRole. */ SortVirtualDesktop, /**< Tasks are sorted by the virtual desktop they are on. */ SortActivity /**< Tasks are sorted by the number of tasks on the activities they're on. */ }; Q_ENUM(SortMode) enum GroupMode { GroupDisabled = 0, /**< No grouping is done. */ GroupApplications /**< Tasks are grouped by the application backing them. */ }; Q_ENUM(GroupMode) explicit TasksModel(QObject *parent = nullptr); ~TasksModel() override; QHash roleNames() const override; Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const override; // Invokable. QVariant data(const QModelIndex &proxyIndex, int role) const override; /** * The number of launcher tasks in the tast list. * * @returns the number of launcher tasks in the task list. **/ int launcherCount() const; /** * The list of launcher URLs serialized to strings along with * the activities they belong to. * * @see setLauncherList * @returns the list of launcher URLs serialized to strings. **/ QStringList launcherList() const; /** * Replace the list of launcher URL strings. * * Invalid or empty URLs will be rejected. Duplicate URLs will be * collapsed. * * @see launcherList * @param launchers A list of launcher URL strings. **/ void setLauncherList(const QStringList &launchers); /** * Returns whether any task in the model currently demands attention * (AbstractTasksModel::IsDemandingAttention). * * @returns whether any task in the model currently demands attention. **/ bool anyTaskDemandsAttention() const; /** - * 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 -1. + * The id of the virtual desktop used in filtering by virtual + * desktop. Usually set to the id of the current virtual desktop. + * Defaults to empty. * * @see setVirtualDesktop * @returns the number of the virtual desktop used in filtering. **/ - int virtualDesktop() const; + QVariant virtualDesktop() const; /** - * Set the number of the virtual desktop to use in filtering by virtual + * Set the id of the virtual desktop to use in filtering by virtual * desktop. * - * If set to @c -1, filtering by virtual desktop is disabled. + * If set to an empty id, filtering by virtual desktop is disabled. * * @see virtualDesktop - * @param virtualDesktop A virtual desktop number. + * @param desktop A virtual desktop id (QString on Wayland; uint >0 on X11). **/ - void setVirtualDesktop(int virtualDesktop); + void setVirtualDesktop(const QVariant &desktop = QVariant()); /** * 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 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); /** * The sort mode used in sorting tasks. Defaults to SortAlpha. * * @see setSortMode * @returns the curent sort mode. **/ SortMode sortMode() const; /** * Sets the sort mode used in sorting tasks. * * @see sortMode * @param mode A sort mode. **/ void setSortMode(SortMode mode); /** * Whether launchers are kept separate from other kinds of tasks. * Defaults to @c true. * * When enabled, launcher tasks are sorted first in the tasks model * and move() disallows moving them below the last launcher task, * or moving a different kind of task above the first launcher. New * launcher tasks are inserted after the last launcher task. When * disabled, move() allows mixing, and new launcher tasks are * appended to the model. * * Further, when disabled, the model always behaves as if * launchInPlace is enabled: A window task takes the place of the * first matching launcher task. * * @see LauncherTasksModel * @see move * @see launchInPlace * @see setSeparateLaunchers * @return whether launcher tasks are kept separate. */ bool separateLaunchers() const; /** * Sets whether launchers are kept separate from other kinds of tasks. * * When enabled, launcher tasks are sorted first in the tasks model * and move() disallows moving them below the last launcher task, * or moving a different kind of task above the first launcher. New * launcher tasks are inserted after the last launcher task. When * disabled, move() allows mixing, and new launcher tasks are * appended to the model. * * Further, when disabled, the model always behaves as if * launchInPlace is enabled: A window task takes the place of the * first matching launcher task. * * @see LauncherTasksModel * @see move * @see launchInPlace * @see separateLaunchers * @param separate Whether to keep launcher tasks separate. */ void setSeparateLaunchers(bool separate); /** * Whether window tasks should be sorted as their associated launcher * tasks or separately. Defaults to @c false. * * @see setLaunchInPlace * @returns whether window tasks should be sorted as their associated * launcher tasks. **/ bool launchInPlace() const; /** * Sets whether window tasks should be sorted as their associated launcher * tasks or separately. * * @see launchInPlace * @param launchInPlace Whether window tasks should be sorted as their * associated launcher tasks. **/ void setLaunchInPlace(bool launchInPlace); /** * Returns the current group mode, i.e. the criteria by which tasks should * be grouped. * * Defaults to TasksModel::GroupApplication, which groups tasks backed by * the same application. * * If the group mode is TasksModel::GroupDisabled, no grouping is done. * * @see setGroupMode * @returns the current group mode. **/ TasksModel::GroupMode groupMode() const; /** * Sets the group mode, i.e. the criteria by which tasks should be grouped. * * The group mode can be set to TasksModel::GroupDisabled to disable grouping * entirely, breaking apart any existing groups. * * @see groupMode * @param mode A group mode. **/ void setGroupMode(TasksModel::GroupMode mode); /** * Returns whether grouping is done "inline" or not, i.e. whether groups * are maintained inside the flat, top-level list, or by forming a tree. * In inline grouping mode, move() on a group member will move all siblings * as well, and sorting is first done among groups, then group members. * * Further, in inline grouping mode, the groupingWindowTasksThreshold * setting is ignored: Grouping is always done. * * @see setGroupInline * @see move * @see groupingWindowTasksThreshold * @returns whether grouping is done inline or not. **/ bool groupInline() const; /** * Sets whether grouping is done "inline" or not, i.e. whether groups * are maintained inside the flat, top-level list, or by forming a tree. * In inline grouping mode, move() on a group member will move all siblings * as well, and sorting is first done among groups, then group members. * * @see groupInline * @see move * @see groupingWindowTasksThreshold * @param inline Whether to do grouping inline or not. **/ void setGroupInline(bool groupInline); /** * As window tasks (AbstractTasksModel::IsWindow) come and go, groups will * be formed when this threshold value is exceeded, and broken apart when * it matches or falls below. * * Defaults to @c -1, which means grouping is done regardless of the number * of window tasks. * * When the groupInline property is set to @c true, the threshold is ignored: * Grouping is always done. * * @see setGroupingWindowTasksThreshold * @see groupInline * @return the threshold number of window tasks used in grouping decisions. **/ int groupingWindowTasksThreshold() const; /** * Sets the number of window tasks (AbstractTasksModel::IsWindow) above which * groups will be formed, and at or below which groups will be broken apart. * * If set to -1, grouping will be done regardless of the number of window tasks * in the source model. * * When the groupInline property is set to @c true, the threshold is ignored: * Grouping is always done. * * @see groupingWindowTasksThreshold * @see groupInline * @param threshold A threshold number of window tasks used in grouping * decisions. **/ void setGroupingWindowTasksThreshold(int threshold); /** * A blacklist of app ids (AbstractTasksModel::AppId) that is consulted before * grouping a task. If a task's app id is found on the blacklist, it is not * grouped. * * The default app id blacklist is empty. * * @see setGroupingAppIdBlacklist * @returns the blacklist of app ids consulted before grouping a task. **/ QStringList groupingAppIdBlacklist() const; /** * Sets the blacklist of app ids (AbstractTasksModel::AppId) that is consulted * before grouping a task. If a task's app id is found on the blacklist, it is * not grouped. * * When set, groups will be formed and broken apart as necessary. * * @see groupingAppIdBlacklist * @param list a blacklist of app ids to be consulted before grouping a task. **/ void setGroupingAppIdBlacklist(const QStringList &list); /** * A blacklist of launcher URLs (AbstractTasksModel::LauncherUrl) that is * consulted before grouping a task. If a task's launcher URL is found on the * blacklist, it is not grouped. * * The default launcher URL blacklist is empty. * * @see setGroupingLauncherUrlBlacklist * @returns the blacklist of launcher URLs consulted before grouping a task. **/ QStringList groupingLauncherUrlBlacklist() const; /** * Sets the blacklist of launcher URLs (AbstractTasksModel::LauncherUrl) that * is consulted before grouping a task. If a task's launcher URL is found on * the blacklist, it is not grouped. * * When set, groups will be formed and broken apart as necessary. * * @see groupingLauncherUrlBlacklist * @param list a blacklist of launcher URLs to be consulted before grouping a task. **/ void setGroupingLauncherUrlBlacklist(const QStringList &list); /** * Finds the first active (AbstractTasksModel::IsActive) task in the model * and returns its QModelIndex, or a null QModelIndex if no active task is * found. * * @returns the model index for the first active task, if any. */ QModelIndex activeTask() const; /** * Request adding a launcher with the given URL. * * If this URL is already in the list, the request will fail. URLs are * compared for equality after removing the query string used to hold * metadata. * * @see launcherUrlsMatch * @param url A launcher URL. * @returns @c true if a launcher was added. */ Q_INVOKABLE bool requestAddLauncher(const QUrl &url); /** * Request removing the launcher with the given URL. * * If this URL is already in the list, the request will fail. URLs are * compared for equality after removing the query string used to hold * metadata. * * @see launcherUrlsMatch * @param url A launcher URL. * @returns @c true if the launcher was removed. */ Q_INVOKABLE bool requestRemoveLauncher(const QUrl &url); /** * Request adding a launcher with the given URL to current activity. * * If this URL is already in the list, the request will fail. URLs are * compared for equality after removing the query string used to hold * metadata. * * @see launcherUrlsMatch * @param url A launcher URL. * @returns @c true if a launcher was added. */ Q_INVOKABLE bool requestAddLauncherToActivity(const QUrl &url, const QString &activity); /** * Request removing the launcher with the given URL from the current activity. * * If this URL is already in the list, the request will fail. URLs are * compared for equality after removing the query string used to hold * metadata. * * @see launcherUrlsMatch * @param url A launcher URL. * @returns @c true if the launcher was removed. */ Q_INVOKABLE bool requestRemoveLauncherFromActivity(const QUrl &url, const QString &activity); /** * Return the list of activities the launcher belongs to. * If there is no launcher with that url, the list will be empty, * while if the launcher is on all activities, it will contain a * null uuid. * * URLs are compared for equality after removing the query string used * to hold metadata. */ Q_INVOKABLE QStringList launcherActivities(const QUrl &url); /** * Return the position of the launcher with the given URL. * * URLs are compared for equality after removing the query string used * to hold metadata. * * @see launcherUrlsMatch * @param url A launcher URL. * @returns @c -1 if no launcher exists for the given URL. */ Q_INVOKABLE int launcherPosition(const QUrl &url) const; /** * 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE void requestActivate(const QModelIndex &index) override; /** * Request an additional instance of the application backing the task * at the given index. * * @param index An index in this tasks model. **/ Q_INVOKABLE void requestNewInstance(const QModelIndex &index) override; /** * Requests to open the given URLs with the application backing the task * at the given index. * * @param index An index in this tasks model. * @param urls The URLs to be passed to the application. **/ Q_INVOKABLE void requestOpenUrls(const QModelIndex &index, const QList &urls) override; /** * Request the task at the given index be closed. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE 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. * * @param index An index in this tasks model. **/ Q_INVOKABLE void requestToggleShaded(const QModelIndex &index) override; /** - * Request moving the task at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktops. * - * This is meant for tasks that have an associated window, and may be - * a no-op when there is no window. + * On Wayland, virtual desktop ids are QStrings. On X11, they are uint >0. * - * @param index An index in this tasks model. - * @param desktop A virtual desktop number. + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. + * + * On X11, a window can only be on one or all virtual desktops. Therefore, only the + * first list entry is actually used. + * + * On X11, the id 0 has a special meaning: The window is entered on all virtual + * desktops in the session. + * + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids. + **/ + Q_INVOKABLE void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) override; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. + * + * @param index An index in this window tasks model. **/ - Q_INVOKABLE void requestVirtualDesktop(const QModelIndex &index, qint32 desktop) override; + Q_INVOKABLE void requestNewVirtualDesktop(const QModelIndex &index) 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. **/ Q_INVOKABLE 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. * * If the task at the given index is a group parent, the geometry is * set for all of its children. If the task at the given index is a * group member, the geometry is set for all of its siblings. * * @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. **/ Q_INVOKABLE void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; /** * Request toggling whether the task at the given index, along with any * tasks matching its kind, should be grouped or not. Task groups will be * formed or broken apart as needed, along with affecting future grouping * decisions as new tasks appear. * * As grouping is toggled for a task, updates are made to the * grouping*Blacklist properties of the model instance. * * @see groupingAppIdBlacklist * @see groupingLauncherUrlBlacklist * * @param index An index in this tasks model. **/ Q_INVOKABLE void requestToggleGrouping(const QModelIndex &index); /** * Moves a task to a new position in the list. The insert position is * is bounded to the list start and end. * * syncLaunchers() should be called after a set of move operations to * update the launcherList property to reflect the new order. * * When the groupInline property is set to @c true, a move request * for a group member will bring all siblings along. * * @see syncLaunchers * @see launcherList * @see setGroupInline * @param index An index in this tasks model. * @param newPos The new list position to move the task to. */ Q_INVOKABLE bool move(int row, int newPos, const QModelIndex &parent = QModelIndex()); /** * Updates the launcher list to reflect the new order after calls to * move(), if needed. * * @see move * @see launcherList */ Q_INVOKABLE void syncLaunchers(); /** * Given a row in the model, returns a QModelIndex for it. To get an index * for a child in a task group, an optional child row may be passed as well. * * This easier to use from Qt Quick views than QAbstractItemModel::index is. * * @param row A row index in the model. * @param childRow A row index for a child of the task group at the given row. * @returns a model index for the task at the given row, or for one of its * child tasks. */ Q_INVOKABLE QModelIndex makeModelIndex(int row, int childRow = -1) const; /** * Given a row in the model, returns a QPersistentModelIndex for it. To get an index * for a child in a task group, an optional child row may be passed as well. * * @param row A row index in the model. * @param childRow A row index for a child of the task group at the given row. * @returns a model index for the task at the given row, or for one of its * child tasks. */ Q_INVOKABLE QPersistentModelIndex makePersistentModelIndex(int row, int childRow = -1) const; void classBegin() override; void componentComplete() override; Q_SIGNALS: void countChanged() const; void launcherCountChanged() const; void launcherListChanged() const; void anyTaskDemandsAttentionChanged() const; void virtualDesktopChanged() const; void screenGeometryChanged() const; void activityChanged() const; void filterByVirtualDesktopChanged() const; void filterByScreenChanged() const; void filterByActivityChanged() const; void filterNotMinimizedChanged() const; void sortModeChanged() const; void separateLaunchersChanged() const; void launchInPlaceChanged() const; void groupModeChanged() const; void groupInlineChanged() const; void groupingWindowTasksThresholdChanged() const; void groupingAppIdBlacklistChanged() const; void groupingLauncherUrlBlacklistChanged() const; void activeTaskChanged() const; protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; private: Q_INVOKABLE void updateLauncherCount(); class Private; class TasksModelLessThan; friend class TasksModelLessThan; QScopedPointer d; }; } #endif diff --git a/libtaskmanager/virtualdesktopinfo.cpp b/libtaskmanager/virtualdesktopinfo.cpp index 3087855e9..2cc659cca 100644 --- a/libtaskmanager/virtualdesktopinfo.cpp +++ b/libtaskmanager/virtualdesktopinfo.cpp @@ -1,95 +1,476 @@ /******************************************************************** 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 "virtualdesktopinfo.h" +#include +#include +#include +#include #include #include #include #if HAVE_X11 #include #include #endif namespace TaskManager { +class Q_DECL_HIDDEN VirtualDesktopInfo::Private : public QObject +{ + Q_OBJECT -VirtualDesktopInfo::VirtualDesktopInfo(QObject *parent) : QObject(parent) +public: + Private(VirtualDesktopInfo *q); + virtual ~Private() {} + + uint refCount = 1; + + virtual void init() = 0; + virtual QVariant currentDesktop() const = 0; + virtual int numberOfDesktops() const = 0; + virtual QVariantList desktopIds() const = 0; + virtual QStringList desktopNames() const = 0; + virtual quint32 position(const QVariant &desktop) const = 0; + virtual int desktopLayoutRows() const = 0; + virtual void requestActivate(const QVariant &desktop) = 0; + virtual void requestCreateDesktop(quint32 position) = 0; + virtual void requestRemoveDesktop(quint32 position) = 0; + +Q_SIGNALS: + void currentDesktopChanged() const; + void numberOfDesktopsChanged() const; + void desktopIdsChanged() const; + void desktopNamesChanged() const; + void desktopLayoutRowsChanged() const; + +protected: + VirtualDesktopInfo *q; +}; + +VirtualDesktopInfo::Private::Private(VirtualDesktopInfo *q) + : q(q) +{ +} + +#if HAVE_X11 +class Q_DECL_HIDDEN VirtualDesktopInfo::XWindowPrivate : public VirtualDesktopInfo::Private +{ +public: + XWindowPrivate(VirtualDesktopInfo *q); + + void init() override; + QVariant currentDesktop() const override; + int numberOfDesktops() const override; + QVariantList desktopIds() const override; + QStringList desktopNames() const override; + quint32 position(const QVariant &desktop) const override; + int desktopLayoutRows() const override; + void requestActivate(const QVariant &desktop) override; + void requestCreateDesktop(quint32 position) override; + void requestRemoveDesktop(quint32 position) override; +}; + +VirtualDesktopInfo::XWindowPrivate::XWindowPrivate(VirtualDesktopInfo *q) + : VirtualDesktopInfo::Private(q) +{ + init(); +} + +void VirtualDesktopInfo::XWindowPrivate::init() { connect(KWindowSystem::self(), &KWindowSystem::currentDesktopChanged, - this, &VirtualDesktopInfo::currentDesktopChanged); + this, &VirtualDesktopInfo::XWindowPrivate::currentDesktopChanged); connect(KWindowSystem::self(), &KWindowSystem::numberOfDesktopsChanged, - this, &VirtualDesktopInfo::numberOfDesktopsChanged); + this, &VirtualDesktopInfo::XWindowPrivate::numberOfDesktopsChanged); connect(KWindowSystem::self(), &KWindowSystem::desktopNamesChanged, - this, &VirtualDesktopInfo::desktopNamesChanged); + this, &VirtualDesktopInfo::XWindowPrivate::desktopNamesChanged); -#if HAVE_X11 - if (KWindowSystem::isPlatformX11()) { - QDBusConnection dbus = QDBusConnection::sessionBus(); - dbus.connect(QString(), QStringLiteral("/KWin"), QStringLiteral("org.kde.KWin"), QStringLiteral("reloadConfig"), - this, SIGNAL(desktopLayoutRowsChanged())); - } -#endif + QDBusConnection dbus = QDBusConnection::sessionBus(); + dbus.connect(QString(), QStringLiteral("/KWin"), QStringLiteral("org.kde.KWin"), QStringLiteral("reloadConfig"), + this, SIGNAL(desktopLayoutRowsChanged())); } -VirtualDesktopInfo::~VirtualDesktopInfo() +QVariant VirtualDesktopInfo::XWindowPrivate::currentDesktop() const { + return KWindowSystem::currentDesktop(); } -int VirtualDesktopInfo::currentDesktop() const +int VirtualDesktopInfo::XWindowPrivate::numberOfDesktops() const { - return KWindowSystem::currentDesktop(); + return KWindowSystem::numberOfDesktops(); } -int VirtualDesktopInfo::numberOfDesktops() const +QVariantList VirtualDesktopInfo::XWindowPrivate::desktopIds() const { - return KWindowSystem::numberOfDesktops(); + QVariantList ids; + + for (int i = 1; i <= KWindowSystem::numberOfDesktops(); ++i) { + ids << i; + } + + return ids; } -QStringList VirtualDesktopInfo::desktopNames() const +QStringList VirtualDesktopInfo::XWindowPrivate::desktopNames() const { QStringList names; // Virtual desktop numbers start at 1. for (int i = 1; i <= KWindowSystem::numberOfDesktops(); ++i) { names << KWindowSystem::desktopName(i); } return names; } -int VirtualDesktopInfo::desktopLayoutRows() const +quint32 VirtualDesktopInfo::XWindowPrivate::position(const QVariant &desktop) const { -#if HAVE_X11 - if (KWindowSystem::isPlatformX11()) { - const NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops | NET::DesktopNames, NET::WM2DesktopLayout); - return info.desktopLayoutColumnsRows().height(); + bool ok = false; + + const quint32 desktopNumber = desktop.toUInt(&ok); + + if (!ok) { + return -1; + } + + return desktopNumber; +} + +int VirtualDesktopInfo::XWindowPrivate::desktopLayoutRows() const +{ + const NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops | NET::DesktopNames, NET::WM2DesktopLayout); + return info.desktopLayoutColumnsRows().height(); +} + +void VirtualDesktopInfo::XWindowPrivate::requestActivate(const QVariant &desktop) +{ + bool ok = false; + const int desktopNumber = desktop.toInt(&ok); + + // Virtual desktop numbers start at 1. + if (ok && desktopNumber > 0 && desktopNumber <= KWindowSystem::numberOfDesktops()) { + KWindowSystem::setCurrentDesktop(desktopNumber); } +} + +void VirtualDesktopInfo::XWindowPrivate::requestCreateDesktop(quint32 position) +{ + Q_UNUSED(position) + + NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops); + info.setNumberOfDesktops(info.numberOfDesktops() + 1); +} + +void VirtualDesktopInfo::XWindowPrivate::requestRemoveDesktop(quint32 position) +{ + Q_UNUSED(position) + + NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops); + + if (info.numberOfDesktops() > 1) { + info.setNumberOfDesktops(info.numberOfDesktops() - 1); + } +} #endif +class Q_DECL_HIDDEN VirtualDesktopInfo::WaylandPrivate : public VirtualDesktopInfo::Private +{ +public: + WaylandPrivate(VirtualDesktopInfo *q); + + QVariant currentVirtualDesktop; + QStringList virtualDesktops; + KWayland::Client::PlasmaVirtualDesktopManagement *virtualDesktopManagement = nullptr; + + void init() override; + void addDesktop(const QString &id, quint32 position); + QVariant currentDesktop() const override; + int numberOfDesktops() const override; + QVariantList desktopIds() const override; + QStringList desktopNames() const override; + quint32 position(const QVariant &desktop) const override; + int desktopLayoutRows() const override; + void requestActivate(const QVariant &desktop) override; + void requestCreateDesktop(quint32 position) override; + void requestRemoveDesktop(quint32 position) override; +}; + +VirtualDesktopInfo::WaylandPrivate::WaylandPrivate(VirtualDesktopInfo *q) + : VirtualDesktopInfo::Private(q) +{ + init(); +} + +void VirtualDesktopInfo::WaylandPrivate::init() +{ + if (!KWindowSystem::isPlatformWayland()) { + return; + } + + KWayland::Client::ConnectionThread *connection = KWayland::Client::ConnectionThread::fromApplication(q); + + if (!connection) { + return; + } + + KWayland::Client::Registry *registry = new KWayland::Client::Registry(q); + registry->create(connection); + + QObject::connect(registry, &KWayland::Client::Registry::plasmaVirtualDesktopManagementAnnounced, + [this, registry] (quint32 name, quint32 version) { + virtualDesktopManagement = registry->createPlasmaVirtualDesktopManagement(name, version, q); + + const QList &desktops = virtualDesktopManagement->desktops(); + + /* FIXME: PlasmaVirtualDesktopManagement doesn't have this ...? + QObject::connect(virtualDesktopManagement, &KWayland::Client::PlasmaVirtualDesktopManagement::interfaceAboutToBeReleased, q, + [this] { + virtualDesktops.clear(); + emit numberOfDesktopsChanged(); + emit currentDesktopChanged(); + emit desktopIdsChanged(); + emit desktopNamesChanged(); + emit desktopLayoutRowsChanged(); + } + ); + */ + + QObject::connect(virtualDesktopManagement, &KWayland::Client::PlasmaVirtualDesktopManagement::desktopCreated, q, + [this](const QString &id, quint32 position) { + addDesktop(id, position); + } + ); + + QObject::connect(virtualDesktopManagement, &KWayland::Client::PlasmaVirtualDesktopManagement::desktopRemoved, q, + [this](const QString &id) { + virtualDesktops.removeOne(id); + + emit numberOfDesktopsChanged(); + emit desktopIdsChanged(); + emit desktopNamesChanged(); + + if (currentVirtualDesktop == id) { + currentVirtualDesktop.clear(); + emit currentDesktopChanged(); + } + } + ); + } + ); + + registry->setup(); +} + +void VirtualDesktopInfo::WaylandPrivate::addDesktop(const QString &id, quint32 position) +{ + if (virtualDesktops.indexOf(id) != -1) { + return; + } + + virtualDesktops.insert(position, id); + + emit numberOfDesktopsChanged(); + emit desktopIdsChanged(); + emit desktopNamesChanged(); + + const KWayland::Client::PlasmaVirtualDesktop *desktop = virtualDesktopManagement->getVirtualDesktop(id); + + QObject::connect(desktop, &KWayland::Client::PlasmaVirtualDesktop::activated, q, + [desktop, this]() { + currentVirtualDesktop = desktop->id(); + emit currentDesktopChanged(); + } + ); + + if (desktop->isActive()) { + currentVirtualDesktop = id; + emit currentDesktopChanged(); + } +} + +QVariant VirtualDesktopInfo::WaylandPrivate::currentDesktop() const +{ + return currentVirtualDesktop; +} + +int VirtualDesktopInfo::WaylandPrivate::numberOfDesktops() const +{ + return virtualDesktops.count(); +} + +quint32 VirtualDesktopInfo::WaylandPrivate::position(const QVariant &desktop) const +{ + return virtualDesktops.indexOf(desktop.toString()); +} + +QVariantList VirtualDesktopInfo::WaylandPrivate::desktopIds() const +{ + QVariantList ids; + + foreach (const QString &id, virtualDesktops) { + ids << id; + } + + return ids; +} + +QStringList VirtualDesktopInfo::WaylandPrivate::desktopNames() const +{ + QStringList names; + + foreach(const QString &id, virtualDesktops) { + const KWayland::Client::PlasmaVirtualDesktop *desktop = virtualDesktopManagement->getVirtualDesktop(id); + + if (desktop) { + names << desktop->name(); + } + } + + return names; +} + +int VirtualDesktopInfo::WaylandPrivate::desktopLayoutRows() const +{ + // TODO FIXME: We don't have virtual desktop layout information in the Wayland + // protocol yet. return 0; } +void VirtualDesktopInfo::WaylandPrivate::requestActivate(const QVariant &desktop) +{ + KWayland::Client::PlasmaVirtualDesktop *desktopObj = virtualDesktopManagement->getVirtualDesktop(desktop.toString()); + + if (desktopObj) { + desktopObj->requestActivate(); + } +} + +void VirtualDesktopInfo::WaylandPrivate::requestCreateDesktop(quint32 position) +{ + virtualDesktopManagement->requestCreateVirtualDesktop(i18n("New Desktop"), position); +} + +void VirtualDesktopInfo::WaylandPrivate::requestRemoveDesktop(quint32 position) +{ + if (virtualDesktops.count() == 1) { + return; + } + + if (position > ((quint32)virtualDesktops.count() - 1)) { + return; + } + + virtualDesktopManagement->requestRemoveVirtualDesktop(virtualDesktops.at(position)); } + +VirtualDesktopInfo::Private* VirtualDesktopInfo::d = nullptr; + +VirtualDesktopInfo::VirtualDesktopInfo(QObject *parent) : QObject(parent) +{ + if (!d) { + #if HAVE_X11 + if (KWindowSystem::isPlatformX11()) { + d = new VirtualDesktopInfo::XWindowPrivate(this); + } else + #endif + { + d = new VirtualDesktopInfo::WaylandPrivate(this); + } + } else { + ++d->refCount; + } + + connect(d, &VirtualDesktopInfo::Private::currentDesktopChanged, + this, &VirtualDesktopInfo::currentDesktopChanged); + connect(d, &VirtualDesktopInfo::Private::numberOfDesktopsChanged, + this, &VirtualDesktopInfo::numberOfDesktopsChanged); + connect(d, &VirtualDesktopInfo::Private::desktopIdsChanged, + this, &VirtualDesktopInfo::desktopIdsChanged); + connect(d, &VirtualDesktopInfo::Private::desktopNamesChanged, + this, &VirtualDesktopInfo::desktopNamesChanged); + connect(d, &VirtualDesktopInfo::Private::desktopLayoutRowsChanged, + this, &VirtualDesktopInfo::desktopLayoutRowsChanged); +} + +VirtualDesktopInfo::~VirtualDesktopInfo() +{ + --d->refCount; + + if (!d->refCount) { + delete d; + d = nullptr; + } +} + +QVariant VirtualDesktopInfo::currentDesktop() const +{ + return d->currentDesktop(); +} + +int VirtualDesktopInfo::numberOfDesktops() const +{ + return d->numberOfDesktops(); +} + +QVariantList VirtualDesktopInfo::desktopIds() const +{ + return d->desktopIds(); +} + +QStringList VirtualDesktopInfo::desktopNames() const +{ + return d->desktopNames(); +} + +quint32 VirtualDesktopInfo::position(const QVariant &desktop) const +{ + return d->position(desktop); +} + +int VirtualDesktopInfo::desktopLayoutRows() const +{ + return d->desktopLayoutRows(); +} + +void VirtualDesktopInfo::requestActivate(const QVariant &desktop) +{ + d->requestActivate(desktop); +} + +void VirtualDesktopInfo::requestCreateDesktop(quint32 position) +{ + return d->requestCreateDesktop(position); +} + +void VirtualDesktopInfo::requestRemoveDesktop(quint32 position) +{ + return d->requestRemoveDesktop(position); +} + +} + +#include "virtualdesktopinfo.moc" diff --git a/libtaskmanager/virtualdesktopinfo.h b/libtaskmanager/virtualdesktopinfo.h index dd52310d7..2dc6ceb3b 100644 --- a/libtaskmanager/virtualdesktopinfo.h +++ b/libtaskmanager/virtualdesktopinfo.h @@ -1,99 +1,149 @@ /******************************************************************** 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 VIRTUALDESKTOPINFO_H #define VIRTUALDESKTOPINFO_H #include #include "taskmanager_export.h" namespace TaskManager { /** - * @short Provides basic virtual desktop information. + * @short Provides basic virtual desktop information. The underlying windowing + * system is abstracted away. * * This class provides basic information about the virtual desktops present * in the session as a set of notifiable properties. * - * @NOTE: This is a placeholder, to be moved into KWindowSystem (which it - * wraps) or the Task Manager applet backend (which used to fill this role - * in the past). - * - * @see KWindowSystem - * * @author Eike Hein **/ class TASKMANAGER_EXPORT VirtualDesktopInfo : public QObject { Q_OBJECT - Q_PROPERTY(int currentDesktop READ currentDesktop NOTIFY currentDesktopChanged) + Q_PROPERTY(QVariant currentDesktop READ currentDesktop NOTIFY currentDesktopChanged) Q_PROPERTY(int numberOfDesktops READ numberOfDesktops NOTIFY numberOfDesktopsChanged) + Q_PROPERTY(QVariantList desktopIds READ desktopIds NOTIFY desktopIdsChanged) Q_PROPERTY(QStringList desktopNames READ desktopNames NOTIFY desktopNamesChanged) Q_PROPERTY(int desktopLayoutRows READ desktopLayoutRows NOTIFY desktopLayoutRowsChanged) public: explicit VirtualDesktopInfo(QObject *parent = nullptr); ~VirtualDesktopInfo() override; /** * The currently active virtual desktop. * - * @returns the number of the currently active virtual desktop. + * @returns the id of the currently active virtual desktop. QString on + * Wayland; uint >0 on X11. **/ - int currentDesktop() const; + QVariant currentDesktop() const; /** * The number of virtual desktops present in the session. * * @returns the number of virtual desktops present in the session. **/ int numberOfDesktops() const; /** - * The names of all virtual desktops present in the session. Note that - * virtual desktops are indexed starting at 1, so the name for virtual - * desktop 1 is at index 0 in this list. + * The ids of all virtual desktops present in the session. + * + * On Wayland, the ids are QString. On X11, they are uint >0. + * + * @returns a the list of ids of the virtual desktops present in the + * session. + **/ + QVariantList desktopIds() const; + + /** + * The names of all virtual desktops present in the session. + * + * Note that on X11, virtual desktops are indexed starting at 1, so + * the name for virtual desktop 1 is at index 0 in this list. * - * @returns a the list of names for the virtual desktops present in the + * @returns the list of names of the virtual desktops present in the * session. **/ QStringList desktopNames() const; + /** + * Returns the position of the passed-in virtual desktop. + * @param desktop A virtual desktop id (QString on Wayland; uint >0 on X11). + * @returns the position of the virtual desktop, or -1 if the desktop + * id is not valid. + **/ + quint32 position(const QVariant &desktop) const; + /** * The number of rows in the virtual desktop layout. * * @returns the number of rows in the virtual desktop layout. **/ int desktopLayoutRows() const; + /** + * Request activating the passed-in virtual desktop. + * + * @param desktop A virtual desktop id (QString on Wayland; uint >0 on X11). + **/ + void requestActivate(const QVariant &desktop); + + /** + * Request adding a new virtual desktop at the specified position. + * + * On X11, the position parameter is ignored and the new desktop is always + * created at the end of the list. + * + * @param position The position of the requested new virtual desktop (ignored on X11). + **/ + void requestCreateDesktop(quint32 position); + + /** + * Request removing the virtual desktop at the specified position. + * + * On X11, the position parameter is ignored and the last desktop in the list + * is always the one removed. + * + * @param position The position of the virtual desktop to remove (ignored on X11). + **/ + void requestRemoveDesktop(quint32 position); + Q_SIGNALS: void currentDesktopChanged() const; void numberOfDesktopsChanged() const; + void desktopIdsChanged() const; void desktopNamesChanged() const; void desktopLayoutRowsChanged() const; + +private: + class Private; + class XWindowPrivate; + class WaylandPrivate; + static Private *d; }; } #endif diff --git a/libtaskmanager/waylandtasksmodel.cpp b/libtaskmanager/waylandtasksmodel.cpp index ffc236784..43f569213 100644 --- a/libtaskmanager/waylandtasksmodel.cpp +++ b/libtaskmanager/waylandtasksmodel.cpp @@ -1,608 +1,768 @@ /******************************************************************** Copyright 2016 Eike Hein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "waylandtasksmodel.h" #include "tasktools.h" +#include "virtualdesktopinfo.h" #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include #include +#include #include namespace TaskManager { class Q_DECL_HIDDEN WaylandTasksModel::Private { public: Private(WaylandTasksModel *q); QList windows; QHash appDataCache; KWayland::Client::PlasmaWindowManagement *windowManagement = nullptr; KSharedConfig::Ptr rulesConfig; KDirWatch *configWatcher = nullptr; + VirtualDesktopInfo *virtualDesktopInfo = nullptr; + static QUuid uuid; void init(); void initWayland(); void addWindow(KWayland::Client::PlasmaWindow *window); AppData appData(KWayland::Client::PlasmaWindow *window); QIcon icon(KWayland::Client::PlasmaWindow *window); + static QString mimeType(); + static QString groupMimeType(); + void dataChanged(KWayland::Client::PlasmaWindow *window, int role); void dataChanged(KWayland::Client::PlasmaWindow *window, const QVector &roles); private: WaylandTasksModel *q; }; +QUuid WaylandTasksModel::Private::uuid = QUuid::createUuid(); + WaylandTasksModel::Private::Private(WaylandTasksModel *q) : q(q) { } void WaylandTasksModel::Private::init() { auto clearCacheAndRefresh = [this] { if (!windows.count()) { return; } appDataCache.clear(); // Emit changes of all roles satisfied from app data cache. q->dataChanged(q->index(0, 0), q->index(windows.count() - 1, 0), QVector{Qt::DecorationRole, AbstractTasksModel::AppId, AbstractTasksModel::AppName, AbstractTasksModel::GenericName, AbstractTasksModel::LauncherUrl, AbstractTasksModel::LauncherUrlWithoutIcon, AbstractTasksModel::SkipTaskbar}); }; rulesConfig = KSharedConfig::openConfig(QStringLiteral("taskmanagerrulesrc")); configWatcher = new KDirWatch(q); foreach (const QString &location, QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)) { configWatcher->addFile(location + QLatin1String("/taskmanagerrulesrc")); } auto rulesConfigChange = [this, clearCacheAndRefresh] { rulesConfig->reparseConfiguration(); clearCacheAndRefresh(); }; QObject::connect(configWatcher, &KDirWatch::dirty, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::created, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::deleted, rulesConfigChange); + virtualDesktopInfo = new VirtualDesktopInfo(q); + initWayland(); } void WaylandTasksModel::Private::initWayland() { if (!KWindowSystem::isPlatformWayland()) { return; } KWayland::Client::ConnectionThread *connection = KWayland::Client::ConnectionThread::fromApplication(q); if (!connection) { return; } KWayland::Client::Registry *registry = new KWayland::Client::Registry(q); registry->create(connection); QObject::connect(registry, &KWayland::Client::Registry::plasmaWindowManagementAnnounced, [this, registry] (quint32 name, quint32 version) { windowManagement = registry->createPlasmaWindowManagement(name, version, q); QObject::connect(windowManagement, &KWayland::Client::PlasmaWindowManagement::interfaceAboutToBeReleased, q, [this] { q->beginResetModel(); windows.clear(); q->endResetModel(); } ); QObject::connect(windowManagement, &KWayland::Client::PlasmaWindowManagement::windowCreated, q, [this](KWayland::Client::PlasmaWindow *window) { addWindow(window); } ); const auto windows = windowManagement->windows(); for (auto it = windows.constBegin(); it != windows.constEnd(); ++it) { addWindow(*it); } } ); registry->setup(); } void WaylandTasksModel::Private::addWindow(KWayland::Client::PlasmaWindow *window) { if (windows.indexOf(window) != -1) { return; } const int count = windows.count(); q->beginInsertRows(QModelIndex(), count, count); windows.append(window); q->endInsertRows(); auto removeWindow = [window, this] { const int row = windows.indexOf(window); if (row != -1) { q->beginRemoveRows(QModelIndex(), row, row); windows.removeAt(row); appDataCache.remove(window); q->endRemoveRows(); } }; QObject::connect(window, &KWayland::Client::PlasmaWindow::unmapped, q, removeWindow); QObject::connect(window, &QObject::destroyed, q, removeWindow); QObject::connect(window, &KWayland::Client::PlasmaWindow::titleChanged, q, [window, this] { this->dataChanged(window, Qt::DisplayRole); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::iconChanged, q, [window, this] { // The icon in the AppData struct might come from PlasmaWindow if it wasn't // filled in by windowUrlFromMetadata+appDataFromUrl. // TODO: Don't evict the cache unnecessarily if this isn't the case. As icons // are currently very static on Wayland, this eviction is unlikely to happen // frequently as of now. appDataCache.remove(window); this->dataChanged(window, Qt::DecorationRole); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::appIdChanged, q, [window, this] { // The AppData struct in the cache is derived from this and needs // to be evicted in favor of a fresh struct based on the changed // window metadata. appDataCache.remove(window); // Refresh roles satisfied from the app data cache. this->dataChanged(window, QVector{AppId, AppName, GenericName, LauncherUrl, LauncherUrlWithoutIcon, SkipTaskbar}); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::activeChanged, q, [window, this] { this->dataChanged(window, IsActive); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::closeableChanged, q, [window, this] { this->dataChanged(window, IsClosable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::movableChanged, q, [window, this] { this->dataChanged(window, IsMovable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::resizableChanged, q, [window, this] { this->dataChanged(window, IsResizable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::fullscreenableChanged, q, [window, this] { this->dataChanged(window, IsFullScreenable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::fullscreenChanged, q, [window, this] { this->dataChanged(window, IsFullScreen); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::maximizeableChanged, q, [window, this] { this->dataChanged(window, IsMaximizable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::maximizedChanged, q, [window, this] { this->dataChanged(window, IsMaximized); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::minimizeableChanged, q, [window, this] { this->dataChanged(window, IsMinimizable); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::minimizedChanged, q, [window, this] { this->dataChanged(window, IsMinimized); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::keepAboveChanged, q, [window, this] { this->dataChanged(window, IsKeepAbove); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::keepBelowChanged, q, [window, this] { this->dataChanged(window, IsKeepBelow); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::shadeableChanged, q, [window, this] { this->dataChanged(window, IsShadeable); } ); - QObject::connect(window, &KWayland::Client::PlasmaWindow::virtualDesktopChangeableChanged, q, - [window, this] { this->dataChanged(window, IsVirtualDesktopChangeable); } - ); +// FIXME +// QObject::connect(window, &KWayland::Client::PlasmaWindow::virtualDesktopChangeableChanged, q, +// // TODO: This is marked deprecated in KWayland, but (IMHO) shouldn't be. +// [window, this] { this->dataChanged(window, IsVirtualDesktopsChangeable); } +// ); + + QObject::connect(window, &KWayland::Client::PlasmaWindow::plasmaVirtualDesktopEntered, q, + [window, this] { + this->dataChanged(window, VirtualDesktops); - QObject::connect(window, &KWayland::Client::PlasmaWindow::virtualDesktopChanged, q, - [window, this] { this->dataChanged(window, VirtualDesktop); } + // If the count has changed from 0, the window may no longer be on all virtual + // desktops. + if (window->plasmaVirtualDesktops().count() > 0) { + this->dataChanged(window, VirtualDesktops); + } + } ); - QObject::connect(window, &KWayland::Client::PlasmaWindow::onAllDesktopsChanged, q, - [window, this] { this->dataChanged(window, IsOnAllVirtualDesktops); } + QObject::connect(window, &KWayland::Client::PlasmaWindow::plasmaVirtualDesktopLeft, q, + [window, this] { + this->dataChanged(window, VirtualDesktops); + + // If the count has changed to 0, the window is now on all virtual desktops. + if (window->plasmaVirtualDesktops().count() == 0) { + this->dataChanged(window, VirtualDesktops); + } + } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::geometryChanged, q, [window, this] { this->dataChanged(window, QVector{Geometry, ScreenGeometry}); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::demandsAttentionChanged, q, [window, this] { this->dataChanged(window, IsDemandingAttention); } ); QObject::connect(window, &KWayland::Client::PlasmaWindow::skipTaskbarChanged, q, [window, this] { this->dataChanged(window, SkipTaskbar); } ); } AppData WaylandTasksModel::Private::appData(KWayland::Client::PlasmaWindow *window) { const auto &it = appDataCache.constFind(window); if (it != appDataCache.constEnd()) { return *it; } const AppData &data = appDataFromUrl(windowUrlFromMetadata(window->appId(), window->pid(), rulesConfig)); appDataCache.insert(window, data); return data; } QIcon WaylandTasksModel::Private::icon(KWayland::Client::PlasmaWindow *window) { const AppData &app = appData(window); if (!app.icon.isNull()) { return app.icon; } appDataCache[window].icon = window->icon(); return window->icon(); } +QString WaylandTasksModel::Private::mimeType() +{ + // Use a unique format id to make this intentionally useless for + // cross-process DND. + return QString("windowsystem/winid+" + uuid.toString().toAscii()); +} + +QString WaylandTasksModel::Private::groupMimeType() +{ + // Use a unique format id to make this intentionally useless for + // cross-process DND. + return QString("windowsystem/multiple-winids+" + uuid.toString().toAscii()); +} + void WaylandTasksModel::Private::dataChanged(KWayland::Client::PlasmaWindow *window, int role) { QModelIndex idx = q->index(windows.indexOf(window)); emit q->dataChanged(idx, idx, QVector{role}); } void WaylandTasksModel::Private::dataChanged(KWayland::Client::PlasmaWindow *window, const QVector &roles) { QModelIndex idx = q->index(windows.indexOf(window)); emit q->dataChanged(idx, idx, roles); } WaylandTasksModel::WaylandTasksModel(QObject *parent) : AbstractWindowTasksModel(parent) , d(new Private(this)) { d->init(); } WaylandTasksModel::~WaylandTasksModel() = default; QVariant WaylandTasksModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->windows.count()) { return QVariant(); } KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); if (role == Qt::DisplayRole) { return window->title(); } else if (role == Qt::DecorationRole) { return d->icon(window); } else if (role == AppId) { const QString &id = d->appData(window).id; if (id.isEmpty()) { return window->appId(); } else { return id; } } else if (role == AppName) { return d->appData(window).name; } else if (role == GenericName) { return d->appData(window).genericName; } else if (role == LauncherUrl || role == LauncherUrlWithoutIcon) { return d->appData(window).url; + } else if (role == WinIdList) { + return QVariantList() << window->internalId(); + } else if (role == MimeType) { + return d->mimeType(); + } else if (role == MimeData) { + return QByteArray::number(window->internalId()); } else if (role == IsWindow) { return true; } else if (role == IsActive) { return window->isActive(); } else if (role == IsClosable) { return window->isCloseable(); } else if (role == IsMovable) { return window->isMovable(); } else if (role == IsResizable) { return window->isResizable(); } else if (role == IsMaximizable) { return window->isMaximizeable(); } else if (role == IsMaximized) { return window->isMaximized(); } else if (role == IsMinimizable) { return window->isMinimizeable(); } else if (role == IsMinimized) { return window->isMinimized(); } else if (role == IsKeepAbove) { return window->isKeepAbove(); } else if (role == IsKeepBelow) { return window->isKeepBelow(); } else if (role == IsFullScreenable) { return window->isFullscreenable(); } else if (role == IsFullScreen) { return window->isFullscreen(); } else if (role == IsShadeable) { return window->isShadeable(); } else if (role == IsShaded) { return window->isShaded(); - } else if (role == IsVirtualDesktopChangeable) { - return window->isVirtualDesktopChangeable(); - } else if (role == VirtualDesktop) { - return window->virtualDesktop(); + } else if (role == IsVirtualDesktopsChangeable) { + // FIXME Currently not implemented in KWayland. + return true; + } else if (role == VirtualDesktops) { + return window->plasmaVirtualDesktops(); } else if (role == IsOnAllVirtualDesktops) { - return window->isOnAllDesktops(); + return window->plasmaVirtualDesktops().isEmpty(); } else if (role == Geometry) { return window->geometry(); } else if (role == ScreenGeometry) { return screenGeometry(window->geometry().center()); } else if (role == Activities) { // FIXME Implement. } else if (role == IsDemandingAttention) { return window->isDemandingAttention(); } else if (role == SkipTaskbar) { return window->skipTaskbar() || d->appData(window).skipTaskbar; } else if (role == SkipPager) { // FIXME Implement. } else if (role == AppPid) { return window->pid(); } return QVariant(); } int WaylandTasksModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->windows.count(); } QModelIndex WaylandTasksModel::index(int row, int column, const QModelIndex &parent) const { return hasIndex(row, column, parent) ? createIndex(row, column, d->windows.at(row)) : QModelIndex(); } void WaylandTasksModel::requestActivate(const QModelIndex &index) { // FIXME Lacks transient handling of the XWindows version. if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestActivate(); } void WaylandTasksModel::requestNewInstance(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } runApp(d->appData(d->windows.at(index.row()))); } void WaylandTasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count() || urls.isEmpty()) { return; } runApp(d->appData(d->windows.at(index.row())), urls); } void WaylandTasksModel::requestClose(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestClose(); } void WaylandTasksModel::requestMove(const QModelIndex &index) { - // FIXME Move-to-desktop logic from XWindows version. (See also others.) - if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } - d->windows.at(index.row())->requestMove(); + KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); + + const QString ¤tDesktop = d->virtualDesktopInfo->currentDesktop().toString(); + + if (!currentDesktop.isEmpty()) { + window->requestEnterVirtualDesktop(currentDesktop); + } + + window->requestMove(); } void WaylandTasksModel::requestResize(const QModelIndex &index) { - // FIXME Move-to-desktop logic from XWindows version. (See also others.) - if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } - d->windows.at(index.row())->requestResize(); + KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); + + const QString ¤tDesktop = d->virtualDesktopInfo->currentDesktop().toString(); + + if (!currentDesktop.isEmpty()) { + window->requestEnterVirtualDesktop(currentDesktop); + } + + window->requestResize(); } void WaylandTasksModel::requestToggleMinimized(const QModelIndex &index) { - // FIXME Move-to-desktop logic from XWindows version. (See also others.) - if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } - d->windows.at(index.row())->requestToggleMinimized(); + KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); + + const QString ¤tDesktop = d->virtualDesktopInfo->currentDesktop().toString(); + + if (!currentDesktop.isEmpty()) { + window->requestEnterVirtualDesktop(currentDesktop); + } + + window->requestToggleMinimized(); } void WaylandTasksModel::requestToggleMaximized(const QModelIndex &index) { - // FIXME Move-to-desktop logic from XWindows version. (See also others.) - if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } - d->windows.at(index.row())->requestToggleMaximized(); + KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); + + const QString ¤tDesktop = d->virtualDesktopInfo->currentDesktop().toString(); + + if (!currentDesktop.isEmpty()) { + window->requestEnterVirtualDesktop(currentDesktop); + } + + window->requestToggleMaximized(); } void WaylandTasksModel::requestToggleKeepAbove(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleKeepAbove(); } void WaylandTasksModel::requestToggleKeepBelow(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleKeepBelow(); } void WaylandTasksModel::requestToggleFullScreen(const QModelIndex &index) { Q_UNUSED(index) // FIXME Implement. } void WaylandTasksModel::requestToggleShaded(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } d->windows.at(index.row())->requestToggleShaded(); } -void WaylandTasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) +void WaylandTasksModel::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) { - // FIXME Lacks add-new-desktop code from XWindows version. - // FIXME Does this do the set-on-all-desktops stuff from the XWindows version? + // FIXME TODO: Lacks the "if we've requested the current desktop, force-activate + // the window" logic from X11 version. This behavior should be in KWin rather than + // libtm however. if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } - d->windows.at(index.row())->requestVirtualDesktop(desktop); + KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); + + if (desktops.isEmpty()) { + foreach (const QVariant &desktop, window->plasmaVirtualDesktops()) { + window->requestLeaveVirtualDesktop(desktop.toString()); + } + } else { + const QStringList &now = window->plasmaVirtualDesktops(); + QStringList next; + + foreach (const QVariant &desktop, desktops) { + const QString &desktopId = desktop.toString(); + + if (!desktopId.isEmpty()) { + next << desktopId; + + if (!now.contains(desktopId)) { + window->requestEnterVirtualDesktop(desktopId); + } + } + } + + foreach (const QString &desktop, now) { + if (!next.contains(desktop)) { + window->requestLeaveVirtualDesktop(desktop); + } + } + } +} + +void WaylandTasksModel::requestNewVirtualDesktop(const QModelIndex &index) +{ + if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { + return; + } + + d->windows.at(index.row())->requestEnterNewVirtualDesktop(); } void WaylandTasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { Q_UNUSED(index) Q_UNUSED(activities) } void WaylandTasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { /* FIXME: This introduces the dependency on Qt5::Quick. I might prefer reversing this and publishing the window pointer through the model, then calling PlasmaWindow::setMinimizeGeometry in the applet backend, rather than hand delegate items into the lib, keeping the lib more UI- agnostic. */ Q_UNUSED(geometry) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const QQuickItem *item = qobject_cast(delegate); if (!item || !item->parentItem() || !item->window()) { return; } QWindow *itemWindow = item->window(); if (!itemWindow) { return; } using namespace KWayland::Client; Surface *surface = Surface::fromWindow(itemWindow); if (!surface) { return; } QRect rect(item->x(), item->y(), item->width(), item->height()); rect.moveTopLeft(item->parentItem()->mapToScene(rect.topLeft()).toPoint()); KWayland::Client::PlasmaWindow *window = d->windows.at(index.row()); window->setMinimizedGeometry(surface, rect); } +quint32 WaylandTasksModel::winIdFromMimeData(const QMimeData *mimeData, bool *ok) +{ + Q_ASSERT(mimeData); + + if (ok) { + *ok = false; + } + + if (!mimeData->hasFormat(Private::mimeType())) { + return 0; + } + + quint32 id = mimeData->data(Private::mimeType()).toUInt(ok); + + return id; +} + +QList WaylandTasksModel::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; + } + + // FIXME: Extracting multiple winids is still unimplemented; + // TaskGroupingProxy::data(..., ::MimeData) can't produce + // a payload with them anyways. + + return ids; +} + } diff --git a/libtaskmanager/waylandtasksmodel.h b/libtaskmanager/waylandtasksmodel.h index d208a7fe8..c1d95baeb 100644 --- a/libtaskmanager/waylandtasksmodel.h +++ b/libtaskmanager/waylandtasksmodel.h @@ -1,214 +1,242 @@ /******************************************************************** 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 WAYLANDTASKSMODEL_H #define WAYLANDTASKSMODEL_H #include "abstractwindowtasksmodel.h" #include "taskmanager_export.h" namespace KWayland { namespace Client { class PlasmaWindowManagement; class Surface; } } namespace TaskManager { /** * @short A tasks model for Wayland windows. * * This model presents tasks sourced from window data on the Wayland * server the host process is connected to. * * FIXME: Filtering by window type still needed. - * FIXME: Support for taskmanagerrulesrc (maybe) still needed. + * + * @see WindowTasksModel * * @author Eike Hein */ class TASKMANAGER_EXPORT WaylandTasksModel : public AbstractWindowTasksModel { Q_OBJECT public: explicit WaylandTasksModel(QObject *parent = nullptr); ~WaylandTasksModel() override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const override; /** * Request activation of the window at the given index. * * FIXME: Lacks transient handling of X Windows version. * * @param index An index in this window tasks model. **/ void requestActivate(const QModelIndex &index) override; /** * Request an additional instance of the application owning the window * at the given index. Success depends on whether a * AbstractTasksModel::LauncherUrl could be derived from window metadata. * * @param index An index in this window tasks model. **/ void requestNewInstance(const QModelIndex &index) override; /** * Runs the application backing the launcher at the given index with the given URLs. * Success depends on whether a AbstractTasksModel::LauncherUrl could be * derived from window metadata and a KService could be found from that. * * @param index An index in this launcher tasks model * @param urls The URLs to be passed to the application */ void requestOpenUrls(const QModelIndex &index, const QList &urls) override; /** * Request the window at the given index be closed. * * @param index An index in this window tasks model. **/ void requestClose(const QModelIndex &index) override; /** * Request starting an interactive move for the window at the given index. * * FIXME: X Windows version has extra virtual desktop logic. * * @param index An index in this window tasks model. **/ void requestMove(const QModelIndex &index) override; /** * Request starting an interactive move for the window at the given index. * * FIXME: X Windows version has extra virtual desktop logic. * * @param index An index in this window tasks model. **/ void requestResize(const QModelIndex &index) override; /** * Request toggling the minimized state of the window at the given index. * * FIXME: X Windows version has extra virtual desktop logic. * * @param index An index in this window tasks model. **/ void requestToggleMinimized(const QModelIndex &index) override; /** * Request toggling the maximized state of the task at the given index. * * FIXME: X Windows version has extra virtual desktop logic. * * @param index An index in this window tasks model. **/ void requestToggleMaximized(const QModelIndex &index) override; /** * Request toggling the keep-above state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleKeepAbove(const QModelIndex &index) override; /** * Request toggling the keep-below state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleKeepBelow(const QModelIndex &index) override; /** * Request toggling the fullscreen state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleFullScreen(const QModelIndex &index) override; /** * Request toggling the shaded state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleShaded(const QModelIndex &index) override; /** - * Request moving the window at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktops, + * leaving any other desktops. * - * FIXME: X Windows version has extra virtual desktop logic. + * Virtual desktop ids are QStrings. + * + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. + * + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids. + **/ + void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) override; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. * * @param index An index in this window tasks model. - * @param desktop A virtual desktop number. **/ - void requestVirtualDesktop(const QModelIndex &index, qint32 desktop) override; + void requestNewVirtualDesktop(const QModelIndex &index) override; /** * Request moving the window at the given index to the specified activities * * FIXME: This currently does nothing as activities is not implementated in kwin/kwayland * * @param index An index in this window tasks model. * @param desktop A virtual desktop number. **/ void requestActivities(const QModelIndex &index, const QStringList &activities) override; /** * Request informing the window manager of new geometry for a visual * delegate for the window at the given index. The geometry is retrieved * from the delegate object passed. Right now, QQuickItem is the only * supported delegate object type. * * FIXME: This introduces the dependency on Qt5::Quick. I might prefer * reversing this and publishing the window pointer through the model, * then calling PlasmaWindow::setMinimizeGeometry in the applet backend, * rather than hand delegate items into the lib, keeping the lib more UI- * agnostic. * * @param index An index in this window tasks model. * @param geometry Visual delegate geometry in screen coordinates. Unused * in this implementation. * @param delegate The delegate. This implementation will attempt to cast * it to QQuickItem, map its coordinates to its window and find the Wayland * Surface for the window. **/ void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; + /** + * Tries to extract a process-internal Wayland window id from supplied mime data. + * + * @param mimeData Some mime data. + * @param @ok Set to true or false on success or failure. + */ + static quint32 winIdFromMimeData(const QMimeData *mimeData, bool *ok = nullptr); + + /** + * Tries to extract process-internal Wayland window ids from supplied mime data. + * + * @param mimeData Some mime data. + * @param @ok Set to true or false on success or failure. + */ + static QList winIdsFromMimeData(const QMimeData *mimeData, bool *ok = nullptr); + private: class Private; QScopedPointer d; }; } #endif diff --git a/libtaskmanager/windowtasksmodel.cpp b/libtaskmanager/windowtasksmodel.cpp index 663f58607..5ca2ef81e 100644 --- a/libtaskmanager/windowtasksmodel.cpp +++ b/libtaskmanager/windowtasksmodel.cpp @@ -1,110 +1,109 @@ /******************************************************************** 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 "windowtasksmodel.h" #include #include "waylandtasksmodel.h" #if HAVE_X11 #include "xwindowtasksmodel.h" #endif #include namespace TaskManager { class Q_DECL_HIDDEN WindowTasksModel::Private { public: Private(WindowTasksModel *q); ~Private(); static int instanceCount; static AbstractTasksModel* sourceTasksModel; void initSourceTasksModel(); private: WindowTasksModel *q; }; int WindowTasksModel::Private::instanceCount = 0; AbstractTasksModel* WindowTasksModel::Private::sourceTasksModel = nullptr; WindowTasksModel::Private::Private(WindowTasksModel *q) : q(q) { ++instanceCount; } WindowTasksModel::Private::~Private() { --instanceCount; - if (!instanceCount) { delete sourceTasksModel; sourceTasksModel = nullptr; } } void WindowTasksModel::Private::initSourceTasksModel() { if (!sourceTasksModel && KWindowSystem::isPlatformWayland()) { sourceTasksModel = new WaylandTasksModel(); } #if HAVE_X11 if (!sourceTasksModel && KWindowSystem::isPlatformX11()) { sourceTasksModel = new XWindowTasksModel(); } #endif q->setSourceModel(sourceTasksModel); } WindowTasksModel::WindowTasksModel(QObject *parent) : QIdentityProxyModel(parent) , d(new Private(this)) { d->initSourceTasksModel(); } WindowTasksModel::~WindowTasksModel() { } QHash WindowTasksModel::roleNames() const { if (d->sourceTasksModel) { return d->sourceTasksModel->roleNames(); } return QHash(); } QModelIndex WindowTasksModel::mapIfaceToSource(const QModelIndex &index) const { return mapToSource(index); } } diff --git a/libtaskmanager/windowtasksmodel.h b/libtaskmanager/windowtasksmodel.h index cdb8f4a7b..d9bca8246 100644 --- a/libtaskmanager/windowtasksmodel.h +++ b/libtaskmanager/windowtasksmodel.h @@ -1,62 +1,65 @@ /******************************************************************** 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 WINDOWTASKSMODEL_H #define WINDOWTASKSMODEL_H #include #include "abstracttasksproxymodeliface.h" #include "taskmanager_export.h" namespace TaskManager { /** * @short A window tasks model. * * This model presents tasks sourced from window data retrieved from the * windowing server the host process is connected to. The underlying * windowing system is abstracted away. * + * @see WaylandTasksModel + * @see XWindowTasksModel + * * @author Eike Hein **/ class TASKMANAGER_EXPORT WindowTasksModel : public QIdentityProxyModel, public AbstractTasksProxyModelIface { Q_OBJECT public: explicit WindowTasksModel(QObject *parent = nullptr); ~WindowTasksModel() override; QHash roleNames() const override; protected: QModelIndex mapIfaceToSource(const QModelIndex &index) const override; private: class Private; QScopedPointer d; }; } #endif diff --git a/libtaskmanager/xwindowtasksmodel.cpp b/libtaskmanager/xwindowtasksmodel.cpp index babfd234d..ae892a064 100644 --- a/libtaskmanager/xwindowtasksmodel.cpp +++ b/libtaskmanager/xwindowtasksmodel.cpp @@ -1,1071 +1,1096 @@ /******************************************************************** Copyright 2016 Eike Hein Copyright 2008 Aaron J. Seigo This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . *********************************************************************/ #include "xwindowtasksmodel.h" #include "tasktools.h" #include "xwindowsystemeventbatcher.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace TaskManager { static const NET::Properties windowInfoFlags = NET::WMState | NET::XAWMState | NET::WMDesktop | NET::WMVisibleName | NET::WMGeometry | NET::WMFrameExtents | NET::WMWindowType | NET::WMPid; static const NET::Properties2 windowInfoFlags2 = NET::WM2DesktopFileName | NET::WM2Activities | NET::WM2WindowClass | NET::WM2AllowedActions; class Q_DECL_HIDDEN XWindowTasksModel::Private { public: Private(XWindowTasksModel *q); ~Private(); QVector windows; QSet transients; QMultiHash transientsDemandingAttention; QHash windowInfoCache; QHash appDataCache; QHash delegateGeometries; QSet usingFallbackIcon; WId activeWindow = -1; KSharedConfig::Ptr rulesConfig; KDirWatch *configWatcher = nullptr; QTimer sycocaChangeTimer; void init(); void addWindow(WId window); void removeWindow(WId window); void windowChanged(WId window, NET::Properties properties, NET::Properties2 properties2); void transientChanged(WId window, NET::Properties properties, NET::Properties2 properties2); void dataChanged(WId window, const QVector &roles); KWindowInfo* windowInfo(WId window); AppData appData(WId window); QIcon icon(WId window); static QString mimeType(); static QString groupMimeType(); QUrl windowUrl(WId window); QUrl launcherUrl(WId window, bool encodeFallbackIcon = true); bool demandsAttention(WId window); private: XWindowTasksModel *q; }; XWindowTasksModel::Private::Private(XWindowTasksModel *q) : q(q) { } XWindowTasksModel::Private::~Private() { qDeleteAll(windowInfoCache); windowInfoCache.clear(); } void XWindowTasksModel::Private::init() { auto clearCacheAndRefresh = [this] { if (!windows.count()) { return; } appDataCache.clear(); // Emit changes of all roles satisfied from app data cache. q->dataChanged(q->index(0, 0), q->index(windows.count() - 1, 0), QVector{Qt::DecorationRole, AbstractTasksModel::AppId, AbstractTasksModel::AppName, AbstractTasksModel::GenericName, AbstractTasksModel::LauncherUrl, AbstractTasksModel::LauncherUrlWithoutIcon, AbstractTasksModel::SkipTaskbar}); }; sycocaChangeTimer.setSingleShot(true); sycocaChangeTimer.setInterval(100); QObject::connect(&sycocaChangeTimer, &QTimer::timeout, q, clearCacheAndRefresh); void (KSycoca::*myDatabaseChangeSignal)(const QStringList &) = &KSycoca::databaseChanged; QObject::connect(KSycoca::self(), myDatabaseChangeSignal, q, [this](const QStringList &changedResources) { if (changedResources.contains(QLatin1String("services")) || changedResources.contains(QLatin1String("apps")) || changedResources.contains(QLatin1String("xdgdata-apps"))) { sycocaChangeTimer.start(); } } ); rulesConfig = KSharedConfig::openConfig(QStringLiteral("taskmanagerrulesrc")); configWatcher = new KDirWatch(q); foreach (const QString &location, QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)) { configWatcher->addFile(location + QLatin1String("/taskmanagerrulesrc")); } auto rulesConfigChange = [this, clearCacheAndRefresh] { rulesConfig->reparseConfiguration(); clearCacheAndRefresh(); }; QObject::connect(configWatcher, &KDirWatch::dirty, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::created, rulesConfigChange); QObject::connect(configWatcher, &KDirWatch::deleted, rulesConfigChange); auto windowSystem = new XWindowSystemEventBatcher(q); QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowAdded, q, [this](WId window) { addWindow(window); } ); QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowRemoved, q, [this](WId window) { removeWindow(window); } ); QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowChanged, q, [this](WId window, NET::Properties properties, NET::Properties2 properties2) { windowChanged(window, properties, properties2); } ); // Update IsActive for previously- and newly-active windows. QObject::connect(KWindowSystem::self(), &KWindowSystem::activeWindowChanged, q, [this](WId window) { const WId oldActiveWindow = activeWindow; activeWindow = window; int row = windows.indexOf(oldActiveWindow); if (row != -1) { dataChanged(oldActiveWindow, QVector{IsActive}); } row = windows.indexOf(window); if (row != -1) { dataChanged(window, QVector{IsActive}); } } ); activeWindow = KWindowSystem::activeWindow(); // Add existing windows. foreach(const WId window, KWindowSystem::windows()) { addWindow(window); } } void XWindowTasksModel::Private::addWindow(WId window) { // Don't add window twice. if (windows.contains(window)) { return; } KWindowInfo info(window, NET::WMWindowType | NET::WMState | NET::WMName | NET::WMVisibleName, NET::WM2TransientFor); NET::WindowType wType = info.windowType(NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask); const WId leader = info.transientFor(); // Handle transient. if (leader > 0 && leader != window && leader != QX11Info::appRootWindow() && !transients.contains(window) && windows.contains(leader)) { transients.insert(window); // Update demands attention state for leader. if (info.hasState(NET::DemandsAttention) && windows.contains(leader)) { transientsDemandingAttention.insertMulti(leader, window); dataChanged(leader, QVector{IsDemandingAttention}); } return; } // Ignore NET::Tool and other special window types; they are not considered tasks. if (wType != NET::Normal && wType != NET::Override && wType != NET::Unknown && wType != NET::Dialog && wType != NET::Utility) { return; } const int count = windows.count(); q->beginInsertRows(QModelIndex(), count, count); windows.append(window); q->endInsertRows(); } void XWindowTasksModel::Private::removeWindow(WId window) { const int row = windows.indexOf(window); if (row != -1) { q->beginRemoveRows(QModelIndex(), row, row); windows.removeAt(row); transientsDemandingAttention.remove(window); delete windowInfoCache.take(window); appDataCache.remove(window); usingFallbackIcon.remove(window); delegateGeometries.remove(window); q->endRemoveRows(); } else { // Could be a transient. // Removing a transient might change the demands attention state of the leader. if (transients.remove(window)) { const WId leader = transientsDemandingAttention.key(window, XCB_WINDOW_NONE); if (leader != XCB_WINDOW_NONE) { transientsDemandingAttention.remove(leader, window); dataChanged(leader, QVector{IsDemandingAttention}); } } } if (activeWindow == window) { activeWindow = -1; } } void XWindowTasksModel::Private::transientChanged(WId window, NET::Properties properties, NET::Properties2 properties2) { // Changes to a transient's state might change demands attention state for leader. if (properties & (NET::WMState | NET::XAWMState)) { const KWindowInfo info(window, NET::WMState | NET::XAWMState, NET::WM2TransientFor); const WId leader = info.transientFor(); if (!windows.contains(leader)) { return; } if (info.hasState(NET::DemandsAttention)) { if (!transientsDemandingAttention.values(leader).contains(window)) { transientsDemandingAttention.insertMulti(leader, window); dataChanged(leader, QVector{IsDemandingAttention}); } } else if (transientsDemandingAttention.remove(window)) { dataChanged(leader, QVector{IsDemandingAttention}); } // Leader might have changed. } else if (properties2 & NET::WM2TransientFor) { const KWindowInfo info(window, NET::WMState | NET::XAWMState, NET::WM2TransientFor); if (info.hasState(NET::DemandsAttention)) { const WId oldLeader = transientsDemandingAttention.key(window, XCB_WINDOW_NONE); if (oldLeader != XCB_WINDOW_NONE) { const WId leader = info.transientFor(); if (leader != oldLeader) { transientsDemandingAttention.remove(oldLeader, window); transientsDemandingAttention.insertMulti(leader, window); dataChanged(oldLeader, QVector{IsDemandingAttention}); dataChanged(leader, QVector{IsDemandingAttention}); } } } } } void XWindowTasksModel::Private::windowChanged(WId window, NET::Properties properties, NET::Properties2 properties2) { if (transients.contains(window)) { transientChanged(window, properties, properties2); return; } bool wipeInfoCache = false; bool wipeAppDataCache = false; QVector changedRoles; if (properties & (NET::WMPid) || properties2 & (NET::WM2DesktopFileName | NET::WM2WindowClass)) { wipeInfoCache = true; wipeAppDataCache = true; changedRoles << Qt::DecorationRole << AppId << AppName << GenericName << LauncherUrl << AppPid << SkipTaskbar; } if (properties & (NET::WMName | NET::WMVisibleName)) { changedRoles << Qt::DisplayRole; wipeInfoCache = true; } if ((properties & NET::WMIcon) && usingFallbackIcon.contains(window)) { wipeAppDataCache = true; if (!changedRoles.contains(Qt::DecorationRole)) { changedRoles << Qt::DecorationRole; } } // FIXME TODO: It might be worth keeping track of which windows were demanding // attention (or not) to avoid emitting this role on every state change, as // TaskGroupingProxyModel needs to check for group-ability when a change to it // is announced and the queried state is false. if (properties & (NET::WMState | NET::XAWMState)) { wipeInfoCache = true; changedRoles << IsFullScreen << IsMaximized << IsMinimized << IsKeepAbove << IsKeepBelow; changedRoles << IsShaded << IsDemandingAttention << SkipTaskbar << SkipPager; } if (properties & NET::WMWindowType) { wipeInfoCache = true; changedRoles << SkipTaskbar; } if (properties2 & NET::WM2AllowedActions) { wipeInfoCache = true; changedRoles << IsClosable << IsMovable << IsResizable << IsMaximizable << IsMinimizable; - changedRoles << IsFullScreenable << IsShadeable << IsVirtualDesktopChangeable; + changedRoles << IsFullScreenable << IsShadeable << IsVirtualDesktopsChangeable; } if (properties & NET::WMDesktop) { wipeInfoCache = true; - changedRoles << VirtualDesktop << IsOnAllVirtualDesktops; + changedRoles << VirtualDesktops << IsOnAllVirtualDesktops; } if (properties & NET::WMGeometry) { wipeInfoCache = true; changedRoles << Geometry << ScreenGeometry; } if (properties2 & NET::WM2Activities) { changedRoles << Activities; } if (wipeInfoCache) { delete windowInfoCache.take(window); } if (wipeAppDataCache) { appDataCache.remove(window); usingFallbackIcon.remove(window); } if (!changedRoles.isEmpty()) { dataChanged(window, changedRoles); } } void XWindowTasksModel::Private::dataChanged(WId window, const QVector &roles) { const int i = windows.indexOf(window); if (i == -1) { return; } QModelIndex idx = q->index(i); emit q->dataChanged(idx, idx, roles); } KWindowInfo* XWindowTasksModel::Private::windowInfo(WId window) { const auto &it = windowInfoCache.constFind(window); if (it != windowInfoCache.constEnd()) { return *it; } KWindowInfo *info = new KWindowInfo(window, windowInfoFlags, windowInfoFlags2); windowInfoCache.insert(window, info); return info; } AppData XWindowTasksModel::Private::appData(WId window) { const auto &it = appDataCache.constFind(window); if (it != appDataCache.constEnd()) { return *it; } const AppData &data = appDataFromUrl(windowUrl(window)); // If we weren't able to derive a launcher URL from the window meta data, // fall back to WM_CLASS Class string as app id. This helps with apps we // can't map to an URL due to existing outside the regular system // environment, e.g. wine clients. if (data.id.isEmpty() && data.url.isEmpty()) { AppData dataCopy = data; dataCopy.id = windowInfo(window)->windowClassClass(); appDataCache.insert(window, dataCopy); return dataCopy; } appDataCache.insert(window, data); return data; } QIcon XWindowTasksModel::Private::icon(WId window) { const AppData &app = appData(window); if (!app.icon.isNull()) { return app.icon; } QIcon icon; icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeSmall, KIconLoader::SizeSmall, false)); icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeSmallMedium, KIconLoader::SizeSmallMedium, false)); icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeMedium, KIconLoader::SizeMedium, false)); icon.addPixmap(KWindowSystem::icon(window, KIconLoader::SizeLarge, KIconLoader::SizeLarge, false)); appDataCache[window].icon = icon; usingFallbackIcon.insert(window); return icon; } QString XWindowTasksModel::Private::mimeType() { return QStringLiteral("windowsystem/winid"); } QString XWindowTasksModel::Private::groupMimeType() { return QStringLiteral("windowsystem/multiple-winids"); } QUrl XWindowTasksModel::Private::windowUrl(WId window) { const KWindowInfo *info = windowInfo(window); QString desktopFile = QString::fromUtf8(info->desktopFileName()); if (!desktopFile.isEmpty()) { KService::Ptr service = KService::serviceByStorageId(desktopFile); if (service) { const QString &menuId = service->menuId(); // applications: URLs are used to refer to applications by their KService::menuId // (i.e. .desktop file name) rather than the absolute path to a .desktop file. if (!menuId.isEmpty()) { return QUrl(QStringLiteral("applications:") + menuId); } return QUrl::fromLocalFile(service->entryPath()); } if (!desktopFile.endsWith(QLatin1String(".desktop"))) { desktopFile.append(QLatin1String(".desktop")); } if (KDesktopFile::isDesktopFile(desktopFile) && QFile::exists(desktopFile)) { return QUrl::fromLocalFile(desktopFile); } } return windowUrlFromMetadata(info->windowClassClass(), NETWinInfo(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMPid, NET::Properties2()).pid(), rulesConfig, info->windowClassName()); } QUrl XWindowTasksModel::Private::launcherUrl(WId window, bool encodeFallbackIcon) { const AppData &data = appData(window); if (!encodeFallbackIcon || !data.icon.name().isEmpty()) { return data.url; } QUrl url = data.url; // Forego adding the window icon pixmap if the URL is otherwise empty. if (!url.isValid()) { return QUrl(); } const QPixmap pixmap = KWindowSystem::icon(window, KIconLoader::SizeLarge, KIconLoader::SizeLarge, false); if (pixmap.isNull()) { return data.url; } QUrlQuery uQuery(url); QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); pixmap.save(&buffer, "PNG"); uQuery.addQueryItem(QStringLiteral("iconData"), bytes.toBase64(QByteArray::Base64UrlEncoding)); url.setQuery(uQuery); return url; } bool XWindowTasksModel::Private::demandsAttention(WId window) { if (windows.contains(window)) { return ((windowInfo(window)->hasState(NET::DemandsAttention)) || transientsDemandingAttention.contains(window)); } return false; } XWindowTasksModel::XWindowTasksModel(QObject *parent) : AbstractWindowTasksModel(parent) , d(new Private(this)) { d->init(); } XWindowTasksModel::~XWindowTasksModel() { } QVariant XWindowTasksModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->windows.count()) { return QVariant(); } const WId window = d->windows.at(index.row()); if (role == Qt::DisplayRole) { return d->windowInfo(window)->visibleName(); } else if (role == Qt::DecorationRole) { return d->icon(window); } else if (role == AppId) { return d->appData(window).id; } else if (role == AppName) { return d->appData(window).name; } else if (role == GenericName) { return d->appData(window).genericName; } else if (role == LauncherUrl) { return d->launcherUrl(window); } else if (role == LauncherUrlWithoutIcon) { return d->launcherUrl(window, false /* encodeFallbackIcon */); - } else if (role == LegacyWinIdList) { + } else if (role == WinIdList) { 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) { + } else if (role == IsVirtualDesktopsChangeable) { return d->windowInfo(window)->actionSupported(NET::ActionChangeDesktop); - } else if (role == VirtualDesktop) { - return d->windowInfo(window)->desktop(); + } else if (role == VirtualDesktops) { + return QVariantList() << d->windowInfo(window)->desktop(); } else if (role == IsOnAllVirtualDesktops) { return d->windowInfo(window)->onAllDesktops(); } else if (role == Geometry) { return d->windowInfo(window)->frameGeometry(); } else if (role == ScreenGeometry) { return screenGeometry(d->windowInfo(window)->frameGeometry().center()); } else if (role == Activities) { return d->windowInfo(window)->activities(); } else if (role == IsDemandingAttention) { return d->demandsAttention(window); } else if (role == SkipTaskbar) { const KWindowInfo *info = d->windowInfo(window); // _NET_WM_WINDOW_TYPE_UTILITY type windows should not be on task bars, // but they should be shown on pagers. return (info->hasState(NET::SkipTaskbar) || info->windowType(NET::UtilityMask) == NET::Utility || d->appData(window).skipTaskbar); } else if (role == SkipPager) { return d->windowInfo(window)->hasState(NET::SkipPager); } else if (role == AppPid) { return d->windowInfo(window)->pid(); } return QVariant(); } int XWindowTasksModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->windows.count(); } void XWindowTasksModel::requestActivate(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } if (index.row() >= 0 && index.row() < d->windows.count()) { WId window = d->windows.at(index.row()); // Pull forward any transient demanding attention. if (d->transientsDemandingAttention.contains(window)) { window = d->transientsDemandingAttention.value(window); // Quote from legacy libtaskmanager: // "this is a work around for (at least?) kwin where a shaded transient will prevent the main // window from being brought forward unless the transient is actually pulled forward, most // easily reproduced by opening a modal file open/save dialog on an app then shading the file // dialog and trying to bring the window forward by clicking on it in a tasks widget // TODO: do we need to check all the transients for shaded?" } else if (!d->transients.isEmpty()) { foreach (const WId transient, d->transients) { KWindowInfo info(transient, NET::WMState, NET::WM2TransientFor); if (info.valid(true) && info.hasState(NET::Shaded) && info.transientFor() == window) { window = transient; break; } } } KWindowSystem::forceActiveWindow(window); } } void XWindowTasksModel::requestNewInstance(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } runApp(d->appData(d->windows.at(index.row()))); } void XWindowTasksModel::requestOpenUrls(const QModelIndex &index, const QList &urls) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count() || urls.isEmpty()) { return; } runApp(d->appData(d->windows.at(index.row())), urls); } void XWindowTasksModel::requestClose(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } NETRootInfo ri(QX11Info::connection(), NET::CloseWindow); ri.closeWindowRequest(d->windows.at(index.row())); } void XWindowTasksModel::requestMove(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); bool onCurrent = info->isOnCurrentDesktop(); if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); KWindowSystem::forceActiveWindow(window); } if (info->isMinimized()) { KWindowSystem::unminimizeWindow(window); } const QRect &geom = info->geometry(); NETRootInfo ri(QX11Info::connection(), NET::WMMoveResize); ri.moveResizeRequest(window, geom.center().x(), geom.center().y(), NET::Move); } void XWindowTasksModel::requestResize(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); bool onCurrent = info->isOnCurrentDesktop(); if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); KWindowSystem::forceActiveWindow(window); } if (info->isMinimized()) { KWindowSystem::unminimizeWindow(window); } const QRect &geom = info->geometry(); NETRootInfo ri(QX11Info::connection(), NET::WMMoveResize); ri.moveResizeRequest(window, geom.bottomRight().x(), geom.bottomRight().y(), NET::BottomRight); } void XWindowTasksModel::requestToggleMinimized(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); if (info->isMinimized()) { bool onCurrent = info->isOnCurrentDesktop(); // FIXME: Move logic up into proxy? (See also others.) if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); } KWindowSystem::unminimizeWindow(window); if (onCurrent) { KWindowSystem::forceActiveWindow(window); } } else { KWindowSystem::minimizeWindow(window); } } void XWindowTasksModel::requestToggleMaximized(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); bool onCurrent = info->isOnCurrentDesktop(); bool restore = (info->hasState(NET::MaxHoriz) && info->hasState(NET::MaxVert)); // FIXME: Move logic up into proxy? (See also others.) if (!onCurrent) { KWindowSystem::setCurrentDesktop(info->desktop()); } if (info->isMinimized()) { KWindowSystem::unminimizeWindow(window); } NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (restore) { ni.setState(NET::States(), NET::Max); } else { ni.setState(NET::Max, NET::Max); } if (!onCurrent) { KWindowSystem::forceActiveWindow(window); } } void XWindowTasksModel::requestToggleKeepAbove(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::StaysOnTop)) { ni.setState(NET::States(), NET::StaysOnTop); } else { ni.setState(NET::StaysOnTop, NET::StaysOnTop); } } void XWindowTasksModel::requestToggleKeepBelow(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::KeepBelow)) { ni.setState(NET::States(), NET::KeepBelow); } else { ni.setState(NET::KeepBelow, NET::KeepBelow); } } void XWindowTasksModel::requestToggleFullScreen(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::FullScreen)) { ni.setState(NET::States(), NET::FullScreen); } else { ni.setState(NET::FullScreen, NET::FullScreen); } } void XWindowTasksModel::requestToggleShaded(const QModelIndex &index) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); const KWindowInfo *info = d->windowInfo(window); NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2()); if (info->hasState(NET::Shaded)) { ni.setState(NET::States(), NET::Shaded); } else { ni.setState(NET::Shaded, NET::Shaded); } } -void XWindowTasksModel::requestVirtualDesktop(const QModelIndex &index, qint32 desktop) +void XWindowTasksModel::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } + int desktop = 0; + + if (!desktops.isEmpty()) { + bool ok = false; + + desktop = desktops.first().toUInt(&ok); + + if (!ok) { + return; + } + } + + if (desktop > KWindowSystem::numberOfDesktops()) { + 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::requestNewVirtualDesktop(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 int 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); +} + void XWindowTasksModel::requestActivities(const QModelIndex &index, const QStringList &activities) { if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); KWindowSystem::setOnActivities(window, activities); } void XWindowTasksModel::requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate) { Q_UNUSED(delegate) if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) { return; } const WId window = d->windows.at(index.row()); if (d->delegateGeometries.contains(window) && d->delegateGeometries.value(window) == geometry) { return; } NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::Properties(), NET::Properties2()); NETRect rect; if (geometry.isValid()) { rect.pos.x = geometry.x(); rect.pos.y = geometry.y(); rect.size.width = geometry.width(); rect.size.height = geometry.height(); d->delegateGeometries.insert(window, geometry); } else { d->delegateGeometries.remove(window); } ni.setIconGeometry(rect); } WId XWindowTasksModel::winIdFromMimeData(const QMimeData *mimeData, bool *ok) { Q_ASSERT(mimeData); if (ok) { *ok = false; } if (!mimeData->hasFormat(Private::mimeType())) { return 0; } QByteArray data(mimeData->data(Private::mimeType())); if (data.size() != sizeof(WId)) { return 0; } WId id; memcpy(&id, data.data(), sizeof(WId)); if (ok) { *ok = true; } return id; } QList XWindowTasksModel::winIdsFromMimeData(const QMimeData *mimeData, bool *ok) { Q_ASSERT(mimeData); QList ids; if (ok) { *ok = false; } if (!mimeData->hasFormat(Private::groupMimeType())) { // Try to extract single window id. bool singularOk; WId id = winIdFromMimeData(mimeData, &singularOk); if (ok) { *ok = singularOk; } if (singularOk) { ids << id; } return ids; } QByteArray data(mimeData->data(Private::groupMimeType())); if ((unsigned int)data.size() < sizeof(int) + sizeof(WId)) { return ids; } int count = 0; memcpy(&count, data.data(), sizeof(int)); if (count < 1 || (unsigned int)data.size() < sizeof(int) + sizeof(WId) * count) { return ids; } WId id; for (int i = 0; i < count; ++i) { memcpy(&id, data.data() + sizeof(int) + sizeof(WId) * i, sizeof(WId)); ids << id; } if (ok) { *ok = true; } return ids; } } diff --git a/libtaskmanager/xwindowtasksmodel.h b/libtaskmanager/xwindowtasksmodel.h index ef46fd34e..37df37989 100644 --- a/libtaskmanager/xwindowtasksmodel.h +++ b/libtaskmanager/xwindowtasksmodel.h @@ -1,239 +1,248 @@ /******************************************************************** 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 XWINDOWTASKSMODEL_H #define XWINDOWTASKSMODEL_H #include "abstractwindowtasksmodel.h" #include "taskmanager_export.h" #include #include #include namespace TaskManager { /** - * @short A tasks model for X Windows windows. + * @short A tasks model for X Window System windows. * * This model presents tasks sourced from window data on the X Windows * server the host process is connected to. * * For the purposes of presentation in a user interface and efficiency, * certain types of windows (e.g. utility windows, or windows that are * transients for an otherwise-included window) are omitted from the * model. * + * @see WindowTasksModel + * * @author Eike Hein */ class TASKMANAGER_EXPORT XWindowTasksModel : public AbstractWindowTasksModel { Q_OBJECT public: explicit XWindowTasksModel(QObject *parent = nullptr); ~XWindowTasksModel() override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; /** * Request activation of the window at the given index. * * If the window has a transient demanding attention, it will be * activated instead. * * If the window has a transient in shaded state, it will be * activated instead. * * @param index An index in this window tasks model. **/ void requestActivate(const QModelIndex &index) override; /** * Request an additional instance of the application owning the window * at the given index. Success depends on whether a * AbstractTasksModel::LauncherUrl could be derived from window metadata. * * @param index An index in this window tasks model. **/ void requestNewInstance(const QModelIndex &index) override; /** * Runs the application backing the launcher at the given index with the given URLs. * Success depends on whether a AbstractTasksModel::LauncherUrl could be * derived from window metadata and a KService could be found from that. * * @param index An index in this launcher tasks model * @param urls The URLs to be passed to the application */ void requestOpenUrls(const QModelIndex &index, const QList &urls) override; /** * Request the window at the given index be closed. * * @param index An index in this window tasks model. **/ void requestClose(const QModelIndex &index) override; /** * Request starting an interactive move for the window at the given index. * * If the window is not currently the active window, it will be activated. * * If the window is not on the current desktop, the current desktop will * be set to the window's desktop. * FIXME: Desktop logic should maybe move into proxy. * * @param index An index in this window tasks model. **/ void requestMove(const QModelIndex &index) override; /** * Request starting an interactive resize for the window at the given index. * * If the window is not currently the active window, it will be activated. * * If the window is not on the current desktop, the current desktop will * be set to the window's desktop. * FIXME: Desktop logic should maybe move into proxy. * * @param index An index in this window tasks model. **/ void requestResize(const QModelIndex &index) override; /** * Request toggling the minimized state of the window at the given index. * * If the window is not on the current desktop, the current desktop will * be set to the window's desktop. * FIXME: Desktop logic should maybe move into proxy. * * @param index An index in this window tasks model. **/ void requestToggleMinimized(const QModelIndex &index) override; /** * Request toggling the maximized state of the task at the given index. * * If the window is not on the current desktop, the current desktop will * be set to the window's desktop. * FIXME: Desktop logic should maybe move into proxy. * * @param index An index in this window tasks model. **/ void requestToggleMaximized(const QModelIndex &index) override; /** * Request toggling the keep-above state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleKeepAbove(const QModelIndex &index) override; /** * Request toggling the keep-below state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleKeepBelow(const QModelIndex &index) override; /** * Request toggling the fullscreen state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleFullScreen(const QModelIndex &index) override; /** * Request toggling the shaded state of the task at the given index. * * @param index An index in this window tasks model. **/ void requestToggleShaded(const QModelIndex &index) override; /** - * Request moving the window at the given index to the specified virtual - * desktop. + * Request entering the window at the given index on the specified virtual desktop. + * For compatibility across windowing systems the library supports, the desktops + * parameter is a list; however, on X11 a window can only be on one or all virtual + * desktops. Therefore, only the first list entry is actually used. * - * If the specified virtual desktop is 0, IsOnAllVirtualDesktops is - * toggled instead. + * An empty list has a special meaning: The window is entered on all virtual desktops + * in the session. * - * If the specified desktop number exceeds the number of virtual - * desktops in the session, a new desktop is created before moving - * the window. + * The id 0 has a special meaning: The window is entered on all virtual desktops in + * the session. * - * FIXME: Desktop logic should maybe move into proxy. + * @param index An index in this window tasks model. + * @param desktops A list of virtual desktop ids (uint). + **/ + void requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops) override; + + /** + * Request entering the window at the given index on a new virtual desktop, + * which is created in response to this request. * * @param index An index in this window tasks model. - * @param desktop A virtual desktop number. **/ - void requestVirtualDesktop(const QModelIndex &index, qint32 desktop) override; + void requestNewVirtualDesktop(const QModelIndex &index) 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. * * * @param index An index in this tasks model. * @param activities The new list of activities. **/ void requestActivities(const QModelIndex &index, const QStringList &activities) override; /** * Request informing the window manager of new geometry for a visual * delegate for the window at the given index. * * @param index An index in this window tasks model. * @param geometry Visual delegate geometry in screen coordinates. * @param delegate The delegate. Unused in this implementation. **/ void requestPublishDelegateGeometry(const QModelIndex &index, const QRect &geometry, QObject *delegate = nullptr) override; /** * Tries to extract a X11 window id from supplied mime data. * * @param mimeData Some mime data. * @param @ok Set to true or false on success or failure. */ static WId winIdFromMimeData(const QMimeData *mimeData, bool *ok = nullptr); /** * Tries to extract X11 window ids from supplied mime data. * * @param mimeData Some mime data. * @param @ok Set to true or false on success or failure. */ static QList winIdsFromMimeData(const QMimeData *mimeData, bool *ok = nullptr); private: class Private; QScopedPointer d; }; } #endif