File: process_data_model.cpp

package info (click to toggle)
libksysguard 4%3A6.5.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,596 kB
  • sloc: cpp: 13,691; xml: 297; sh: 23; makefile: 11
file content (529 lines) | stat: -rw-r--r-- 15,605 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
222
223
224
225
226
227
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
256
257
258
259
260
261
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
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
/*
    SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "process_data_model.h"

#include <ranges>

#include "formatter.h"

#include "processcore/extended_process_list.h"
#include "processcore/process.h"
#include "processcore/process_attribute.h"
#include "processcore/process_attribute_model.h"
#include "processcore/process_data_provider.h"

#include <QMetaEnum>
#include <QTimer>

using namespace KSysGuard;

class Q_DECL_HIDDEN KSysGuard::ProcessDataModel::Private
{
public:
    Private(ProcessDataModel *q);
    void beginInsertRow(KSysGuard::Process *parent);
    void endInsertRow();
    void beginMoveProcess(KSysGuard::Process *process, KSysGuard::Process *new_parent);
    void endMoveProcess();
    void beginRemoveRow(KSysGuard::Process *process);
    void endRemoveRow();

    void update();
    QModelIndex getQModelIndex(Process *process, int column) const;
    void handleChangedProcesses();

    ProcessDataModel *q;
    KSysGuard::Process *m_rootProcess;
    QSharedPointer<ExtendedProcesses> m_processes;
    QTimer *m_timer;
    ProcessAttributeModel *m_attributeModel = nullptr;
    const int m_updateInterval = 2000;
    bool m_flatList = true;

    QHash<QString, KSysGuard::ProcessAttribute *> m_availableAttributes;
    QList<KSysGuard::ProcessAttribute *> m_enabledAttributes;

    // A list of indices that we got change notifications for that still need to
    // be propagated. Note that this needs to be stored as QPersistentModelIndex
    // so any changes to rows and columns are automatically accounted for in the
    // index.
    QList<QPersistentModelIndex> m_pendingChanges;
};

ProcessDataModel::ProcessDataModel(QObject *parent)
    : QAbstractItemModel(parent)
    , d(new ProcessDataModel::Private(this))
{
}

ProcessDataModel::~ProcessDataModel()
{
}

ProcessDataModel::Private::Private(ProcessDataModel *_q)
    : q(_q)
    , m_processes(KSysGuard::ExtendedProcesses::instance())
    , m_timer(new QTimer(_q))
{
    m_rootProcess = m_processes->getProcess(-1);
    connect(m_processes.get(), &KSysGuard::Processes::beginAddProcess, q, [this](KSysGuard::Process *process) {
        beginInsertRow(process);
    });
    connect(m_processes.get(), &KSysGuard::Processes::endAddProcess, q, [this]() {
        endInsertRow();
    });
    connect(m_processes.get(), &KSysGuard::Processes::beginMoveProcess, q, [this](KSysGuard::Process *process, KSysGuard::Process *new_parent) {
        beginMoveProcess(process, new_parent);
    });
    connect(m_processes.get(), &KSysGuard::Processes::endMoveProcess, q, [this]() {
        endMoveProcess();
    });
    connect(m_processes.get(), &KSysGuard::Processes::beginRemoveProcess, q, [this](KSysGuard::Process *process) {
        beginRemoveRow(process);
    });
    connect(m_processes.get(), &KSysGuard::Processes::endRemoveProcess, q, [this]() {
        endRemoveRow();
    });

    const auto attributes = m_processes->attributes();
    m_availableAttributes.reserve(attributes.count());
    for (auto attr : attributes) {
        m_availableAttributes[attr->id()] = attr;
    }

    connect(m_timer, &QTimer::timeout, q, [this]() {
        update();
    });
    m_timer->setInterval(m_updateInterval);
    m_timer->start();
}

QVariant ProcessDataModel::data(const QModelIndex &index, int role) const
{
    if (!checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid)) {
        return QVariant();
    }

    const int attr = index.column();
    auto attribute = d->m_enabledAttributes[attr];
    switch (role) {
    case Qt::DisplayRole:
    case FormattedValue: {
        KSysGuard::Process *process = reinterpret_cast<KSysGuard::Process *>(index.internalPointer());
        const QVariant value = attribute->data(process);
        return KSysGuard::Formatter::formatValue(value, attribute->unit());
    }
    case Value: {
        KSysGuard::Process *process = reinterpret_cast<KSysGuard::Process *>(index.internalPointer());
        const QVariant value = attribute->data(process);
        return value;
    }
    case Attribute: {
        return attribute->id();
    }
    case Minimum: {
        return attribute->min();
    }
    case Maximum: {
        return attribute->max();
    }
    case ShortName: {
        if (!attribute->shortName().isEmpty()) {
            return attribute->shortName();
        }
        return attribute->name();
    }
    case Name: {
        return attribute->name();
    }
    case Unit: {
        return attribute->unit();
    }
    case UpdateInterval: {
        return d->m_updateInterval;
    }
    }
    return QVariant();
}

int ProcessDataModel::rowCount(const QModelIndex &parent) const
{
    if (d->m_flatList) {
        if (parent.isValid()) {
            return 0;
        } else {
            return d->m_processes->processCount();
        }
    }

    if (!parent.isValid()) {
        return d->m_rootProcess->children().count();
    } else if (parent.column() != 0) {
        return 0;
    }

    KSysGuard::Process *proc = reinterpret_cast<KSysGuard::Process *>(parent.internalPointer());
    Q_ASSERT(proc);
    return proc->children().count();
}

QModelIndex ProcessDataModel::parent(const QModelIndex &index) const
{
    Q_UNUSED(index)
    if (d->m_flatList || !index.isValid()) {
        return QModelIndex();
    }

    KSysGuard::Process *proc = reinterpret_cast<KSysGuard::Process *>(index.internalPointer());
    Q_ASSERT(proc);
    return d->getQModelIndex(proc->parent(), 0);
}

QStringList ProcessDataModel::availableAttributes() const
{
    return d->m_availableAttributes.keys();
}

QStringList ProcessDataModel::enabledAttributes() const
{
    QStringList rc;
    rc.reserve(d->m_enabledAttributes.size());
    for (auto attr : d->m_enabledAttributes) {
        rc << attr->id();
    }
    return rc;
}

void ProcessDataModel::setEnabledAttributes(const QStringList &enabledAttributes)
{
    beginResetModel();

    QList<ProcessAttribute *> unusedAttributes = d->m_enabledAttributes;
    d->m_enabledAttributes.clear();

    for (auto attributeId : enabledAttributes) {
        auto attribute = d->m_availableAttributes[attributeId];
        if (!attribute) {
            continue;
        }
        unusedAttributes.removeOne(attribute);
        d->m_enabledAttributes << attribute;
        int columnIndex = d->m_enabledAttributes.count() - 1;

        // reconnect as using the columnIndex in the lambda makes everything super fast
        disconnect(attribute, &KSysGuard::ProcessAttribute::dataChanged, this, nullptr);
        connect(attribute, &KSysGuard::ProcessAttribute::dataChanged, this, [this, columnIndex](KSysGuard::Process *process) {
            if (process->pid() != -1) {
                // Don't emit dataChanged here directly, instead add the changed
                // index to the list of pending changes so that we can deduplicate
                // and batch these later.
                d->m_pendingChanges.append(d->getQModelIndex(process, columnIndex));
            }
        });
    }

    for (auto *unusedAttribute : std::as_const(unusedAttributes)) {
        disconnect(unusedAttribute, &KSysGuard::ProcessAttribute::dataChanged, this, nullptr);
    }

    endResetModel();
    d->update();

    Q_EMIT enabledAttributesChanged();
}

bool ProcessDataModel::enabled() const
{
    return d->m_timer->isActive();
}

void ProcessDataModel::setEnabled(bool newEnabled)
{
    if (newEnabled == d->m_timer->isActive()) {
        return;
    }

    if (newEnabled) {
        d->m_timer->start();
    } else {
        d->m_timer->stop();
    }

    Q_EMIT enabledChanged();
}

bool ProcessDataModel::flatList() const
{
    return d->m_flatList;
}

void ProcessDataModel::setFlatList(bool flat)
{
    if (d->m_flatList == flat) {
        return;
    }
    beginResetModel();
    // NOTE: layoutAboutToBeChanged doesn't play well with TableView delegate recycling
    // Q_EMIT layoutAboutToBeChanged();

    d->m_flatList = flat;
    endResetModel();
    Q_EMIT flatListChanged();
}

QModelIndex ProcessDataModel::index(int row, int column, const QModelIndex &parent) const
{
    if (row < 0 || column < 0 || column >= columnCount()) {
        return QModelIndex();
    }

    // Flat List
    if (d->m_flatList) {
        if (parent.isValid()) {
            return QModelIndex();
        }

        if (d->m_processes->processCount() <= row) {
            return QModelIndex();
        }

        return createIndex(row, column, d->m_processes->getAllProcesses().at(row));
    }

    // Tree mode
    KSysGuard::Process *process;

    if (parent.isValid()) {
        process = reinterpret_cast<KSysGuard::Process *>(parent.internalPointer());
    } else {
        process = d->m_rootProcess;
    }

    if (row >= process->children().count()) {
        return QModelIndex();
    } else {
        return createIndex(row, column, process->children()[row]);
    }
}

void ProcessDataModel::Private::beginInsertRow(KSysGuard::Process *process)
{
    Q_ASSERT(process);

    // Flat List
    if (m_flatList) {
        const int row = m_processes->processCount();
        q->beginInsertRows(QModelIndex(), row, row);
        return;
    }

    // Tree mode
    const int row = process->parent()->children().count();
    q->beginInsertRows(getQModelIndex(process->parent(), 0), row, row);
}

void ProcessDataModel::Private::endInsertRow()
{
    q->endInsertRows();
}

void ProcessDataModel::Private::beginRemoveRow(KSysGuard::Process *process)
{
    Q_ASSERT(process);
    int row = m_flatList ? process->index() : process->parent()->children().indexOf(process);
    Q_ASSERT(row >= 0);
    auto parentIndex = m_flatList ? QModelIndex{} : getQModelIndex(process->parent(), 0);

    q->beginRemoveRows(parentIndex, row, row);

    auto removed = std::ranges::remove_if(m_pendingChanges, [row, parentIndex](const QPersistentModelIndex &index) {
        return index.parent() == parentIndex && index.row() == row;
    });
    m_pendingChanges.erase(removed.begin(), removed.end());
}

void ProcessDataModel::Private::endRemoveRow()
{
    q->endRemoveRows();
}

void ProcessDataModel::Private::beginMoveProcess(KSysGuard::Process *process, KSysGuard::Process *new_parent)
{
    if (m_flatList) {
        return; // We don't need to move processes when in simple mode
    }

    int current_row = process->parent()->children().indexOf(process);
    Q_ASSERT(current_row != -1);
    int new_row = new_parent->children().count();
    QModelIndex sourceParent = getQModelIndex(process->parent(), 0);
    QModelIndex destinationParent = getQModelIndex(new_parent, 0);
    q->beginMoveRows(sourceParent, current_row, current_row, destinationParent, new_row);
}

void ProcessDataModel::Private::endMoveProcess()
{
    if (m_flatList) {
        return; // We don't need to move processes when in simple mode
    }

    q->endMoveRows();
}

void ProcessDataModel::Private::update()
{
    Processes::UpdateFlags flags;
    for (auto attribute : std::as_const(m_enabledAttributes)) {
        flags |= attribute->requiredUpdateFlags();
    }

    m_processes->updateAllProcesses(m_updateInterval, flags);
    handleChangedProcesses();
}

QModelIndex ProcessDataModel::Private::getQModelIndex(KSysGuard::Process *process, int column) const
{
    if (!process || process->pid() == -1) {
        return QModelIndex(); // pid -1 is our fake process meaning the very root (never drawn).  To represent that, we return QModelIndex() which also means
                              // the top element
    }

    int row;

    if (m_flatList) {
        row = process->index();
    } else {
        row = process->parent()->children().indexOf(process);
    }

    Q_ASSERT(row != -1);
    return q->createIndex(row, column, process);
}

ProcessAttributeModel *ProcessDataModel::attributesModel()
{
    // lazy load
    if (!d->m_attributeModel) {
        d->m_attributeModel = new KSysGuard::ProcessAttributeModel(d->m_availableAttributes.values().toVector(), this);
    }
    return d->m_attributeModel;
}

int ProcessDataModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return d->m_enabledAttributes.count();
}

QHash<int, QByteArray> ProcessDataModel::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();

    const QMetaEnum e = QMetaEnum::fromType<AdditionalRoles>();

    for (int i = 0; i < e.keyCount(); ++i) {
        roles.insert(e.value(i), e.key(i));
    }

    return roles;
}

QVariant ProcessDataModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Vertical) {
        return QVariant();
    }

    if (section < 0 || section >= columnCount()) {
        return QVariant();
    }

    auto attribute = d->m_enabledAttributes[section];

    switch (role) {
    case Qt::DisplayRole:
    case ShortName: {
        if (!attribute->shortName().isEmpty()) {
            return attribute->shortName();
        }
        return attribute->name();
    }
    case Name:
        return attribute->name();
    case Value:
    case Attribute: {
        return attribute->id();
    }
    case Unit: {
        auto attribute = d->m_enabledAttributes[section];
        return attribute->unit();
    }
    case Minimum: {
        return attribute->min();
    }
    case Maximum: {
        return attribute->max();
    }
    case UpdateInterval: {
        return d->m_updateInterval;
    }
    default:
        break;
    }

    return QVariant();
}

void ProcessDataModel::Private::handleChangedProcesses()
{
    if (m_pendingChanges.isEmpty()) {
        return;
    }

    // Take a snapshot of the current state of pending changes.
    // This avoids any additional changes made to m_pendingChanges affecting the
    // operations below.
    QList<QPersistentModelIndex> pendingChanges;
    std::swap(m_pendingChanges, pendingChanges);

    // Sort all changes so consecutive rows are also consecutive elements in the list.
    std::ranges::stable_sort(pendingChanges, [](const QModelIndex &first, const QModelIndex &second) {
        if (first.parent() == second.parent()) {
            return first.row() < second.row();
        } else {
            return first.parent() < second.parent();
        }
    });

    auto first = pendingChanges.takeFirst();
    QModelIndex parentIndex = first.parent();
    int firstChangedRow = first.row();
    int lastChangedRow = first.row();
    int firstChangedColumn = first.column();
    int lastChangedColumn = first.column();

    for (const auto &index : std::as_const(pendingChanges)) {
        if (index.parent() != parentIndex || index.row() > lastChangedRow + 1) {
            auto firstIndex = q->index(firstChangedRow, firstChangedColumn, parentIndex);
            auto lastIndex = q->index(lastChangedRow, lastChangedColumn, parentIndex);
            if (firstIndex.isValid() && lastIndex.isValid()) {
                Q_EMIT q->dataChanged(firstIndex, lastIndex);
            }

            parentIndex = index.parent();
            firstChangedRow = lastChangedRow = index.row();
            firstChangedColumn = lastChangedColumn = index.column();
            continue;
        } else {
            lastChangedRow = index.row();
            firstChangedColumn = std::min(firstChangedColumn, index.column());
            lastChangedColumn = std::max(lastChangedColumn, index.column());
        }
    }

    Q_EMIT q->dataChanged(q->index(firstChangedRow, firstChangedColumn, parentIndex), q->index(lastChangedRow, lastChangedColumn, parentIndex), {Qt::DisplayRole, Value, FormattedValue});
}