xwindowtasksmodel.cpp 34.3 KB
Newer Older
Eike Hein's avatar
Eike Hein committed
1
2
/********************************************************************
Copyright 2016  Eike Hein <hein@kde.org>
3
Copyright 2008  Aaron J. Seigo <aseigo@kde.org>
Eike Hein's avatar
Eike Hein committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

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 <http://www.gnu.org/licenses/>.
*********************************************************************/

#include "xwindowtasksmodel.h"
#include "tasktools.h"
24
#include "xwindowsystemeventbatcher.h"
Eike Hein's avatar
Eike Hein committed
25

26
#include <KActivities/ResourceInstance>
27
#include <KDesktopFile>
Eike Hein's avatar
Eike Hein committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <KDirWatch>
#include <KIconLoader>
#include <KRun>
#include <KService>
#include <KSharedConfig>
#include <KStartupInfo>
#include <KSycoca>
#include <KWindowInfo>
#include <KWindowSystem>

#include <QBuffer>
#include <QDir>
#include <QIcon>
#include <QFile>
#include <QSet>
#include <QTimer>
44
#include <QUrlQuery>
Eike Hein's avatar
Eike Hein committed
45
46
47
48
49
50
#include <QX11Info>

namespace TaskManager
{

static const NET::Properties windowInfoFlags = NET::WMState | NET::XAWMState | NET::WMDesktop |
51
    NET::WMVisibleName | NET::WMGeometry | NET::WMFrameExtents | NET::WMWindowType | NET::WMPid;
52
53
static const NET::Properties2 windowInfoFlags2 = NET::WM2DesktopFileName | NET::WM2Activities |
    NET::WM2WindowClass | NET::WM2AllowedActions;
Eike Hein's avatar
Eike Hein committed
54

55
class Q_DECL_HIDDEN XWindowTasksModel::Private
Eike Hein's avatar
Eike Hein committed
56
57
58
59
60
61
62
{
public:
    Private(XWindowTasksModel *q);
    ~Private();

    QVector<WId> windows;
    QSet<WId> transients;
Eike Hein's avatar
Eike Hein committed
63
    QMultiHash<WId, WId> transientsDemandingAttention;
Eike Hein's avatar
Eike Hein committed
64
65
66
    QHash<WId, KWindowInfo*> windowInfoCache;
    QHash<WId, AppData> appDataCache;
    QHash<WId, QRect> delegateGeometries;
Eike Hein's avatar
Eike Hein committed
67
    QSet<WId> usingFallbackIcon;
Eike Hein's avatar
Eike Hein committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    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<int> &roles);

    KWindowInfo* windowInfo(WId window);
    AppData appData(WId window);

    QIcon icon(WId window);
84
85
    static QString mimeType();
    static QString groupMimeType();
Eike Hein's avatar
Eike Hein committed
86
    QUrl windowUrl(WId window);
87
    QUrl launcherUrl(WId window, bool encodeFallbackIcon = true);
Eike Hein's avatar
Eike Hein committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    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()
{
107
108
109
110
    auto clearCacheAndRefresh = [this] {
        if (!windows.count()) {
            return;
        }
Eike Hein's avatar
Eike Hein committed
111

112
        appDataCache.clear();
Eike Hein's avatar
Eike Hein committed
113

114
115
116
117
118
        // Emit changes of all roles satisfied from app data cache.
        q->dataChanged(q->index(0, 0),  q->index(windows.count() - 1, 0),
            QVector<int>{Qt::DecorationRole, AbstractTasksModel::AppId,
            AbstractTasksModel::AppName, AbstractTasksModel::GenericName,
            AbstractTasksModel::LauncherUrl,
119
120
            AbstractTasksModel::LauncherUrlWithoutIcon,
            AbstractTasksModel::SkipTaskbar});
121
    };
Eike Hein's avatar
Eike Hein committed
122
123
124
125

    sycocaChangeTimer.setSingleShot(true);
    sycocaChangeTimer.setInterval(100);

126
    QObject::connect(&sycocaChangeTimer, &QTimer::timeout, q, clearCacheAndRefresh);
Eike Hein's avatar
Eike Hein committed
127
128
129
130
131
132
133
134
135
136
137
138

    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();
            }
        }
    );

139
140
141
142
143
144
145
    rulesConfig = KSharedConfig::openConfig(QStringLiteral("taskmanagerrulesrc"));
    configWatcher = new KDirWatch(q);

    foreach (const QString &location, QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)) {
        configWatcher->addFile(location + QLatin1String("/taskmanagerrulesrc"));
    }

Eike Hein's avatar
Eike Hein committed
146
    auto rulesConfigChange = [this, clearCacheAndRefresh] {
147
148
149
150
151
152
153
154
        rulesConfig->reparseConfiguration();
        clearCacheAndRefresh();
    };

    QObject::connect(configWatcher, &KDirWatch::dirty, rulesConfigChange);
    QObject::connect(configWatcher, &KDirWatch::created, rulesConfigChange);
    QObject::connect(configWatcher, &KDirWatch::deleted, rulesConfigChange);

155
156
157
    auto windowSystem = new XWindowSystemEventBatcher(q);

    QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowAdded, q,
Eike Hein's avatar
Eike Hein committed
158
159
160
161
162
        [this](WId window) {
            addWindow(window);
        }
    );

163
    QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowRemoved, q,
Eike Hein's avatar
Eike Hein committed
164
165
166
167
168
        [this](WId window) {
            removeWindow(window);
        }
    );

169
    QObject::connect(windowSystem, &XWindowSystemEventBatcher::windowChanged, q,
Eike Hein's avatar
Eike Hein committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
        [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<int>{IsActive});
            }

            row = windows.indexOf(window);

            if (row != -1) {
                dataChanged(window, QVector<int>{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.
222
    if (leader > 0 && leader != window && leader != QX11Info::appRootWindow()
Eike Hein's avatar
Eike Hein committed
223
224
225
226
        && !transients.contains(window) && windows.contains(leader)) {
        transients.insert(window);

        // Update demands attention state for leader.
227
        if (info.hasState(NET::DemandsAttention) && windows.contains(leader)) {
Eike Hein's avatar
Eike Hein committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
            transientsDemandingAttention.insertMulti(leader, window);
            dataChanged(leader, QVector<int>{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);
256
        delete windowInfoCache.take(window);
Eike Hein's avatar
Eike Hein committed
257
        appDataCache.remove(window);
Eike Hein's avatar
Eike Hein committed
258
        usingFallbackIcon.remove(window);
Eike Hein's avatar
Eike Hein committed
259
260
261
262
263
        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)) {
Eike Hein's avatar
Eike Hein committed
264
            const WId leader = transientsDemandingAttention.key(window, XCB_WINDOW_NONE);
Eike Hein's avatar
Eike Hein committed
265

Eike Hein's avatar
Eike Hein committed
266
267
            if (leader != XCB_WINDOW_NONE) {
                transientsDemandingAttention.remove(leader, window);
Eike Hein's avatar
Eike Hein committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
                dataChanged(leader, QVector<int>{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;
        }

289
        if (info.hasState(NET::DemandsAttention)) {
Eike Hein's avatar
Eike Hein committed
290
291
292
293
294
295
296
297
298
299
300
            if (!transientsDemandingAttention.values(leader).contains(window)) {
                transientsDemandingAttention.insertMulti(leader, window);
                dataChanged(leader, QVector<int>{IsDemandingAttention});
            }
        } else if (transientsDemandingAttention.remove(window)) {
            dataChanged(leader, QVector<int>{IsDemandingAttention});
        }
    // Leader might have changed.
    } else if (properties2 & NET::WM2TransientFor) {
        const KWindowInfo info(window, NET::WMState | NET::XAWMState, NET::WM2TransientFor);

301
        if (info.hasState(NET::DemandsAttention)) {
Eike Hein's avatar
Eike Hein committed
302
            const WId oldLeader = transientsDemandingAttention.key(window, XCB_WINDOW_NONE);
Eike Hein's avatar
Eike Hein committed
303

Eike Hein's avatar
Eike Hein committed
304
            if (oldLeader != XCB_WINDOW_NONE) {
305
                const WId leader = info.transientFor();
Eike Hein's avatar
Eike Hein committed
306

307
                if (leader != oldLeader) {
Eike Hein's avatar
Eike Hein committed
308
                    transientsDemandingAttention.remove(oldLeader, window);
309
310
311
                    transientsDemandingAttention.insertMulti(leader, window);
                    dataChanged(oldLeader, QVector<int>{IsDemandingAttention});
                    dataChanged(leader, QVector<int>{IsDemandingAttention});
Eike Hein's avatar
Eike Hein committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
                }
            }
        }
    }
}

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<int> changedRoles;

330
    if (properties & (NET::WMPid)
331
        || properties2 & (NET::WM2DesktopFileName | NET::WM2WindowClass)) {
Eike Hein's avatar
Eike Hein committed
332
333
        wipeInfoCache = true;
        wipeAppDataCache = true;
334
        changedRoles << Qt::DecorationRole << AppId << AppName << GenericName << LauncherUrl << AppPid << SkipTaskbar;
335
336
337
338
339
    }

    if (properties & (NET::WMName | NET::WMVisibleName)) {
        changedRoles << Qt::DisplayRole;
        wipeInfoCache = true;
Eike Hein's avatar
Eike Hein committed
340
341
    }

Eike Hein's avatar
Eike Hein committed
342
343
344
345
346
347
    if ((properties & NET::WMIcon) && usingFallbackIcon.contains(window)) {
        wipeAppDataCache = true;

        if (!changedRoles.contains(Qt::DecorationRole)) {
            changedRoles << Qt::DecorationRole;
        }
Eike Hein's avatar
Eike Hein committed
348
349
350
351
352
353
354
355
356
    }

    // 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;
357
        changedRoles << IsShaded << IsDemandingAttention << SkipTaskbar << SkipPager;
Eike Hein's avatar
Eike Hein committed
358
359
    }

360
361
362
363
364
    if (properties & NET::WMWindowType) {
        wipeInfoCache = true;
        changedRoles << SkipTaskbar;
    }

Eike Hein's avatar
Eike Hein committed
365
366
367
    if (properties2 & NET::WM2AllowedActions) {
        wipeInfoCache = true;
        changedRoles << IsClosable << IsMovable << IsResizable << IsMaximizable << IsMinimizable;
368
        changedRoles << IsFullScreenable << IsShadeable << IsVirtualDesktopsChangeable;
Eike Hein's avatar
Eike Hein committed
369
370
371
372
    }

    if (properties & NET::WMDesktop) {
        wipeInfoCache = true;
373
        changedRoles << VirtualDesktops << IsOnAllVirtualDesktops;
Eike Hein's avatar
Eike Hein committed
374
375
376
377
    }

    if (properties & NET::WMGeometry) {
        wipeInfoCache = true;
378
        changedRoles << Geometry << ScreenGeometry;
Eike Hein's avatar
Eike Hein committed
379
380
381
382
383
384
385
386
387
388
389
390
    }

    if (properties2 & NET::WM2Activities) {
        changedRoles << Activities;
    }

    if (wipeInfoCache) {
        delete windowInfoCache.take(window);
    }

    if (wipeAppDataCache) {
        appDataCache.remove(window);
Eike Hein's avatar
Eike Hein committed
391
        usingFallbackIcon.remove(window);
Eike Hein's avatar
Eike Hein committed
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    }

    if (!changedRoles.isEmpty()) {
        dataChanged(window, changedRoles);
    }
}

void XWindowTasksModel::Private::dataChanged(WId window, const QVector<int> &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)
{
413
    const auto &it = windowInfoCache.constFind(window);
Eike Hein's avatar
Eike Hein committed
414

415
416
    if (it != windowInfoCache.constEnd()) {
        return *it;
Eike Hein's avatar
Eike Hein committed
417
418
    }

419
420
421
422
    KWindowInfo *info = new KWindowInfo(window, windowInfoFlags, windowInfoFlags2);
    windowInfoCache.insert(window, info);

    return info;
Eike Hein's avatar
Eike Hein committed
423
424
425
426
}

AppData XWindowTasksModel::Private::appData(WId window)
{
427
    const auto &it = appDataCache.constFind(window);
428

429
430
431
    if (it != appDataCache.constEnd()) {
        return *it;
    }
432

433
    const AppData &data = appDataFromUrl(windowUrl(window));
434

435
436
437
438
439
440
    // 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;
441

442
        dataCopy.id = windowInfo(window)->windowClassClass();
443

444
        appDataCache.insert(window, dataCopy);
Eike Hein's avatar
Eike Hein committed
445

446
        return dataCopy;
Eike Hein's avatar
Eike Hein committed
447
448
    }

449
450
451
    appDataCache.insert(window, data);

    return data;
Eike Hein's avatar
Eike Hein committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
}

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));

469
    appDataCache[window].icon = icon;
Eike Hein's avatar
Eike Hein committed
470
    usingFallbackIcon.insert(window);
471

Eike Hein's avatar
Eike Hein committed
472
473
474
    return icon;
}

475
QString XWindowTasksModel::Private::mimeType()
Eike Hein's avatar
Eike Hein committed
476
477
478
479
{
    return QStringLiteral("windowsystem/winid");
}

480
481
482
483
484
QString XWindowTasksModel::Private::groupMimeType()
{
    return QStringLiteral("windowsystem/multiple-winids");
}

Eike Hein's avatar
Eike Hein committed
485
486
487
QUrl XWindowTasksModel::Private::windowUrl(WId window)
{
    const KWindowInfo *info = windowInfo(window);
488

489
    QString desktopFile = QString::fromUtf8(info->desktopFileName());
490
491
492
493
494

    if (!desktopFile.isEmpty()) {
        KService::Ptr service = KService::serviceByStorageId(desktopFile);

        if (service) {
495
496
497
498
499
500
501
502
            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);
            }

503
504
505
            return QUrl::fromLocalFile(service->entryPath());
        }

506
507
508
509
        if (!desktopFile.endsWith(QLatin1String(".desktop"))) {
            desktopFile.append(QLatin1String(".desktop"));
        }

510
511
512
513
514
        if (KDesktopFile::isDesktopFile(desktopFile) && QFile::exists(desktopFile)) {
            return QUrl::fromLocalFile(desktopFile);
        }
    }

515
    return windowUrlFromMetadata(info->windowClassClass(),
516
        info->pid(),
517
        rulesConfig, info->windowClassName());
Eike Hein's avatar
Eike Hein committed
518
519
}

520
QUrl XWindowTasksModel::Private::launcherUrl(WId window, bool encodeFallbackIcon)
Eike Hein's avatar
Eike Hein committed
521
522
523
{
    const AppData &data = appData(window);

524
    if (!encodeFallbackIcon || !data.icon.name().isEmpty()) {
Eike Hein's avatar
Eike Hein committed
525
526
527
        return data.url;
    }

528
529
    QUrl url = data.url;

530
531
532
533
    // Forego adding the window icon pixmap if the URL is otherwise empty.
    if (!url.isValid()) {
        return QUrl();
    }
Eike Hein's avatar
Eike Hein committed
534

535
536
    const QPixmap pixmap = KWindowSystem::icon(window, KIconLoader::SizeLarge, KIconLoader::SizeLarge, false);
    if (pixmap.isNull()) {
Eike Hein's avatar
Eike Hein committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
        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)) {
554
        return ((windowInfo(window)->hasState(NET::DemandsAttention))
Eike Hein's avatar
Eike Hein committed
555
556
557
558
559
560
561
        || transientsDemandingAttention.contains(window));
    }

    return false;
}

XWindowTasksModel::XWindowTasksModel(QObject *parent)
562
    : AbstractWindowTasksModel(parent)
Eike Hein's avatar
Eike Hein committed
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
    , 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);
592
593
    } else if (role == LauncherUrlWithoutIcon) {
        return d->launcherUrl(window, false /* encodeFallbackIcon */);
594
    } else if (role == WinIdList) {
Eike Hein's avatar
Eike Hein committed
595
596
597
598
        return QVariantList() << window;
    } else if (role == MimeType) {
        return d->mimeType();
    } else if (role == MimeData) {
Laurent Montel's avatar
Laurent Montel committed
599
        return QByteArray((char*)&window, sizeof(window));
Eike Hein's avatar
Eike Hein committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
    } 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);
614
        return info->hasState(NET::MaxHoriz) && info->hasState(NET::MaxVert);
Eike Hein's avatar
Eike Hein committed
615
616
617
618
619
    } else if (role == IsMinimizable) {
        return d->windowInfo(window)->actionSupported(NET::ActionMinimize);
    } else if (role == IsMinimized) {
        return d->windowInfo(window)->isMinimized();
    } else if (role == IsKeepAbove) {
Laurent Montel's avatar
Laurent Montel committed
620
        return d->windowInfo(window)->hasState(NET::KeepAbove);
Eike Hein's avatar
Eike Hein committed
621
    } else if (role == IsKeepBelow) {
622
        return d->windowInfo(window)->hasState(NET::KeepBelow);
Eike Hein's avatar
Eike Hein committed
623
624
625
    } else if (role == IsFullScreenable) {
        return d->windowInfo(window)->actionSupported(NET::ActionFullScreen);
    } else if (role == IsFullScreen) {
626
        return d->windowInfo(window)->hasState(NET::FullScreen);
Eike Hein's avatar
Eike Hein committed
627
628
629
    } else if (role == IsShadeable) {
        return d->windowInfo(window)->actionSupported(NET::ActionShade);
    } else if (role == IsShaded) {
630
        return d->windowInfo(window)->hasState(NET::Shaded);
631
    } else if (role == IsVirtualDesktopsChangeable) {
Eike Hein's avatar
Eike Hein committed
632
        return d->windowInfo(window)->actionSupported(NET::ActionChangeDesktop);
633
634
    } else if (role == VirtualDesktops) {
        return QVariantList() << d->windowInfo(window)->desktop();
Eike Hein's avatar
Eike Hein committed
635
636
    } else if (role == IsOnAllVirtualDesktops) {
        return d->windowInfo(window)->onAllDesktops();
637
638
639
640
    } else if (role == Geometry) {
        return d->windowInfo(window)->frameGeometry();
    } else if (role == ScreenGeometry) {
        return screenGeometry(d->windowInfo(window)->frameGeometry().center());
Eike Hein's avatar
Eike Hein committed
641
    } else if (role == Activities) {
642
        return d->windowInfo(window)->activities();
Eike Hein's avatar
Eike Hein committed
643
644
645
    } else if (role == IsDemandingAttention) {
        return d->demandsAttention(window);
    } else if (role == SkipTaskbar) {
646
647
648
        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.
649
650
651
        return (info->hasState(NET::SkipTaskbar)
            || info->windowType(NET::UtilityMask) == NET::Utility
            || d->appData(window).skipTaskbar);
652
653
    } else if (role == SkipPager) {
        return d->windowInfo(window)->hasState(NET::SkipPager);
654
655
    } else if (role == AppPid) {
        return d->windowInfo(window)->pid();
Eike Hein's avatar
Eike Hein committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    }

    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);

688
                if (info.valid(true) && info.hasState(NET::Shaded) && info.transientFor() == window) {
Eike Hein's avatar
Eike Hein committed
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
                    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;
    }

705
    runApp(d->appData(d->windows.at(index.row())));
Eike Hein's avatar
Eike Hein committed
706
707
}

708
709
710
711
712
713
714
715
void XWindowTasksModel::requestOpenUrls(const QModelIndex &index, const QList<QUrl> &urls)
{
    if (!index.isValid() || index.model() != this || index.row() < 0
        || index.row() >= d->windows.count()
        || urls.isEmpty()) {
        return;
    }

716
    runApp(d->appData(d->windows.at(index.row())), urls);
717
718
}

Eike Hein's avatar
Eike Hein committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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();
817
    bool restore = (info->hasState(NET::MaxHoriz) && info->hasState(NET::MaxVert));
Eike Hein's avatar
Eike Hein committed
818
819
820
821
822
823
824
825
826
827

    // FIXME: Move logic up into proxy? (See also others.)
    if (!onCurrent) {
        KWindowSystem::setCurrentDesktop(info->desktop());
    }

    if (info->isMinimized()) {
        KWindowSystem::unminimizeWindow(window);
    }

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
828
    NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2());
Eike Hein's avatar
Eike Hein committed
829
830

    if (restore) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
831
        ni.setState(NET::States(), NET::Max);
Eike Hein's avatar
Eike Hein committed
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
    } 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);

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
850
    NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2());
Eike Hein's avatar
Eike Hein committed
851

Laurent Montel's avatar
Laurent Montel committed
852
853
    if (info->hasState(NET::KeepAbove)) {
        ni.setState(NET::States(), NET::KeepAbove);
Eike Hein's avatar
Eike Hein committed
854
    } else {
Laurent Montel's avatar
Laurent Montel committed
855
        ni.setState(NET::KeepAbove, NET::KeepAbove);
Eike Hein's avatar
Eike Hein committed
856
857
858
859
860
861
862
863
864
865
866
867
    }
}

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);

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
868
    NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2());
Eike Hein's avatar
Eike Hein committed
869

870
    if (info->hasState(NET::KeepBelow)) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
871
        ni.setState(NET::States(), NET::KeepBelow);
Eike Hein's avatar
Eike Hein committed
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    } 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);

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
886
    NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2());
Eike Hein's avatar
Eike Hein committed
887

888
    if (info->hasState(NET::FullScreen)) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
889
        ni.setState(NET::States(), NET::FullScreen);
Eike Hein's avatar
Eike Hein committed
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    } 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);

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
904
    NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::WMState, NET::Properties2());
Eike Hein's avatar
Eike Hein committed
905

906
    if (info->hasState(NET::Shaded)) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
907
        ni.setState(NET::States(), NET::Shaded);
Eike Hein's avatar
Eike Hein committed
908
909
910
911
912
    } else {
        ni.setState(NET::Shaded, NET::Shaded);
    }
}

913
void XWindowTasksModel::requestVirtualDesktops(const QModelIndex &index, const QVariantList &desktops)
Eike Hein's avatar
Eike Hein committed
914
915
916
917
918
{
    if (!index.isValid() || index.model() != this || index.row() < 0 || index.row() >= d->windows.count()) {
        return;
    }

919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
    int desktop = 0;

    if (!desktops.isEmpty()) {
        bool ok = false;

        desktop = desktops.first().toUInt(&ok);

        if (!ok) {
            return;
        }
    }

    if (desktop > KWindowSystem::numberOfDesktops()) {
        return;
    }

Eike Hein's avatar
Eike Hein committed
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
    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;
    }

    KWindowSystem::setOnDesktop(window, desktop);

    if (desktop == KWindowSystem::currentDesktop()) {
        KWindowSystem::forceActiveWindow(window);
    }
}

956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
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);
}

976
977
978
979
980
981
982
983
984
985
986
987
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);
}


Eike Hein's avatar
Eike Hein committed
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
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;
    }

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
1003
    NETWinInfo ni(QX11Info::connection(), window, QX11Info::appRootWindow(), NET::Properties(), NET::Properties2());
Eike Hein's avatar
Eike Hein committed
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
    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);
}

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
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<WId> XWindowTasksModel::winIdsFromMimeData(const QMimeData *mimeData, bool *ok)
{
    Q_ASSERT(mimeData);
    QList<WId> 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;
}

Eike Hein's avatar
Eike Hein committed
1096
}