debug_console.cpp 58.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/********************************************************************
 KWin - the KDE window manager
 This file is part of the KDE project.

Copyright (C) 2016 Martin Gräßlin <mgraesslin@kde.org>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#include "debug_console.h"
21
#include "composite.h"
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
22
#include "x11client.h"
23
#include "input_event.h"
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
24
#include "internal_client.h"
25
#include "main.h"
26
#include "scene.h"
27
#include "xdgshellclient.h"
28
29
30
#include "unmanaged.h"
#include "wayland_server.h"
#include "workspace.h"
Hrvoje Senjan's avatar
Hrvoje Senjan committed
31
#include "keyboard_input.h"
32
33
#include "libinput/connection.h"
#include "libinput/device.h"
34
35
#include <kwinglplatform.h>
#include <kwinglutils.h>
36
37
38
39

#include "ui_debug_console.h"

// KWayland
40
41
42
#include <KWayland/Server/buffer_interface.h>
#include <KWayland/Server/clientconnection.h>
#include <KWayland/Server/subcompositor_interface.h>
43
44
45
46
47
#include <KWayland/Server/surface_interface.h>
// frameworks
#include <KLocalizedString>
#include <NETWM>
// Qt
48
#include <QMouseEvent>
49
50
51
#include <QMetaProperty>
#include <QMetaType>

52
53
54
55
56
// xkb
#include <xkbcommon/xkbcommon.h>

#include <functional>

57
58
59
namespace KWin
{

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

static QString tableHeaderRow(const QString &title)
{
    return QStringLiteral("<tr><th colspan=\"2\">%1</th></tr>").arg(title);
}

template<typename T>
static
QString tableRow(const QString &title, const T &argument)
{
    return QStringLiteral("<tr><td>%1</td><td>%2</td></tr>").arg(title).arg(argument);
}

static QString timestampRow(quint32 timestamp)
{
    return tableRow(i18n("Timestamp"), timestamp);
}

78
79
80
81
82
static QString timestampRowUsec(quint64 timestamp)
{
    return tableRow(i18n("Timestamp (µsec)"), timestamp);
}

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
static QString buttonToString(Qt::MouseButton button)
{
    switch (button) {
        case Qt::LeftButton:
            return i18nc("A mouse button", "Left");
        case Qt::RightButton:
            return i18nc("A mouse button", "Right");
        case Qt::MiddleButton:
            return i18nc("A mouse button", "Middle");
        case Qt::BackButton:
            return i18nc("A mouse button", "Back");
        case Qt::ForwardButton:
            return i18nc("A mouse button", "Forward");
        case Qt::TaskButton:
            return i18nc("A mouse button", "Task");
        case Qt::ExtraButton4:
            return i18nc("A mouse button", "Extra Button 4");
        case Qt::ExtraButton5:
            return i18nc("A mouse button", "Extra Button 5");
        case Qt::ExtraButton6:
            return i18nc("A mouse button", "Extra Button 6");
        case Qt::ExtraButton7:
            return i18nc("A mouse button", "Extra Button 7");
        case Qt::ExtraButton8:
            return i18nc("A mouse button", "Extra Button 8");
        case Qt::ExtraButton9:
            return i18nc("A mouse button", "Extra Button 9");
        case Qt::ExtraButton10:
            return i18nc("A mouse button", "Extra Button 10");
        case Qt::ExtraButton11:
            return i18nc("A mouse button", "Extra Button 11");
        case Qt::ExtraButton12:
            return i18nc("A mouse button", "Extra Button 12");
        case Qt::ExtraButton13:
            return i18nc("A mouse button", "Extra Button 13");
        case Qt::ExtraButton14:
            return i18nc("A mouse button", "Extra Button 14");
        case Qt::ExtraButton15:
            return i18nc("A mouse button", "Extra Button 15");
        case Qt::ExtraButton16:
            return i18nc("A mouse button", "Extra Button 16");
        case Qt::ExtraButton17:
            return i18nc("A mouse button", "Extra Button 17");
        case Qt::ExtraButton18:
            return i18nc("A mouse button", "Extra Button 18");
        case Qt::ExtraButton19:
            return i18nc("A mouse button", "Extra Button 19");
        case Qt::ExtraButton20:
            return i18nc("A mouse button", "Extra Button 20");
        case Qt::ExtraButton21:
            return i18nc("A mouse button", "Extra Button 21");
        case Qt::ExtraButton22:
            return i18nc("A mouse button", "Extra Button 22");
        case Qt::ExtraButton23:
            return i18nc("A mouse button", "Extra Button 23");
        case Qt::ExtraButton24:
            return i18nc("A mouse button", "Extra Button 24");
    default:
        return QString();
    }
}

145
146
147
148
149
150
151
152
static QString deviceRow(LibInput::Device *device)
{
    if (!device) {
        return tableRow(i18n("Input Device"), i18nc("The input device of the event is not known", "Unknown"));
    }
    return tableRow(i18n("Input Device"), QStringLiteral("%1 (%2)").arg(device->name()).arg(device->sysName()));
}

153
154
155
156
157
158
159
160
161
static QString buttonsToString(Qt::MouseButtons buttons)
{
    QString ret;
    for (uint i = 1; i < Qt::ExtraButton24; i = i << 1) {
        if (buttons & i) {
            ret.append(buttonToString(Qt::MouseButton(uint(buttons) & i)));
            ret.append(QStringLiteral(" "));
        }
    };
162
    return ret.trimmed();
163
164
165
166
167
168
169
}

static const QString s_hr = QStringLiteral("<hr/>");
static const QString s_tableStart = QStringLiteral("<table>");
static const QString s_tableEnd = QStringLiteral("</table>");

DebugConsoleFilter::DebugConsoleFilter(QTextEdit *textEdit)
170
    : InputEventSpy()
171
172
173
174
175
176
    , m_textEdit(textEdit)
{
}

DebugConsoleFilter::~DebugConsoleFilter() = default;

177
void DebugConsoleFilter::pointerEvent(MouseEvent *event)
178
179
180
181
182
183
{
    QString text = s_hr;
    const QString timestamp = timestampRow(event->timestamp());

    text.append(s_tableStart);
    switch (event->type()) {
184
    case QEvent::MouseMove: {
185
        text.append(tableHeaderRow(i18nc("A mouse pointer motion event", "Pointer Motion")));
186
        text.append(deviceRow(event->device()));
187
        text.append(timestamp);
188
189
        if (event->timestampMicroseconds() != 0) {
            text.append(timestampRowUsec(event->timestampMicroseconds()));
190
        }
191
        if (event->delta() != QSizeF()) {
192
            text.append(tableRow(i18nc("The relative mouse movement", "Delta"),
193
                                 QStringLiteral("%1/%2").arg(event->delta().width()).arg(event->delta().height())));
194
        }
195
        if (event->deltaUnaccelerated() != QSizeF()) {
196
            text.append(tableRow(i18nc("The relative mouse movement", "Delta (not accelerated)"),
197
                                 QStringLiteral("%1/%2").arg(event->deltaUnaccelerated().width()).arg(event->deltaUnaccelerated().height())));
198
        }
199
200
        text.append(tableRow(i18nc("The global mouse pointer position", "Global Position"), QStringLiteral("%1/%2").arg(event->pos().x()).arg(event->pos().y())));
        break;
201
    }
202
203
    case QEvent::MouseButtonPress:
        text.append(tableHeaderRow(i18nc("A mouse pointer button press event", "Pointer Button Press")));
204
        text.append(deviceRow(event->device()));
205
206
        text.append(timestamp);
        text.append(tableRow(i18nc("A button in a mouse press/release event", "Button"), buttonToString(event->button())));
207
        text.append(tableRow(i18nc("A button in a mouse press/release event",  "Native Button code"), event->nativeButton()));
208
209
210
211
        text.append(tableRow(i18nc("All currently pressed buttons in a mouse press/release event", "Pressed Buttons"), buttonsToString(event->buttons())));
        break;
    case QEvent::MouseButtonRelease:
        text.append(tableHeaderRow(i18nc("A mouse pointer button release event", "Pointer Button Release")));
212
        text.append(deviceRow(event->device()));
213
214
        text.append(timestamp);
        text.append(tableRow(i18nc("A button in a mouse press/release event", "Button"), buttonToString(event->button())));
215
        text.append(tableRow(i18nc("A button in a mouse press/release event", "Native Button code"), event->nativeButton()));
216
217
218
219
220
221
222
223
224
225
226
        text.append(tableRow(i18nc("All currently pressed buttons in a mouse press/release event", "Pressed Buttons"), buttonsToString(event->buttons())));
        break;
    default:
        break;
    }
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

227
void DebugConsoleFilter::wheelEvent(WheelEvent *event)
228
229
230
231
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A mouse pointer axis (wheel) event", "Pointer Axis")));
Martin Flöser's avatar
Martin Flöser committed
232
    text.append(deviceRow(event->device()));
233
234
235
236
237
    text.append(timestampRow(event->timestamp()));
    const Qt::Orientation orientation = event->angleDelta().x() == 0 ? Qt::Vertical : Qt::Horizontal;
    text.append(tableRow(i18nc("The orientation of a pointer axis event", "Orientation"),
                         orientation == Qt::Horizontal ? i18nc("An orientation of a pointer axis event", "Horizontal")
                                                       : i18nc("An orientation of a pointer axis event", "Vertical")));
238
239
    text.append(tableRow(i18nc("The angle delta of a pointer axis event", "Delta"),
                         orientation == Qt::Horizontal ? event->angleDelta().x() : event->angleDelta().y()));
240
241
242
243
244
245
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

246
void DebugConsoleFilter::keyEvent(KeyEvent *event)
247
248
249
250
251
252
253
254
255
256
257
258
259
260
{
    QString text = s_hr;
    text.append(s_tableStart);

    switch (event->type()) {
    case QEvent::KeyPress:
        text.append(tableHeaderRow(i18nc("A key press event", "Key Press")));
        break;
    case QEvent::KeyRelease:
        text.append(tableHeaderRow(i18nc("A key release event", "Key Release")));
        break;
    default:
        break;
    }
Martin Flöser's avatar
Martin Flöser committed
261
    text.append(deviceRow(event->device()));
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    auto modifiersToString = [event] {
        QString ret;
        if (event->modifiers().testFlag(Qt::ShiftModifier)) {
            ret.append(i18nc("A keyboard modifier", "Shift"));
            ret.append(QStringLiteral(" "));
        }
        if (event->modifiers().testFlag(Qt::ControlModifier)) {
            ret.append(i18nc("A keyboard modifier", "Control"));
            ret.append(QStringLiteral(" "));
        }
        if (event->modifiers().testFlag(Qt::AltModifier)) {
            ret.append(i18nc("A keyboard modifier", "Alt"));
            ret.append(QStringLiteral(" "));
        }
        if (event->modifiers().testFlag(Qt::MetaModifier)) {
            ret.append(i18nc("A keyboard modifier", "Meta"));
            ret.append(QStringLiteral(" "));
        }
        if (event->modifiers().testFlag(Qt::KeypadModifier)) {
            ret.append(i18nc("A keyboard modifier", "Keypad"));
            ret.append(QStringLiteral(" "));
        }
        if (event->modifiers().testFlag(Qt::GroupSwitchModifier)) {
            ret.append(i18nc("A keyboard modifier", "Group-switch"));
            ret.append(QStringLiteral(" "));
        }
        return ret;
    };
    text.append(timestampRow(event->timestamp()));
    text.append(tableRow(i18nc("Whether the event is an automatic key repeat", "Repeat"), event->isAutoRepeat()));
292
293
294

    const auto keyMetaObject = Qt::qt_getEnumMetaObject(Qt::Key());
    const auto enumerator = keyMetaObject->enumerator(keyMetaObject->indexOfEnumerator("Key"));
295
    text.append(tableRow(i18nc("The code as read from the input device", "Scan code"), event->nativeScanCode()));
296
297
    text.append(tableRow(i18nc("Key according to Qt", "Qt::Key code"),
                         enumerator.valueToKey(event->key())));
298
299
300
301
302
303
304
305
306
307
    text.append(tableRow(i18nc("The translated code to an Xkb symbol", "Xkb symbol"), event->nativeVirtualKey()));
    text.append(tableRow(i18nc("The translated code interpreted as text", "Utf8"), event->text()));
    text.append(tableRow(i18nc("The currently active modifiers", "Modifiers"), modifiersToString()));

    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

308
void DebugConsoleFilter::touchDown(qint32 id, const QPointF &pos, quint32 time)
309
310
311
312
313
314
315
316
317
318
319
320
321
322
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A touch down event", "Touch down")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("The id of the touch point in the touch event", "Point identifier"), id));
    text.append(tableRow(i18nc("The global position of the touch point", "Global position"),
                         QStringLiteral("%1/%2").arg(pos.x()).arg(pos.y())));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

323
void DebugConsoleFilter::touchMotion(qint32 id, const QPointF &pos, quint32 time)
324
325
326
327
328
329
330
331
332
333
334
335
336
337
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A touch motion event", "Touch Motion")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("The id of the touch point in the touch event", "Point identifier"), id));
    text.append(tableRow(i18nc("The global position of the touch point", "Global position"),
                         QStringLiteral("%1/%2").arg(pos.x()).arg(pos.y())));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

338
void DebugConsoleFilter::touchUp(qint32 id, quint32 time)
339
340
341
342
343
344
345
346
347
348
349
350
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A touch up event", "Touch Up")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("The id of the touch point in the touch event", "Point identifier"), id));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

351
void DebugConsoleFilter::pinchGestureBegin(int fingerCount, quint32 time)
352
353
354
355
356
357
358
359
360
361
362
363
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A pinch gesture is started", "Pinch start")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("Number of fingers in this pinch gesture", "Finger count"), fingerCount));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

364
void DebugConsoleFilter::pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time)
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A pinch gesture is updated", "Pinch update")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("Current scale in pinch gesture", "Scale"), scale));
    text.append(tableRow(i18nc("Current angle in pinch gesture", "Angle delta"), angleDelta));
    text.append(tableRow(i18nc("Current delta in pinch gesture", "Delta x"), delta.width()));
    text.append(tableRow(i18nc("Current delta in pinch gesture", "Delta y"), delta.height()));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

380
void DebugConsoleFilter::pinchGestureEnd(quint32 time)
381
382
383
384
385
386
387
388
389
390
391
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A pinch gesture ended", "Pinch end")));
    text.append(timestampRow(time));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

392
void DebugConsoleFilter::pinchGestureCancelled(quint32 time)
393
394
395
396
397
398
399
400
401
402
403
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A pinch gesture got cancelled", "Pinch cancelled")));
    text.append(timestampRow(time));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

404
void DebugConsoleFilter::swipeGestureBegin(int fingerCount, quint32 time)
405
406
407
408
409
410
411
412
413
414
415
416
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A swipe gesture is started", "Swipe start")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("Number of fingers in this swipe gesture", "Finger count"), fingerCount));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

417
void DebugConsoleFilter::swipeGestureUpdate(const QSizeF &delta, quint32 time)
418
419
420
421
422
423
424
425
426
427
428
429
430
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A swipe gesture is updated", "Swipe update")));
    text.append(timestampRow(time));
    text.append(tableRow(i18nc("Current delta in swipe gesture", "Delta x"), delta.width()));
    text.append(tableRow(i18nc("Current delta in swipe gesture", "Delta y"), delta.height()));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

431
void DebugConsoleFilter::swipeGestureEnd(quint32 time)
432
433
434
435
436
437
438
439
440
441
442
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A swipe gesture ended", "Swipe end")));
    text.append(timestampRow(time));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

443
void DebugConsoleFilter::swipeGestureCancelled(quint32 time)
444
445
446
447
448
449
450
451
452
453
454
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A swipe gesture got cancelled", "Swipe cancelled")));
    text.append(timestampRow(time));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
void DebugConsoleFilter::switchEvent(SwitchEvent *event)
{
    QString text = s_hr;
    text.append(s_tableStart);
    text.append(tableHeaderRow(i18nc("A hardware switch (e.g. notebook lid) got toggled", "Switch toggled")));
    text.append(timestampRow(event->timestamp()));
    if (event->timestampMicroseconds() != 0) {
        text.append(timestampRowUsec(event->timestampMicroseconds()));
    }
    text.append(deviceRow(event->device()));
    QString switchName;
    if (event->device()->isLidSwitch()) {
        switchName = i18nc("Name of a hardware switch", "Notebook lid");
    } else if (event->device()->isTabletModeSwitch()) {
        switchName = i18nc("Name of a hardware switch", "Tablet mode");
    }
    text.append(tableRow(i18nc("A hardware switch", "Switch"), switchName));
    QString switchState;
    switch (event->state()) {
    case SwitchEvent::State::Off:
        switchState = i18nc("The hardware switch got turned off", "Off");
        break;
    case SwitchEvent::State::On:
        switchState = i18nc("The hardware switch got turned on", "On");
        break;
    default:
        Q_UNREACHABLE();
    }
    text.append(tableRow(i18nc("State of a hardware switch (on/off)", "State"), switchState));
    text.append(s_tableEnd);

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
void DebugConsoleFilter::tabletToolEvent(QTabletEvent *event)
{
    QString typeString;
    {
        QDebug d(&typeString);
        d << event->type();
    }

    QString text = s_hr + s_tableStart + tableHeaderRow(i18n("Tablet Tool"))
                 + tableRow(i18n("EventType"), typeString)
                 + tableRow(i18n("Position"),
                            QStringLiteral("%1,%2").arg(event->pos().x()).arg(event->pos().y()))
                 + tableRow(i18n("Tilt"),
                            QStringLiteral("%1,%2").arg(event->xTilt()).arg(event->yTilt()))
                 + tableRow(i18n("Rotation"), QString::number(event->rotation()))
                 + tableRow(i18n("Pressure"), QString::number(event->pressure()))
                 + tableRow(i18n("Buttons"), QString::number(event->buttons()))
                 + tableRow(i18n("Modifiers"), QString::number(event->modifiers()))
                 + s_tableEnd;

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

void DebugConsoleFilter::tabletToolButtonEvent(const QSet<uint> &pressedButtons)
{
    QString buttons;
    for (uint b : pressedButtons) {
        buttons += QString::number(b) + ' ';
    }
    QString text = s_hr + s_tableStart + tableHeaderRow(i18n("Tablet Tool Button"))
                 + tableRow(i18n("Pressed Buttons"), buttons)
                 + s_tableEnd;

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

void DebugConsoleFilter::tabletPadButtonEvent(const QSet<uint> &pressedButtons)
{
    QString buttons;
    for (uint b : pressedButtons) {
        buttons += QString::number(b) + ' ';
    }
    QString text = s_hr + s_tableStart
                 + tableHeaderRow(i18n("Tablet Pad Button"))
                 + tableRow(i18n("Pressed Buttons"), buttons)
                 + s_tableEnd;

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

void DebugConsoleFilter::tabletPadStripEvent(int number, int position, bool isFinger)
{
    QString text = s_hr + s_tableStart + tableHeaderRow(i18n("Tablet Pad Strip"))
                 + tableRow(i18n("Number"), number)
                 + tableRow(i18n("Position"), position)
                 + tableRow(i18n("isFinger"), isFinger)
                 + s_tableEnd;

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

void DebugConsoleFilter::tabletPadRingEvent(int number, int position, bool isFinger)
{
    QString text = s_hr + s_tableStart + tableHeaderRow(i18n("Tablet Pad Ring"))
                 + tableRow(i18n("Number"), number)
                 + tableRow(i18n("Position"), position)
                 + tableRow(i18n("isFinger"), isFinger)
                 + s_tableEnd;

    m_textEdit->insertHtml(text);
    m_textEdit->ensureCursorVisible();
}

567
568
569
570
DebugConsole::DebugConsole()
    : QWidget()
    , m_ui(new Ui::DebugConsole)
{
571
    setAttribute(Qt::WA_ShowWithoutActivating);
572
    m_ui->setupUi(this);
573
574
575
    m_ui->windowsView->setItemDelegate(new DebugConsoleDelegate(this));
    m_ui->windowsView->setModel(new DebugConsoleModel(this));
    m_ui->surfacesView->setModel(new SurfaceTreeModel(this));
576
577
578
579
    if (kwinApp()->usesLibinput()) {
        m_ui->inputDevicesView->setModel(new InputDeviceModel(this));
        m_ui->inputDevicesView->setItemDelegate(new DebugConsoleDelegate(this));
    }
580
    m_ui->quitButton->setIcon(QIcon::fromTheme(QStringLiteral("application-exit")));
581
582
    m_ui->tabWidget->setTabIcon(0, QIcon::fromTheme(QStringLiteral("view-list-tree")));
    m_ui->tabWidget->setTabIcon(1, QIcon::fromTheme(QStringLiteral("view-list-tree")));
583
584

    if (kwinApp()->operationMode() == Application::OperationMode::OperationModeX11) {
585
586
        m_ui->tabWidget->setTabEnabled(1, false);
        m_ui->tabWidget->setTabEnabled(2, false);
587
    }
588
589
590
    if (!kwinApp()->usesLibinput()) {
        m_ui->tabWidget->setTabEnabled(3, false);
    }
591
592

    connect(m_ui->quitButton, &QAbstractButton::clicked, this, &DebugConsole::deleteLater);
593
594
595
596
    connect(m_ui->tabWidget, &QTabWidget::currentChanged, this,
        [this] (int index) {
            // delay creation of input event filter until the tab is selected
            if (index == 2 && m_inputFilter.isNull()) {
597
                m_inputFilter.reset(new DebugConsoleFilter(m_ui->inputTextEdit));
598
                input()->installInputEventSpy(m_inputFilter.data());
599
            }
600
601
602
603
            if (index == 5) {
                updateKeyboardTab();
                connect(input(), &InputRedirection::keyStateChanged, this, &DebugConsole::updateKeyboardTab);
            }
604
605
        }
    );
606
607
608

    // for X11
    setWindowFlags(Qt::X11BypassWindowManagerHint);
609
610

    initGLTab();
611
612
613
614
}

DebugConsole::~DebugConsole() = default;

615
616
void DebugConsole::initGLTab()
{
Martin Flöser's avatar
Martin Flöser committed
617
    if (!effects || !effects->isOpenGLCompositing()) {
618
619
620
621
        m_ui->noOpenGLLabel->setVisible(true);
        m_ui->glInfoScrollArea->setVisible(false);
        return;
    }
Martin Flöser's avatar
Martin Flöser committed
622
    GLPlatform *gl = GLPlatform::instance();
623
624
625
626
627
628
629
630
631
632
633
    m_ui->noOpenGLLabel->setVisible(false);
    m_ui->glInfoScrollArea->setVisible(true);
    m_ui->glVendorStringLabel->setText(QString::fromLocal8Bit(gl->glVendorString()));
    m_ui->glRendererStringLabel->setText(QString::fromLocal8Bit(gl->glRendererString()));
    m_ui->glVersionStringLabel->setText(QString::fromLocal8Bit(gl->glVersionString()));
    m_ui->glslVersionStringLabel->setText(QString::fromLocal8Bit(gl->glShadingLanguageVersionString()));
    m_ui->glDriverLabel->setText(GLPlatform::driverToString(gl->driver()));
    m_ui->glGPULabel->setText(GLPlatform::chipClassToString(gl->chipClass()));
    m_ui->glVersionLabel->setText(GLPlatform::versionToString(gl->glVersion()));
    m_ui->glslLabel->setText(GLPlatform::versionToString(gl->glslVersion()));

634
    auto extensionsString = [] (const auto &extensions) {
635
636
637
638
639
640
641
642
        QString text = QStringLiteral("<ul>");
        for (auto extension : extensions) {
            text.append(QStringLiteral("<li>%1</li>").arg(QString::fromLocal8Bit(extension)));
        }
        text.append(QStringLiteral("</ul>"));
        return text;
    };

643
    m_ui->platformExtensionsLabel->setText(extensionsString(Compositor::self()->scene()->openGLPlatformInterfaceExtensions()));
644
645
646
    m_ui->openGLExtensionsLabel->setText(extensionsString(openGLExtensions()));
}

647
648
649
650
651
652
653
654
655
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
template <typename T>
QString keymapComponentToString(xkb_keymap *map, const T &count, std::function<const char*(xkb_keymap*,T)> f)
{
    QString text = QStringLiteral("<ul>");
    for (T i = 0; i < count; i++) {
        text.append(QStringLiteral("<li>%1</li>").arg(QString::fromLocal8Bit(f(map, i))));
    }
    text.append(QStringLiteral("</ul>"));
    return text;
}

template <typename T>
QString stateActiveComponents(xkb_state *state, const T &count, std::function<int(xkb_state*,T)> f, std::function<const char*(xkb_keymap*,T)> name)
{
    QString text = QStringLiteral("<ul>");
    xkb_keymap *map = xkb_state_get_keymap(state);
    for (T i = 0; i < count; i++) {
        if (f(state, i) == 1) {
            text.append(QStringLiteral("<li>%1</li>").arg(QString::fromLocal8Bit(name(map, i))));
        }
    }
    text.append(QStringLiteral("</ul>"));
    return text;
}

void DebugConsole::updateKeyboardTab()
{
    auto xkb = input()->keyboard()->xkb();
    xkb_keymap *map = xkb->keymap();
    xkb_state *state = xkb->state();
    m_ui->layoutsLabel->setText(keymapComponentToString<xkb_layout_index_t>(map, xkb_keymap_num_layouts(map), &xkb_keymap_layout_get_name));
    m_ui->currentLayoutLabel->setText(xkb_keymap_layout_get_name(map, xkb->currentLayout()));
    m_ui->modifiersLabel->setText(keymapComponentToString<xkb_mod_index_t>(map, xkb_keymap_num_mods(map), &xkb_keymap_mod_get_name));
    m_ui->ledsLabel->setText(keymapComponentToString<xkb_led_index_t>(map, xkb_keymap_num_leds(map), &xkb_keymap_led_get_name));
    m_ui->activeLedsLabel->setText(stateActiveComponents<xkb_led_index_t>(state, xkb_keymap_num_leds(map), &xkb_state_led_index_is_active, &xkb_keymap_led_get_name));

    using namespace std::placeholders;
    auto modActive = std::bind(xkb_state_mod_index_is_active, _1, _2, XKB_STATE_MODS_EFFECTIVE);
    m_ui->activeModifiersLabel->setText(stateActiveComponents<xkb_mod_index_t>(state, xkb_keymap_num_mods(map), modActive, &xkb_keymap_mod_get_name));
}

688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
void DebugConsole::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    // delay the connection to the show event as in ctor the windowHandle returns null
    connect(windowHandle(), &QWindow::visibleChanged, this,
        [this] (bool visible) {
            if (visible) {
                // ignore
                return;
            }
            deleteLater();
        }
    );
}

704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
DebugConsoleDelegate::DebugConsoleDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

DebugConsoleDelegate::~DebugConsoleDelegate() = default;

QString DebugConsoleDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
    switch (value.type()) {
    case QMetaType::QPoint: {
        const QPoint p = value.toPoint();
        return QStringLiteral("%1,%2").arg(p.x()).arg(p.y());
    }
    case QMetaType::QPointF: {
        const QPointF p = value.toPointF();
        return QStringLiteral("%1,%2").arg(p.x()).arg(p.y());
    }
    case QMetaType::QSize: {
        const QSize s = value.toSize();
        return QStringLiteral("%1x%2").arg(s.width()).arg(s.height());
    }
    case QMetaType::QSizeF: {
        const QSizeF s = value.toSizeF();
        return QStringLiteral("%1x%2").arg(s.width()).arg(s.height());
    }
    case QMetaType::QRect: {
        const QRect r = value.toRect();
        return QStringLiteral("%1,%2 %3x%4").arg(r.x()).arg(r.y()).arg(r.width()).arg(r.height());
    }
    default:
        if (value.userType() == qMetaTypeId<KWayland::Server::SurfaceInterface*>()) {
            if (auto s = value.value<KWayland::Server::SurfaceInterface*>()) {
                return QStringLiteral("KWayland::Server::SurfaceInterface(0x%1)").arg(qulonglong(s), 0, 16);
            } else {
                return QStringLiteral("nullptr");
            }
        }
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
        if (value.userType() == qMetaTypeId<Qt::MouseButtons>()) {
            const auto buttons = value.value<Qt::MouseButtons>();
            if (buttons == Qt::NoButton) {
                return i18n("No Mouse Buttons");
            }
            QStringList list;
            if (buttons.testFlag(Qt::LeftButton)) {
                list << i18nc("Mouse Button", "left");
            }
            if (buttons.testFlag(Qt::RightButton)) {
                list << i18nc("Mouse Button", "right");
            }
            if (buttons.testFlag(Qt::MiddleButton)) {
                list << i18nc("Mouse Button", "middle");
            }
            if (buttons.testFlag(Qt::BackButton)) {
                list << i18nc("Mouse Button", "back");
            }
            if (buttons.testFlag(Qt::ForwardButton)) {
                list << i18nc("Mouse Button", "forward");
            }
            if (buttons.testFlag(Qt::ExtraButton1)) {
                list << i18nc("Mouse Button", "extra 1");
            }
            if (buttons.testFlag(Qt::ExtraButton2)) {
                list << i18nc("Mouse Button", "extra 2");
            }
            if (buttons.testFlag(Qt::ExtraButton3)) {
                list << i18nc("Mouse Button", "extra 3");
            }
            if (buttons.testFlag(Qt::ExtraButton4)) {
                list << i18nc("Mouse Button", "extra 4");
            }
            if (buttons.testFlag(Qt::ExtraButton5)) {
                list << i18nc("Mouse Button", "extra 5");
            }
            if (buttons.testFlag(Qt::ExtraButton6)) {
                list << i18nc("Mouse Button", "extra 6");
            }
            if (buttons.testFlag(Qt::ExtraButton7)) {
                list << i18nc("Mouse Button", "extra 7");
            }
            if (buttons.testFlag(Qt::ExtraButton8)) {
                list << i18nc("Mouse Button", "extra 8");
            }
            if (buttons.testFlag(Qt::ExtraButton9)) {
                list << i18nc("Mouse Button", "extra 9");
            }
            if (buttons.testFlag(Qt::ExtraButton10)) {
                list << i18nc("Mouse Button", "extra 10");
            }
            if (buttons.testFlag(Qt::ExtraButton11)) {
                list << i18nc("Mouse Button", "extra 11");
            }
            if (buttons.testFlag(Qt::ExtraButton12)) {
                list << i18nc("Mouse Button", "extra 12");
            }
            if (buttons.testFlag(Qt::ExtraButton13)) {
                list << i18nc("Mouse Button", "extra 13");
            }
            if (buttons.testFlag(Qt::ExtraButton14)) {
                list << i18nc("Mouse Button", "extra 14");
            }
            if (buttons.testFlag(Qt::ExtraButton15)) {
                list << i18nc("Mouse Button", "extra 15");
            }
            if (buttons.testFlag(Qt::ExtraButton16)) {
                list << i18nc("Mouse Button", "extra 16");
            }
            if (buttons.testFlag(Qt::ExtraButton17)) {
                list << i18nc("Mouse Button", "extra 17");
            }
            if (buttons.testFlag(Qt::ExtraButton18)) {
                list << i18nc("Mouse Button", "extra 18");
            }
            if (buttons.testFlag(Qt::ExtraButton19)) {
                list << i18nc("Mouse Button", "extra 19");
            }
            if (buttons.testFlag(Qt::ExtraButton20)) {
                list << i18nc("Mouse Button", "extra 20");
            }
            if (buttons.testFlag(Qt::ExtraButton21)) {
                list << i18nc("Mouse Button", "extra 21");
            }
            if (buttons.testFlag(Qt::ExtraButton22)) {
                list << i18nc("Mouse Button", "extra 22");
            }
            if (buttons.testFlag(Qt::ExtraButton23)) {
                list << i18nc("Mouse Button", "extra 23");
            }
            if (buttons.testFlag(Qt::ExtraButton24)) {
                list << i18nc("Mouse Button", "extra 24");
            }
            if (buttons.testFlag(Qt::TaskButton)) {
                list << i18nc("Mouse Button", "task");
            }
            return list.join(QStringLiteral(", "));
        }
840
841
842
843
844
845
846
847
        break;
    }
    return QStyledItemDelegate::displayText(value, locale);
}

static const int s_x11ClientId = 1;
static const int s_x11UnmanagedId = 2;
static const int s_waylandClientId = 3;
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
848
static const int s_workspaceInternalId = 4;
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
static const quint32 s_propertyBitMask = 0xFFFF0000;
static const quint32 s_clientBitMask   = 0x0000FFFF;
static const quint32 s_idDistance = 10000;

template <class T>
void DebugConsoleModel::add(int parentRow, QVector<T*> &clients, T *client)
{
    beginInsertRows(index(parentRow, 0, QModelIndex()), clients.count(), clients.count());
    clients.append(client);
    endInsertRows();
}

template <class T>
void DebugConsoleModel::remove(int parentRow, QVector<T*> &clients, T *client)
{
    const int remove = clients.indexOf(client);
    if (remove == -1) {
        return;
    }
    beginRemoveRows(index(parentRow, 0, QModelIndex()), remove, remove);
    clients.removeAt(remove);
    endRemoveRows();
}

DebugConsoleModel::DebugConsoleModel(QObject *parent)
    : QAbstractItemModel(parent)
{
    if (waylandServer()) {
        const auto clients = waylandServer()->clients();
        for (auto c : clients) {
            m_shellClients.append(c);
        }
        // TODO: that only includes windows getting shown, not those which are only created
        connect(waylandServer(), &WaylandServer::shellClientAdded, this,
883
            [this] (XdgShellClient *c) {
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
884
                add(s_waylandClientId -1, m_shellClients, c);
885
886
887
            }
        );
        connect(waylandServer(), &WaylandServer::shellClientRemoved, this,
888
            [this] (XdgShellClient *c) {
889
890
891
892
893
894
895
896
897
898
899
900
901
                remove(s_waylandClientId -1, m_shellClients, c);
            }
        );
    }
    const auto x11Clients = workspace()->clientList();
    for (auto c : x11Clients) {
        m_x11Clients.append(c);
    }
    const auto x11DesktopClients = workspace()->desktopList();
    for (auto c : x11DesktopClients) {
        m_x11Clients.append(c);
    }
    connect(workspace(), &Workspace::clientAdded, this,
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
902
        [this] (X11Client *c) {
903
904
905
906
907
            add(s_x11ClientId -1, m_x11Clients, c);
        }
    );
    connect(workspace(), &Workspace::clientRemoved, this,
        [this] (AbstractClient *ac) {
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
908
            X11Client *c = qobject_cast<X11Client *>(ac);
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
            if (!c) {
                return;
            }
            remove(s_x11ClientId -1, m_x11Clients, c);
        }
    );

    const auto unmangeds = workspace()->unmanagedList();
    for (auto u : unmangeds) {
        m_unmanageds.append(u);
    }
    connect(workspace(), &Workspace::unmanagedAdded, this,
        [this] (Unmanaged *u) {
            add(s_x11UnmanagedId -1, m_unmanageds, u);
        }
    );
    connect(workspace(), &Workspace::unmanagedRemoved, this,
        [this] (Unmanaged *u) {
            remove(s_x11UnmanagedId -1, m_unmanageds, u);
        }
    );
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
930
931
932
933
934
935
936
937
938
939
940
941
942
    for (InternalClient *client : workspace()->internalClients()) {
        m_internalClients.append(client);
    }
    connect(workspace(), &Workspace::internalClientAdded, this,
        [this](InternalClient *client) {
            add(s_workspaceInternalId -1, m_internalClients, client);
        }
    );
    connect(workspace(), &Workspace::internalClientRemoved, this,
        [this](InternalClient *client) {
            remove(s_workspaceInternalId -1, m_internalClients, client);
        }
    );
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
}

DebugConsoleModel::~DebugConsoleModel() = default;

int DebugConsoleModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 2;
}

int DebugConsoleModel::topLevelRowCount() const
{
    return kwinApp()->shouldUseWaylandForCompositing() ? 4 : 2;
}

template <class T>
int DebugConsoleModel::propertyCount(const QModelIndex &parent, T *(DebugConsoleModel::*filter)(const QModelIndex&) const) const
{
    if (T *t = (this->*filter)(parent)) {
        return t->metaObject()->propertyCount();
    }
    return 0;
}

int DebugConsoleModel::rowCount(const QModelIndex &parent) const
{
    if (!parent.isValid()) {
        return topLevelRowCount();
    }

    switch (parent.internalId()) {
    case s_x11ClientId:
        return m_x11Clients.count();
    case s_x11UnmanagedId:
        return m_unmanageds.count();
    case s_waylandClientId:
        return m_shellClients.count();
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
980
    case s_workspaceInternalId:
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
        return m_internalClients.count();
    default:
        break;
    }

    if (parent.internalId() & s_propertyBitMask) {
        // properties do not have children
        return 0;
    }

    if (parent.internalId() < s_idDistance * (s_x11ClientId + 1)) {
        return propertyCount(parent, &DebugConsoleModel::x11Client);
    } else if (parent.internalId() < s_idDistance * (s_x11UnmanagedId + 1)) {
        return propertyCount(parent, &DebugConsoleModel::unmanaged);
    } else if (parent.internalId() < s_idDistance * (s_waylandClientId + 1)) {
        return propertyCount(parent, &DebugConsoleModel::shellClient);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
997
    } else if (parent.internalId() < s_idDistance * (s_workspaceInternalId + 1)) {
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
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
        return propertyCount(parent, &DebugConsoleModel::internalClient);
    }

    return 0;
}

template <class T>
QModelIndex DebugConsoleModel::indexForClient(int row, int column, const QVector<T*> &clients, int id) const
{
    if (column != 0) {
        return QModelIndex();
    }
    if (row >= clients.count()) {
        return QModelIndex();
    }
    return createIndex(row, column, s_idDistance * id + row);
}

template <class T>
QModelIndex DebugConsoleModel::indexForProperty(int row, int column, const QModelIndex &parent, T *(DebugConsoleModel::*filter)(const QModelIndex&) const) const
{
    if (T *t = (this->*filter)(parent)) {
        if (row >= t->metaObject()->propertyCount()) {
            return QModelIndex();
        }
        return createIndex(row, column, quint32(row + 1) << 16 | parent.internalId());
    }
    return QModelIndex();
}

QModelIndex DebugConsoleModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!parent.isValid()) {
        // index for a top level item
        if (column != 0 || row >= topLevelRowCount()) {
            return QModelIndex();
        }
        return createIndex(row, column, row + 1);
    }
    if (column >= 2) {
        // max of 2 columns
        return QModelIndex();
    }
    // index for a client (second level)
    switch (parent.internalId()) {
    case s_x11ClientId:
        return indexForClient(row, column, m_x11Clients, s_x11ClientId);
    case s_x11UnmanagedId:
        return indexForClient(row, column, m_unmanageds, s_x11UnmanagedId);
    case s_waylandClientId:
        return indexForClient(row, column, m_shellClients, s_waylandClientId);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1049
1050
    case s_workspaceInternalId:
        return indexForClient(row, column, m_internalClients, s_workspaceInternalId);
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
    default:
        break;
    }

    // index for a property (third level)
    if (parent.internalId() < s_idDistance * (s_x11ClientId + 1)) {
        return indexForProperty(row, column, parent, &DebugConsoleModel::x11Client);
    } else if (parent.internalId() < s_idDistance * (s_x11UnmanagedId + 1)) {
        return indexForProperty(row, column, parent, &DebugConsoleModel::unmanaged);
    } else if (parent.internalId() < s_idDistance * (s_waylandClientId + 1)) {
        return indexForProperty(row, column, parent, &DebugConsoleModel::shellClient);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1062
    } else if (parent.internalId() < s_idDistance * (s_workspaceInternalId + 1)) {
1063
1064
1065
1066
1067
1068
1069
1070
        return indexForProperty(row, column, parent, &DebugConsoleModel::internalClient);
    }

    return QModelIndex();
}

QModelIndex DebugConsoleModel::parent(const QModelIndex &child) const
{
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1071
    if (child.internalId() <= s_workspaceInternalId) {
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
        return QModelIndex();
    }
    if (child.internalId() & s_propertyBitMask) {
        // a property
        const quint32 parentId = child.internalId() & s_clientBitMask;
        if (parentId < s_idDistance * (s_x11ClientId + 1)) {
            return createIndex(parentId - (s_idDistance * s_x11ClientId), 0, parentId);
        } else if (parentId < s_idDistance * (s_x11UnmanagedId + 1)) {
            return createIndex(parentId - (s_idDistance * s_x11UnmanagedId), 0, parentId);
        } else if (parentId < s_idDistance * (s_waylandClientId + 1)) {
            return createIndex(parentId - (s_idDistance * s_waylandClientId), 0, parentId);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1083
1084
        } else if (parentId < s_idDistance * (s_workspaceInternalId + 1)) {
            return createIndex(parentId - (s_idDistance * s_workspaceInternalId), 0, parentId);
1085
1086
1087
1088
1089
1090
1091
1092
1093
        }
        return QModelIndex();
    }
    if (child.internalId() < s_idDistance * (s_x11ClientId + 1)) {
        return createIndex(s_x11ClientId -1, 0, s_x11ClientId);
    } else if (child.internalId() < s_idDistance * (s_x11UnmanagedId + 1)) {
        return createIndex(s_x11UnmanagedId -1, 0, s_x11UnmanagedId);
    } else if (child.internalId() < s_idDistance * (s_waylandClientId + 1)) {
        return createIndex(s_waylandClientId -1, 0, s_waylandClientId);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1094
1095
    } else if (child.internalId() < s_idDistance * (s_workspaceInternalId + 1)) {
        return createIndex(s_workspaceInternalId -1, 0, s_workspaceInternalId);
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
    }
    return QModelIndex();
}

QVariant DebugConsoleModel::propertyData(QObject *object, const QModelIndex &index, int role) const
{
    Q_UNUSED(role)
    const auto property = object->metaObject()->property(index.row());
    if (index.column() == 0) {
        return property.name();
    } else {
        const QVariant value = property.read(object);
        if (qstrcmp(property.name(), "windowType") == 0) {
            switch (value.toInt()) {
            case NET::Normal:
                return QStringLiteral("NET::Normal");
            case NET::Desktop:
                return QStringLiteral("NET::Desktop");
            case NET::Dock:
                return QStringLiteral("NET::Dock");
            case NET::Toolbar:
                return QStringLiteral("NET::Toolbar");
            case NET::Menu:
                return QStringLiteral("NET::Menu");
            case NET::Dialog:
                return QStringLiteral("NET::Dialog");
            case NET::Override:
                return QStringLiteral("NET::Override");
            case NET::TopMenu:
                return QStringLiteral("NET::TopMenu");
            case NET::Utility:
                return QStringLiteral("NET::Utility");
            case NET::Splash:
                return QStringLiteral("NET::Splash");
            case NET::DropdownMenu:
                return QStringLiteral("NET::DropdownMenu");
            case NET::PopupMenu:
                return QStringLiteral("NET::PopupMenu");
            case NET::Tooltip:
                return QStringLiteral("NET::Tooltip");
            case NET::Notification:
                return QStringLiteral("NET::Notification");
            case NET::ComboBox:
                return QStringLiteral("NET::ComboBox");
            case NET::DNDIcon:
                return QStringLiteral("NET::DNDIcon");
            case NET::OnScreenDisplay:
                return QStringLiteral("NET::OnScreenDisplay");
1144
1145
            case NET::CriticalNotification:
                return QStringLiteral("NET::CriticalNotification");
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
            case NET::Unknown:
            default:
                return QStringLiteral("NET::Unknown");
            }
        }
        return value;
    }
    return QVariant();
}

template <class T>
QVariant DebugConsoleModel::clientData(const QModelIndex &index, int role, const QVector<T*> clients) const
{
    if (index.row() >= clients.count()) {
        return QVariant();
    }
    auto c = clients.at(index.row());
    if (role == Qt::DisplayRole) {
        return QStringLiteral("%1: %2").arg(c->window()).arg(c->caption());
    } else if (role == Qt::DecorationRole) {
        return c->icon();
    }
    return QVariant();
}

QVariant DebugConsoleModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }
    if (!index.parent().isValid()) {
        // one of the top levels
        if (index.column() != 0 || role != Qt::DisplayRole) {
            return QVariant();
        }
        switch (index.internalId()) {
        case s_x11ClientId:
            return i18n("X11 Client Windows");
        case s_x11UnmanagedId:
            return i18n("X11 Unmanaged Windows");
        case s_waylandClientId:
            return i18n("Wayland Windows");
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1188
        case s_workspaceInternalId:
1189
1190
1191
1192
1193
1194
1195
1196
1197
            return i18n("Internal Windows");
        default:
            return QVariant();
        }
    }
    if (index.internalId() & s_propertyBitMask) {
        if (index.column() >= 2 || role != Qt::DisplayRole) {
            return QVariant();
        }
1198
        if (XdgShellClient *c = shellClient(index)) {
1199
            return propertyData(c, index, role);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1200
        } else if (InternalClient *c = internalClient(index)) {
1201
            return propertyData(c, index, role);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1202
        } else if (X11Client *c = x11Client(index)) {
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
            return propertyData(c, index, role);
        } else if (Unmanaged *u = unmanaged(index)) {
            return propertyData(u, index, role);
        }
    } else {
        if (index.column() != 0) {
            return QVariant();
        }
        switch (index.parent().internalId()) {
        case s_x11ClientId:
            return clientData(index, role, m_x11Clients);
        case s_x11UnmanagedId: {
            if (index.row() >= m_unmanageds.count()) {
                return QVariant();
            }
            auto u = m_unmanageds.at(index.row());
            if (role == Qt::DisplayRole) {
                return u->window();
            }
            break;
        }
        case s_waylandClientId:
            return clientData(index, role, m_shellClients);
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1226
        case s_workspaceInternalId:
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
            return clientData(index, role, m_internalClients);
        default:
            break;
        }
    }

    return QVariant();
}

template<class T>
static T *clientForIndex(const QModelIndex &index, const QVector<T*> &clients, int id)
{
    const qint32 row = (index.internalId() & s_clientBitMask) - (s_idDistance * id);
    if (row < 0 || row >= clients.count()) {
        return nullptr;
    }
    return clients.at(row);
}

1246
XdgShellClient *DebugConsoleModel::shellClient(const QModelIndex &index) const
1247
1248
1249
1250
{
    return clientForIndex(index, m_shellClients, s_waylandClientId);
}

Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1251
InternalClient *DebugConsoleModel::internalClient(const QModelIndex &index) const
1252
{
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1253
    return clientForIndex(index, m_internalClients, s_workspaceInternalId);
1254
1255
}

Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1256
X11Client *DebugConsoleModel::x11Client(const QModelIndex &index) const
1257
1258
1259
1260
1261
1262
1263
1264
1265
{
    return clientForIndex(index, m_x11Clients, s_x11ClientId);
}

Unmanaged *DebugConsoleModel::unmanaged(const QModelIndex &index) const
{
    return clientForIndex(index, m_unmanageds, s_x11UnmanagedId);
}

1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
/////////////////////////////////////// SurfaceTreeModel
SurfaceTreeModel::SurfaceTreeModel(QObject *parent)
    : QAbstractItemModel(parent)
{
    // TODO: it would be nice to not have to reset the model on each change
    auto reset = [this] {
        beginResetModel();
        endResetModel();
    };
    using namespace KWayland::Server;

    const auto unmangeds = workspace()->unmanagedList();
    for (auto u : unmangeds) {
1279
1280
1281
        if (!u->surface()) {
            continue;
        }
1282
1283
1284
        connect(u->surface(), &SurfaceInterface::subSurfaceTreeChanged, this, reset);
    }
    for (auto c : workspace()->allClientList()) {
1285
1286
1287
        if (!c->surface()) {
            continue;
        }
1288
1289
1290
        connect(c->surface(), &SurfaceInterface::subSurfaceTreeChanged, this, reset);
    }
    for (auto c : workspace()->desktopList()) {
1291
1292
1293
        if (!c->surface()) {
            continue;
        }
1294
1295
        connect(c->surface(), &SurfaceInterface::subSurfaceTreeChanged, this, reset);
    }
1296
1297
    if (waylandServer()) {
        connect(waylandServer(), &WaylandServer::shellClientAdded, this,
1298
            [this, reset] (XdgShellClient *c) {
1299
1300
1301
1302
1303
                connect(c->surface(), &SurfaceInterface::subSurfaceTreeChanged, this, reset);
                reset();
            }
        );
    }
1304
1305
    connect(workspace(), &Workspace::clientAdded, this,
        [this, reset] (AbstractClient *c) {
1306
1307
1308
            if (c->surface()) {
                connect(c->surface(), &SurfaceInterface::subSurfaceTreeChanged, this, reset);
            }
1309
1310
1311
1312
1313
1314
            reset();
        }
    );
    connect(workspace(), &Workspace::clientRemoved, this, reset);
    connect(workspace(), &Workspace::unmanagedAdded, this,
        [this, reset] (Unmanaged *u) {
1315
1316
1317
            if (u->surface()) {
                connect(u->surface(), &SurfaceInterface::subSurfaceTreeChanged, this, reset);
            }
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
            reset();
        }
    );
    connect(workspace(), &Workspace::unmanagedRemoved, this, reset);
}

SurfaceTreeModel::~SurfaceTreeModel() = default;

int SurfaceTreeModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 1;
}

int SurfaceTreeModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        using namespace KWayland::Server;
        if (SurfaceInterface *surface = static_cast<SurfaceInterface*>(parent.internalPointer())) {
            const auto &children = surface->childSubSurfaces();
            return children.count();
        }
        return 0;
    }
    // toplevel are all windows
    return workspace()->allClientList().count() +
           workspace()->desktopList().count() +
Vlad Zahorodnii's avatar
Vlad Zahorodnii committed
1345
           workspace()->unmanagedList().count();
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
}

QModelIndex SurfaceTreeModel::index(int row, int column, const QModelIndex &parent) const
{
    if (column != 0) {
        // invalid column
        return QModelIndex();
    }

    if (parent.isValid()) {
        using namespace KWayland::Server;
        if (SurfaceInterface *surface = static_cast<SurfaceInterface*>(parent.internalPointer())) {
            const auto &children = surface->childSubSurfaces();
            if (row < children.count()) {
                return createIndex(row, column, children.at(row)->surface().data());
            }
        }
        return QModelIndex();
    }
    // a window
    const auto &allClients = workspace()->allClientList();
    if (row < allClients.count()) {
        // references a client
        return createIndex(row, column, allClients.at(row)->surface());
    }
    int reference = allClients.count();
    const auto &desktopClients = workspace()->desktopList();
    if (row < reference + desktopClients.count()) {
        return createIndex(row, column, desktopClients.at(row-reference)->surface());
    }
    reference += desktopClients.count();
    const auto &unmanaged = workspace()->unmanagedList();
    if (row < reference + unmanaged.count()) {
        return createIndex(row, column, unmanaged.at(row-reference)->surface());
    }
    reference += unmanaged.count();
    // not found
    return QModelIndex();
}

QModelIndex SurfaceTreeModel::parent(const QModelIndex &child) const
{
    using namespace KWayland::Server;
    if (SurfaceInterface *surface = static_cast<SurfaceInterface*>(child.internalPointer())) {
        const auto &subsurface = surface->subSurface();
        if (subsurface.isNull()) {
            // doesn't reference a subsurface, this is a top-level window
            return QModelIndex();
        }
        SurfaceInterface *parent = subsurface->parentSurface().data();
        if (!parent) {
            // something is wrong
            return QModelIndex();
        }
        // is the parent a subsurface itself?
        if (parent->subSurface()) {
            auto grandParent = parent->subSurface()->parentSurface();
            if (grandParent.isNull()) {
                // something is wrong
                return QModelIndex();
            }
            const auto &children = grandParent->childSubSurfaces();
            for (int row = 0; row < children.count(); row++) {
                if (children.at(row).data() == parent->subSurface().data()) {
                    return createIndex(row, 0, parent);
                }
            }
            return QModelIndex();
        }
        // not a subsurface, thus it's a true window
        int row = 0;
        const auto &allClients = workspace()->allClientList();
        for (; row < allClients.count(); row++) {
            if (allClients.at(row)->surface() == parent) {
                return createIndex(row, 0, parent);
            }
        }
        row = allClients.count();
        const auto &desktopClients = workspace()->desktopList();
        for (int i = 0; i < desktopClients.count(); i++) {
            if (desktopClients.at(i)->surface() == parent) {
                return createIndex(row + i, 0, parent);
            }
        }
        row += desktopClients.count();
        const auto &unmanaged = workspace()->unmanagedList();
        for (int i = 0; i < unmanaged.count(); i++) {
            if (unmanaged.at(i)->surface() == parent) {
                return createIndex(row + i, 0, parent);
            }
        }
        row += unmanaged.count();
    }
    return QModelIndex();
}

QVariant SurfaceTreeModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }
    using namespace KWayland::Server;
    if (SurfaceInterface *surface = static_cast<SurfaceInterface*>(index.internalPointer())) {
        if (role == Qt::DisplayRole || role == Qt::ToolTipRole) {
            return QStringLiteral("%1 (%2) - %3").arg(surface->client()->executablePath())
                                                .arg(surface->client()->processId())
                                                .arg(surface->id());
        } else if (role == Qt::DecorationRole) {
            if (auto buffer = surface->buffer()) {
                if (buffer->shmBuffer()) {
                    return buffer->data().scaled(QSize(64, 64), Qt::KeepAspectRatio);
                }
            }
        }
    }
    return QVariant();
}

1464
1465
InputDeviceModel::InputDeviceModel(QObject *parent)
    : QAbstractItemModel(parent)
1466
    , m_devices(LibInput::Connection::self()->devices())
1467
{
1468
1469
1470
    for (auto it = m_devices.constBegin(); it != m_devices.constEnd(); ++it) {
        setupDeviceConnections(*it);
    }
1471
    auto c = LibInput::Connection::self();
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
    connect(c, &LibInput::Connection::deviceAdded, this,
        [this] (LibInput::Device *d) {
            beginInsertRows(QModelIndex(), m_devices.count(), m_devices.count());
            m_devices << d;
            setupDeviceConnections(d);
            endInsertRows();
        }
    );
    connect(c, &LibInput::Connection::deviceRemoved, this,
        [this] (LibInput::Device *d) {
            const int index = m_devices.indexOf(d);
            if (index == -1) {
                return;
            }
            beginRemoveRows(QModelIndex(), index, index);
            m_devices.removeAt(index);
            endRemoveRows();
        }
    );
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
}

InputDeviceModel::~InputDeviceModel() = default;


int InputDeviceModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 2;
}

QVariant InputDeviceModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }
    if (!index.parent().isValid() && index.column() == 0) {
        const auto devices = LibInput::Connection::self()->devices();
        if (index.row() >= devices.count()) {
            return QVariant();
        }
        if (role == Qt::DisplayRole) {
            return devices.at(index.row())->name();
        }
    }
    if (index.parent().isValid()) {
        if (role == Qt::DisplayRole) {
            const auto device = LibInput::Connection::self()->devices().at(index.parent().row());
            const auto property = device->metaObject()->property(index.row());
            if (index.column() == 0) {
                return property.name();
            } else if (index.column() == 1) {
                return device->property(property.name());
            }
        }
    }
    return QVariant();
}

QModelIndex InputDeviceModel::index(int row, int column, const QModelIndex &parent) const
{
    if (column >= 2) {
        return QModelIndex();
    }
    if (parent.isValid()) {
        if (parent.internalId() & s_propertyBitMask) {
            return QModelIndex();
        }
        if (row >= LibInput::Connection::self()->devices().at(parent.row())->metaObject()->propertyCount()) {
            return QModelIndex();
        }
        return createIndex(row, column, quint32(row + 1) << 16 | parent.internalId());
    }
    if (row >= LibInput::Connection::self()->devices().count()) {
        return QModelIndex();
    }
    return createIndex(row, column, row + 1);
}

int InputDeviceModel::rowCount(const QModelIndex &parent) const
{
    if (!parent.isValid()) {
        return LibInput::Connection::self()->devices().count();
    }
    if (parent.internalId() & s_propertyBitMask) {
        return 0;
    }

    return LibInput::Connection::self()->devices().at(parent.row())->metaObject()->propertyCount();
}

QModelIndex InputDeviceModel::parent(const QModelIndex &child) const
{
    if (child.internalId() & s_propertyBitMask) {
        const quintptr parentId = child.internalId() & s_clientBitMask;
        return createIndex(parentId - 1, 0, parentId);
    }
    return QModelIndex();
}

1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
void InputDeviceModel::setupDeviceConnections(LibInput::Device *device)
{
    connect(device, &LibInput::Device::enabledChanged, this,
        [this, device] {
            const QModelIndex parent = index(m_devices.indexOf(device), 0, QModelIndex());
            const QModelIndex child = index(device->metaObject()->indexOfProperty("enabled"), 1, parent);
            emit dataChanged(child, child, QVector<int>{Qt::DisplayRole});
        }
    );
    connect(device, &LibInput::Device::leftHandedChanged, this,
        [this, device] {
            const QModelIndex parent = index(m_devices.indexOf(device), 0, QModelIndex());
            const QModelIndex child = index(device->metaObject()->indexOfProperty("leftHanded"), 1, parent);
            emit dataChanged(child, child, QVector<int>{Qt::DisplayRole});
        }
    );
    connect(device, &LibInput::Device::pointerAccelerationChanged, this,
        [this, device] {
            const QModelIndex parent = index(m_devices.indexOf(device), 0, QModelIndex());
            const QModelIndex child = index(device->metaObject()->indexOfProperty("pointerAcceleration"), 1, parent);
            emit dataChanged(child, child, QVector<int>{Qt::DisplayRole});
        }
    );
}

1596
}