summaryrefslogtreecommitdiffstats
path: root/src/shared-main-lib/monitormodel.cpp
blob: d9ca060d53e2851c0cf47336dfc56e29d5b558e7 (plain)
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
// Copyright (C) 2021 The Qt Company Ltd.
// Copyright (C) 2019 Luxoft Sweden AB
// Copyright (C) 2018 Pelagicore AG
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "monitormodel.h"
#include "logging.h"

#include <QMetaProperty>
#include <qqmlinfo.h>

#include <QDebug>
#include <QQmlProperty>
#include <QJSValue>
#include <QQmlEngine>

using namespace Qt::StringLiterals;


/*!
    \qmltype MonitorModel
    \inqmlmodule QtApplicationManager
    \ingroup common-instantiatable
    \brief A model that can fetch data from various sources and keep a history of their values.

    MonitorModel can fetch data from various sources at regular intervals and keep a history of
    their values. Its main use is having it as a model to plot historical data in a graph for
    monitoring purposes, such as a CPU usage graph.

    The snippet below shows how to use it for plotting a system's CPU load in a simple bar graph:

    \qml
    import QtQuick
    import QtApplicationManager

    ListView {
        id: listView
        width: 400
        height: 100
        orientation: ListView.Horizontal
        spacing: (width / model.count) * 0.2
        clip: true
        interactive: false

        model: MonitorModel {
            id: monitorModel
            running: listView.visible
            CpuStatus {}
        }

        delegate: Rectangle {
            width: (listView.width / monitorModel.count) * 0.8
            height: model.cpuLoad * listView.height
            y: listView.height - height
            color: "blue"
        }
    }
    \endqml

    To add a data source to MonitorModel just declare it inside the model, as done in the example
    above with the CpuStatus component. Alternatively (such as from imperative javscript code) you
    can add data sources by assigning them to MonitorModel's dataSources property.

    A data source can be any QtObject with the following characteristics:
    \list
    \li A \c roleNames property: it's a list of strings naming the roles that this data source
        provides. Those role names will be available on each row created by MonitorModel.
    \li Properties matching the names provided in the \c roleNames property: MonitorModel will
        query their values when building each new model row.
    \li An \c update() function: MonitorModel will call it before creating each new model row, so
        that the data source can update the values of its properties.
    \endlist

    The following snippet shows MonitorModel using a custom data source written in QML:

    \qml
    MonitorModel {
        running: true
        QtObject {
            property var roleNames: ["foo", "bar"]

            function update() {
                // foo will have ever increasing values
                foo += 1;

                // bar will keep oscillating between 0 and 10
                if (up) {
                    bar += 1;
                    if (bar == 10)
                        up = false;
                } else {
                    bar -= 1;
                    if (bar == 0)
                        up = true;
                }
            }

            property int foo: 0
            property int bar: 10
            property bool up: false
        }
    }
    \endqml

    Thus, in the MonitorModel above, every row will have two roles: \c foo and \c bar. If plotted,
    you would see an ever incresing \c foo and an oscillating \c bar.

    QtApplicationManager comes with a number of components that are readily usable as data sources,
    namely:
    \list
    \li CpuStatus
    \li FrameTimer
    \li FrameContentTracker
    \li GpuStatus
    \li IoStatus
    \li MemoryStatus
    \li ProcessStatus
    \endlist

    While \l running is \c true, MonitorModel will probe its data sources every \l interval
    milliseconds, creating a new row every time up to \l maximumCount. Once that value is reached,
    the oldest row (the first one) is discarded whenever a new row comes in, so that \l count
    doesn't exceed \l maximumCount. New rows are always appended to the model and are
    ordered chronologically from oldest (index \c 0) to newest (index \c {count-1}).
*/

QT_USE_NAMESPACE_AM

MonitorModel::MonitorModel(QObject *parent)
    : QAbstractListModel(parent)
{
    m_timer.setInterval(1000);
    connect(&m_timer, &QTimer::timeout, this, &MonitorModel::readDataSourcesAndAddRow);
}

MonitorModel::~MonitorModel()
{
    // avoid calling clear, as this would emit signals
    qDeleteAll(m_rows);
    qDeleteAll(m_dataSources);
}

/*!
    \qmlproperty list<object> MonitorModel::dataSources
    \qmldefault

    List of data sources for the MonitorModel to use. A data source can be any QtObject containing
    at least a \c roleNames property and an \c update() function. For more information, see
    detailed description above.
*/
QQmlListProperty<QObject> MonitorModel::dataSources()
{
    return QQmlListProperty<QObject>(this, nullptr, &MonitorModel::dataSources_append,
            &MonitorModel::dataSources_count,
            &MonitorModel::dataSources_at,
            &MonitorModel::dataSources_clear);
}

void MonitorModel::dataSources_append(QQmlListProperty<QObject> *property, QObject *dataSource)
{
    auto *that = static_cast<MonitorModel*>(property->object);
    that->appendDataSource(dataSource);
}

qsizetype MonitorModel::dataSources_count(QQmlListProperty<QObject> *property)
{
    auto *that = static_cast<MonitorModel*>(property->object);
    return that->m_dataSources.count();
}

QObject *MonitorModel::dataSources_at(QQmlListProperty<QObject> *property, qsizetype index)
{
    auto *that = static_cast<MonitorModel*>(property->object);
    return that && that->m_dataSources.count() > index && index >= 0 ? that->m_dataSources.at(index)->obj : nullptr;
}

void MonitorModel::dataSources_clear(QQmlListProperty<QObject> *property)
{
    auto *that = static_cast<MonitorModel*>(property->object);
    that->clearDataSources();
    emit that->dataSourcesChanged();
}

void MonitorModel::clearDataSources()
{
    qDeleteAll(m_dataSources);
    m_dataSources.clear();
    m_roleNamesList.clear();
    m_roleNameToIndex.clear();

    clear();
}

void MonitorModel::appendDataSource(QObject *dataSourceObj)
{
    DataSource *dataSource = new DataSource;
    dataSource->obj = dataSourceObj;
    m_dataSources.append(dataSource);

    if (!extractRoleNamesFromJsArray(dataSource)
            && !extractRoleNamesFromStringList(dataSource))
        qmlWarning(this) << "Could not find a roleNames property containing an array or list of strings.";
}

bool MonitorModel::extractRoleNamesFromJsArray(DataSource *dataSource)
{
    QQmlEngine *engine = qmlEngine(this);

    QJSValue jsDataSource = engine->toScriptValue<QObject*>(dataSource->obj);

    if (!jsDataSource.hasProperty(u"roleNames"_s))
        return false;

    QJSValue jsRoleNames = jsDataSource.property(u"roleNames"_s);
    if (!jsRoleNames.isArray())
        return false;

    int length = jsRoleNames.property(u"length"_s).toInt();
    for (int i = 0; i < length; i++)
        addRoleName(jsRoleNames.property(quint32(i)).toString().toLatin1(), dataSource);

    return true;
}

bool MonitorModel::extractRoleNamesFromStringList(DataSource *dataSource)
{
    const QMetaObject *metaObj = dataSource->obj->metaObject();

    int index = metaObj->indexOfProperty("roleNames");
    if (index == -1)
        return false;

    QMetaProperty property = metaObj->property(index);

    QVariant variant = property.read(dataSource->obj);

    if (!variant.canConvert<QStringList>())
        return false;

    QList<QString> roleNames = variant.toStringList();
    for (int i = 0; i < roleNames.count(); i++)
        addRoleName(roleNames[i].toLatin1(), dataSource);

    return true;
}

void MonitorModel::addRoleName(const QByteArray &roleName, DataSource *dataSource)
{
    dataSource->roleNames.append(roleName);

    if (m_roleNamesList.contains(roleName))
        qmlWarning(this) << "roleName" << roleName << "already exists. Model won't function correctly.";

    m_roleNamesList.append(dataSource->roleNames.constLast());
    m_roleNameToIndex[dataSource->roleNames.constLast()] = int(m_roleNamesList.count()) - 1;
}

/*!
    \qmlproperty int MonitorModel::count
    \readonly

    Number of rows in the model. It ranges from zero up to \l maximumCount.

    \sa maximumCount, clear
*/
int MonitorModel::count() const
{
    return int(m_rows.count());
}

int MonitorModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        // this model is not a tree
        return 0;
    }

    return count();
}

QVariant MonitorModel::data(const QModelIndex &index, int role) const
{
    if (index.parent().isValid() || !index.isValid() || index.row() < 0 || index.row() >= m_rows.count())
        return QVariant();

    return m_rows.at(index.row())->dataFromRoleIndex.value(role);
}

QHash<int, QByteArray> MonitorModel::roleNames() const
{
    QHash<int, QByteArray> result;
    for (int i = 0; i < m_roleNamesList.count(); i++) {
        result[i] = m_roleNamesList.at(i);
    }

    return result;
}

/*!
    \qmlproperty bool MonitorModel::running

    While \c true, MonitorModel will keep probing its data sources and adding new rows every
    \l interval milliseconds. The default value is \c false.

    Normally you have this property set to \c true only while the data is being displayed.

    \sa interval
*/
bool MonitorModel::running() const
{
    return m_timer.isActive();
}

void MonitorModel::setRunning(bool value)
{
    if (value && !m_timer.isActive()) {
        m_timer.start();
        emit runningChanged();
    } else if (!value && m_timer.isActive()) {
        m_timer.stop();
        emit runningChanged();
    }
}

/*!
    \qmlproperty int MonitorModel::interval

    Interval in milliseconds between model updates (while \l running). The default value is \c 1000.

    \sa running
*/
int MonitorModel::interval() const
{
    return m_timer.interval();
}

void MonitorModel::setInterval(int value)
{
    if (value != m_timer.interval()) {
        m_timer.setInterval(value);
        emit intervalChanged();
    }
}

void MonitorModel::readDataSourcesAndAddRow()
{
    if (m_dataSources.count() == 0)
        return;

    int cnt = count();
    if (cnt < m_maximumCount) {
        // create a new row
        DataRow *dataRow = new DataRow;
        fillDataRow(dataRow);
        beginInsertRows(QModelIndex(), cnt, cnt);
        m_rows.append(dataRow);
        endInsertRows();
        emit countChanged();
    } else {
        // this should really be begin/endMoveRows, but something is broken in QML's ListView:
        // we get a constant 7 fps render load with spikes into 60 fps in this case.

        emit layoutAboutToBeChanged({ }, VerticalSortHint);
        const QModelIndexList before = persistentIndexList();

        std::rotate(m_rows.begin(), m_rows.begin() + 1, m_rows.end());

        QModelIndexList after;
        after.reserve(before.size());
        for (const QModelIndex &idx : before)
            after.append(index((idx.row() > 0) ? (idx.row() - 1) : (cnt - 1), idx.column()));
        changePersistentIndexList(before, after);
        emit layoutChanged({ }, VerticalSortHint);

        fillDataRow(m_rows.last());
        QModelIndex modelIndex = index(cnt - 1, 0);
        emit dataChanged(modelIndex, modelIndex);
    }
}

void MonitorModel::fillDataRow(DataRow *dataRow)
{
    dataRow->dataFromRoleIndex.clear();
    for (int i = 0; i < m_dataSources.count(); ++i)
        readDataSource(m_dataSources.at(i), dataRow);
}

void MonitorModel::readDataSource(DataSource *dataSource, DataRow *dataRow)
{
    QMetaObject::invokeMethod(dataSource->obj, "update", Qt::DirectConnection);

    for (const auto &roleName : std::as_const(dataSource->roleNames)) {
        Q_ASSERT(m_roleNameToIndex.contains(roleName));
        int roleIndex = m_roleNameToIndex.value(roleName);
        QVariant variant = QQmlProperty::read(dataSource->obj, QString::fromLatin1(roleName));
        dataRow->dataFromRoleIndex[roleIndex] = variant;
    }
}

/*!
    \qmlproperty int MonitorModel::maximumCount

    The maximum number of rows that the MonitorModel will keep. After this limit is reached the
    oldest rows start to get discarded to make room for the new ones coming in.

    \sa count, clear
*/
int MonitorModel::maximumCount() const
{
    return m_maximumCount;
}

void MonitorModel::setMaximumCount(int value)
{
    if (m_maximumCount == value)
        return;

    m_maximumCount = value;
    trimHistory();
    emit maximumCountChanged();
}

void MonitorModel::trimHistory()
{
    int excess = count() - m_maximumCount;
    if (excess <= 0)
        return;

    beginRemoveRows(QModelIndex(), /* first */ 0, /* last */ excess - 1);

    while (count() > m_maximumCount)
        delete m_rows.takeFirst();

    endRemoveRows();
}

/*!
    \qmlmethod MonitorModel::clear

    Empties the model, removing all exising rows.

    \sa count
*/
void MonitorModel::clear()
{
    beginResetModel();
    qDeleteAll(m_rows);
    m_rows.clear();
    endResetModel();

    emit countChanged();
}

/*!
    \qmlmethod object MonitorModel::get(int index)

    Returns the model data for the reading point identified by \a index as a JavaScript object.
    The \a index must be in the range [0, \l count); returns an empty object otherwise.
*/
QVariantMap MonitorModel::get(int row) const
{
    if (row < 0 || row >= count()) {
        qCWarning(LogSystem) << "MonitorModel::get invalid row:" << row;
        return QVariantMap();
    }

    QVariantMap map;
    QHash<int, QByteArray> roles = roleNames();
    for (auto it = roles.cbegin(); it != roles.cend(); ++it)
        map.insert(QString::fromLatin1(it.value()), data(index(row), it.key()));

    return map;
}

#include "moc_monitormodel.cpp"