File: aggregatedpropertymodel.cpp

package info (click to toggle)
gammaray 3.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,612 kB
  • sloc: cpp: 94,643; ansic: 2,227; sh: 336; python: 164; yacc: 90; lex: 82; xml: 61; makefile: 26
file content (542 lines) | stat: -rw-r--r-- 18,656 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
530
531
532
533
534
535
536
537
538
539
540
541
542
/*
  aggregatedpropertymodel.cpp

  This file is part of GammaRay, the Qt application inspection and manipulation tool.

  SPDX-FileCopyrightText: 2014 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Volker Krause <volker.krause@kdab.com>

  SPDX-License-Identifier: GPL-2.0-or-later

  Contact KDAB at <info@kdab.com> for commercial licensing options.
*/

#include "aggregatedpropertymodel.h"
#include "metaobjectrepository.h"
#include "objectinstance.h"
#include "probe.h"
#include "propertyaggregator.h"
#include "propertydata.h"
#include "propertyadaptorfactory.h"
#include "toolfactory.h"
#include "varianthandler.h"
#include "enumrepositoryserver.h"
#include "enumutil.h"
#include "util.h"

#include <common/objectid.h>
#include <common/propertymodel.h>

#include <QDebug>
#include <QMetaEnum>

using namespace GammaRay;


Q_DECLARE_METATYPE(const QObject *)

/*!
 * Checks if it is dangerous to unpack a QVariant because it stores an invalid pointer.
 * Returns true if the value is an invalid pointer to a QObject.
 * Returns false either if it is a valid pointer or not a QObject*.
 */
bool isInvalidPointer(const QVariant &value)
{
    if (!value.canConvert<QObject *>() && !value.canConvert<const QObject *>())
        return false;
    return !Probe::instance()->isValidObject(Util::uncheckedQObjectCast(value));
}


AggregatedPropertyModel::AggregatedPropertyModel(QObject *parent)
    : QAbstractItemModel(parent)
{
    qRegisterMetaType<GammaRay::PropertyAdaptor *>();
}

AggregatedPropertyModel::~AggregatedPropertyModel() = default;

void AggregatedPropertyModel::setObject(const ObjectInstance &oi)
{
    clear();

    if (!oi.isValid())
        return;
    auto adaptor = PropertyAdaptorFactory::create(oi, this);
    if (!adaptor)
        return;

    auto count = adaptor->count();
    if (count)
        beginInsertRows(QModelIndex(), 0, count - 1);

    m_rootAdaptor = adaptor;
    addPropertyAdaptor(m_rootAdaptor);

    if (count)
        endInsertRows();
}

void AggregatedPropertyModel::setReadOnly(bool readOnly)
{
    m_readOnly = readOnly;
}

void AggregatedPropertyModel::clear()
{
    if (!m_rootAdaptor)
        return;

    const auto count = m_parentChildrenMap.at(m_rootAdaptor).size();
    if (count)
        beginRemoveRows(QModelIndex(), 0, count - 1);

    m_parentChildrenMap.clear();
    delete m_rootAdaptor;
    m_rootAdaptor = nullptr;

    if (count)
        endRemoveRows();
}

QVariant AggregatedPropertyModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || !m_rootAdaptor)
        return QVariant();

    const auto adaptor = adaptorForIndex(index);
    if (!adaptor->object().isValid()) {
        // clang-format off
        QMetaObject::invokeMethod(const_cast<AggregatedPropertyModel *>(this), "objectInvalidated",
                                  Qt::QueuedConnection,
                                  Q_ARG(GammaRay::PropertyAdaptor*, adaptor));
        // clang-format on
        return QVariant();
    }

    const auto d = adaptor->propertyData(index.row());
    return data(adaptor, d, index.column(), role);
}

QMap<int, QVariant> AggregatedPropertyModel::itemData(const QModelIndex &index) const
{
    QMap<int, QVariant> res;
    if (!index.isValid() || !m_rootAdaptor)
        return res;

    const auto adaptor = adaptorForIndex(index);
    if (!adaptor->object().isValid()) {
        // clang-format off
        QMetaObject::invokeMethod(const_cast<AggregatedPropertyModel *>(this), "objectInvalidated",
                                  Qt::QueuedConnection,
                                  Q_ARG(GammaRay::PropertyAdaptor*, adaptor));
        // clang-format on
        return res;
    }
    const auto d = adaptor->propertyData(index.row());

    res.insert(Qt::DisplayRole, data(adaptor, d, index.column(), Qt::DisplayRole));
    res.insert(PropertyModel::ActionRole, data(adaptor, d, index.column(), PropertyModel::ActionRole));
    res.insert(PropertyModel::ObjectIdRole,
               data(adaptor, d, index.column(), PropertyModel::ObjectIdRole));
    if (index.column() == 0) {
        auto v = data(adaptor, d, index.column(), PropertyModel::PropertyFlagsRole);
        if (!v.isNull())
            res.insert(PropertyModel::PropertyFlagsRole, v);
        v = data(adaptor, d, index.column(), PropertyModel::PropertyRevisionRole);
        if (!v.isNull())
            res.insert(PropertyModel::PropertyRevisionRole, v);
        v = data(adaptor, d, index.column(), PropertyModel::NotifySignalRole);
        if (!v.isNull())
            res.insert(PropertyModel::NotifySignalRole, v);
    } else if (index.column() == 1) {
        res.insert(Qt::EditRole, data(adaptor, d, index.column(), Qt::EditRole));
        res.insert(Qt::DecorationRole, data(adaptor, d, index.column(), Qt::DecorationRole));
        if (d.value().typeId() == QMetaType::Bool)
            res.insert(Qt::CheckStateRole, data(adaptor, d, index.column(), Qt::CheckStateRole));
    }
    return res;
}

QVariant AggregatedPropertyModel::data(PropertyAdaptor *adaptor, const PropertyData &d, int column,
                                       int role)
{
    switch (role) {
    case Qt::DisplayRole:
        switch (column) {
        case 0:
            return d.name();
        case 1: {
            // QMetaProperty::read sets QVariant::typeName to int for enums,
            // so we need to handle that separately here
            const QString enumStr = EnumUtil::enumToString(d.value(), d.typeName().toLatin1(), adaptor->object().metaObject());
            if (!enumStr.isEmpty())
                return enumStr;
            if (d.value().typeId() == QMetaType::Bool && (d.accessFlags() & PropertyData::Writable))
                return QVariant();
            if (isInvalidPointer(d.value()) && Util::uncheckedQObjectCast(d.value()) != nullptr)
                return "[invalid]";
            return VariantHandler::displayString(d.value());
        }
        case 2:
            return d.typeName();
        case 3:
            return d.className();
        }
        break;
    case Qt::EditRole:
        if (column == 1) {
            const auto me = EnumUtil::metaEnum(d.value(), d.typeName().toLatin1(), adaptor->object().metaObject());
            if (me.isValid()) {
                const auto num = EnumUtil::enumToInt(d.value(), me);
                return QVariant::fromValue(EnumRepositoryServer::valueFromMetaEnum(num, me));
            }
            return VariantHandler::serializableVariant(d.value());
        }
        break;
    case Qt::DecorationRole:
        if (column == 1)
            return VariantHandler::decoration(d.value());
        break;
    case Qt::CheckStateRole:
        if (column == 1 && d.value().typeId() == QMetaType::Bool && (d.accessFlags() & PropertyData::Writable))
            return d.value().toBool() ? Qt::Checked : Qt::Unchecked;
        break;
    case PropertyModel::ActionRole: {
        int actions = PropertyModel::NoAction;
        if (d.accessFlags() & PropertyData::Resettable)
            actions |= PropertyModel::Reset;
        if (d.accessFlags() & PropertyData::Deletable)
            actions |= PropertyModel::Delete;
        if ((MetaObjectRepository::instance()->metaObject(d.typeName())
             && *reinterpret_cast<void *const *>(d.value().data()))
            || d.value().value<QObject *>())
            actions |= PropertyModel::NavigateTo;
        return actions;
    }
    case PropertyModel::ObjectIdRole:
        if (d.value().canConvert<QObject *>()) {
            if (isInvalidPointer(d.value()))
                return QVariant();
            return QVariant::fromValue(ObjectId(d.value().value<QObject *>()));
        } else if (d.value().isValid()) {
            const auto &v = d.value();
            return QVariant::fromValue(ObjectId(*reinterpret_cast<void *const *>(v.data()),
                                                v.typeName()));
        }
        return QVariant();
    case PropertyModel::PropertyFlagsRole:
        if (column == 0 && d.propertyFlags() != PropertyModel::None)
            return QVariant::fromValue(d.propertyFlags());
        return QVariant();
    case PropertyModel::PropertyRevisionRole:
        if (column == 0 && d.revision() >= 0)
            return d.revision();
        return QVariant();
    case PropertyModel::NotifySignalRole:
        if (column == 0 && !d.notifySignal().isEmpty())
            return d.notifySignal();
        return QVariant();
    }
    return QVariant();
}

bool AggregatedPropertyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || !m_rootAdaptor)
        return false;

    const auto adaptor = adaptorForIndex(index);
    switch (role) {
    case Qt::EditRole: {
        QPointer<GammaRay::PropertyAdaptor> guard(adaptor);
        if (value.userType() == qMetaTypeId<EnumValue>()) {
            const auto d = adaptor->propertyData(index.row());
            if (d.value().typeId() == QMetaType::Int) {
                adaptor->writeProperty(index.row(), value.value<EnumValue>().value());
            } else {
                auto v = d.value();
                *(static_cast<int *>(v.data())) = value.value<EnumValue>().value();
                adaptor->writeProperty(index.row(), v);
            }
        } else {
            adaptor->writeProperty(index.row(), value);
        }
        if (guard) {
            propagateWrite(adaptor);
        }
        return true;
    }
    case Qt::CheckStateRole:
        adaptor->writeProperty(index.row(), value.toInt() == Qt::Checked);
        propagateWrite(adaptor);
        return true;
    case PropertyModel::ResetActionRole:
        adaptor->resetProperty(index.row());
        return true;
    }

    return false;
}

int AggregatedPropertyModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 4;
}

int AggregatedPropertyModel::rowCount(const QModelIndex &parent) const
{
    if (!m_rootAdaptor || parent.column() > 0)
        return 0;
    if (!parent.isValid())
        return m_parentChildrenMap.at(m_rootAdaptor).size();

    auto adaptor = adaptorForIndex(parent);
    auto &siblings = m_parentChildrenMap[adaptor];
    if (!m_inhibitAdaptorCreation && !siblings.at(parent.row())) {
        // TODO: remember we tried any of this
        auto pd = adaptor->propertyData(parent.row());
        if (!isInvalidPointer(pd.value()) && !hasLoop(adaptor, pd.value())) {
            auto a = PropertyAdaptorFactory::create(pd.value(), adaptor);
            siblings[parent.row()] = a;
            addPropertyAdaptor(a);
        }
    }

    if (siblings.isEmpty())
        return 0;

    auto childAdaptor = siblings.at(parent.row());
    if (!childAdaptor)
        return 0;
    return m_parentChildrenMap.at(childAdaptor).size(); // childAdaptor->count() might already be updated in insert/removeRows
}

Qt::ItemFlags AggregatedPropertyModel::flags(const QModelIndex &index) const
{
    const auto baseFlags = QAbstractItemModel::flags(index);
    if (!index.isValid() || index.column() != 1 || m_readOnly)
        return baseFlags;

    auto adaptor = adaptorForIndex(index);
    auto data = adaptor->propertyData(index.row());
    const auto editable = (data.accessFlags() & PropertyData::Writable) && isParentEditable(adaptor);
    const auto booleanEditable = editable && data.value().typeId() == QMetaType::Bool;
    if (booleanEditable)
        return baseFlags | Qt::ItemIsUserCheckable;
    return editable ? (baseFlags | Qt::ItemIsEditable) : baseFlags;
}

QModelIndex AggregatedPropertyModel::parent(const QModelIndex &child) const
{
    auto childAdaptor = adaptorForIndex(child);
    if (childAdaptor == m_rootAdaptor)
        return {};

    auto parentAdaptor = childAdaptor->parentAdaptor();
    return createIndex(m_parentChildrenMap.at(parentAdaptor).indexOf(childAdaptor), 0, parentAdaptor);
}

QModelIndex AggregatedPropertyModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!hasIndex(row, column, parent) || !m_rootAdaptor)
        return {};

    if (!parent.isValid())
        return createIndex(row, column, m_rootAdaptor);
    auto adaptor = adaptorForIndex(parent);
    return createIndex(row, column, m_parentChildrenMap.at(adaptor).at(parent.row()));
}

PropertyAdaptor *AggregatedPropertyModel::adaptorForIndex(const QModelIndex &index) const
{
    if (!index.isValid())
        return m_rootAdaptor;
    return static_cast<PropertyAdaptor *>(index.internalPointer());
}

void AggregatedPropertyModel::addPropertyAdaptor(PropertyAdaptor *adaptor) const
{
    if (!adaptor)
        return;

    m_parentChildrenMap.emplace(adaptor, QVector<PropertyAdaptor *>(adaptor->count()));
    connect(adaptor, &PropertyAdaptor::propertyChanged, this, &AggregatedPropertyModel::propertyChanged);
    connect(adaptor, &PropertyAdaptor::propertyAdded, this, &AggregatedPropertyModel::propertyAdded);
    connect(adaptor, &PropertyAdaptor::propertyRemoved, this, &AggregatedPropertyModel::propertyRemoved);
}

void AggregatedPropertyModel::propertyChanged(int first, int last)
{
    auto adaptor = qobject_cast<PropertyAdaptor *>(sender());
    Q_ASSERT(adaptor);
    Q_ASSERT(m_parentChildrenMap.find(adaptor) != m_parentChildrenMap.cend());
    Q_ASSERT(first <= last);
    Q_ASSERT(first >= 0);
    Q_ASSERT(last < adaptor->count());

    emit dataChanged(createIndex(first, 0, adaptor), createIndex(last, columnCount() - 1, adaptor));
    for (int i = first; i <= last; ++i)
        reloadSubTree(adaptor, i);
}

void AggregatedPropertyModel::propertyAdded(int first, int last)
{
    auto adaptor = qobject_cast<PropertyAdaptor *>(sender());
    Q_ASSERT(adaptor);
    Q_ASSERT(m_parentChildrenMap.find(adaptor) != m_parentChildrenMap.cend());
    Q_ASSERT(first <= last);
    Q_ASSERT(first >= 0);
    Q_ASSERT(last < adaptor->count());

    auto idx = createIndex(first, 0, adaptor);
    beginInsertRows(idx.parent(), first, last);
    auto &children = m_parentChildrenMap[adaptor];
    if (first >= children.size())
        children.resize(last + 1);
    else
        children.insert(first, last - first + 1, nullptr);
    endInsertRows();
}

void AggregatedPropertyModel::propertyRemoved(int first, int last)
{
    auto adaptor = qobject_cast<PropertyAdaptor *>(sender());

    Q_ASSERT(adaptor);
    Q_ASSERT(m_parentChildrenMap.find(adaptor) != m_parentChildrenMap.cend());
    Q_ASSERT(first <= last);
    Q_ASSERT(first >= 0);
    Q_ASSERT(last < adaptor->count());

    auto idx = createIndex(first, 0, adaptor);
    beginRemoveRows(idx.parent(), first, last);
    auto &children = m_parentChildrenMap[adaptor];
    children.remove(first, last - first + 1);
    endRemoveRows();
}

void AggregatedPropertyModel::objectInvalidated()
{
    auto adaptor = qobject_cast<PropertyAdaptor *>(sender());
    objectInvalidated(adaptor);
}

void AggregatedPropertyModel::objectInvalidated(PropertyAdaptor *adaptor)
{
    Q_ASSERT(adaptor);
    if (m_parentChildrenMap.find(adaptor) == m_parentChildrenMap.end()) // already handled
        return;

    if (adaptor == m_rootAdaptor) {
        clear();
        return;
    }

    auto parentAdaptor = adaptor->parentAdaptor();
    Q_ASSERT(parentAdaptor);
    Q_ASSERT(m_parentChildrenMap.find(parentAdaptor) != m_parentChildrenMap.cend());
    reloadSubTree(parentAdaptor, m_parentChildrenMap.at(parentAdaptor).indexOf(adaptor));
}

bool AggregatedPropertyModel::hasLoop(PropertyAdaptor *adaptor, const QVariant &v)
{
    const ObjectInstance newOi(v);
    if (newOi.type() != ObjectInstance::QtObject && newOi.type() != ObjectInstance::Object)
        return false;
    if (!newOi.object())
        return false;

    while (adaptor) {
        if (adaptor->object() == newOi)
            return true;
        adaptor = adaptor->parentAdaptor();
    }

    return false;
}

void AggregatedPropertyModel::reloadSubTree(PropertyAdaptor *parentAdaptor, int index)
{
    Q_ASSERT(parentAdaptor);
    Q_ASSERT(m_parentChildrenMap.find(parentAdaptor) != m_parentChildrenMap.cend());
    Q_ASSERT(index >= 0);
    Q_ASSERT(index < m_parentChildrenMap.at(parentAdaptor).size());

    // prevent rowCount calls as a result of the change notification to re-create
    // the adaptor
    m_inhibitAdaptorCreation = true;

    // remove the old sub-tree, if present
    auto oldAdaptor = m_parentChildrenMap.at(parentAdaptor).at(index);
    if (oldAdaptor) {
        auto oldRowCount = m_parentChildrenMap.at(oldAdaptor).size();
        if (oldRowCount > 0)
            beginRemoveRows(createIndex(index, 0, parentAdaptor), 0, oldRowCount - 1);
        m_parentChildrenMap[parentAdaptor][index] = nullptr;

        m_parentChildrenMap.erase(oldAdaptor);
        delete oldAdaptor;
        if (oldRowCount)
            endRemoveRows();
    }

    // re-add the sub-tree
    // TODO consolidate with code in rowCount()
    auto pd = parentAdaptor->propertyData(index);

    if (isInvalidPointer(pd.value()) || hasLoop(parentAdaptor, pd.value())) {
        m_inhibitAdaptorCreation = false;
        return;
    }
    auto newAdaptor = PropertyAdaptorFactory::create(pd.value(), parentAdaptor);
    if (!newAdaptor) {
        m_inhibitAdaptorCreation = false;
        return;
    }
    auto newRowCount = newAdaptor->count();
    if (newRowCount > 0)
        beginInsertRows(createIndex(index, 0, parentAdaptor), 0, newRowCount - 1);
    m_parentChildrenMap[parentAdaptor][index] = newAdaptor;
    addPropertyAdaptor(newAdaptor);
    if (newRowCount > 0)
        endInsertRows();

    m_inhibitAdaptorCreation = false;
}

bool AggregatedPropertyModel::isParentEditable(PropertyAdaptor *adaptor) const
{
    const auto parentAdaptor = adaptor->parentAdaptor();
    if (!parentAdaptor)
        return true;

    // we need all value types along the way to be writable
    if (adaptor->object().isValueType()) {
        const auto row = m_parentChildrenMap.at(parentAdaptor).indexOf(adaptor);
        Q_ASSERT(row >= 0);

        const auto pd = parentAdaptor->propertyData(row);
        if ((pd.accessFlags() & PropertyData::Writable) == 0)
            return false;
    }

    return isParentEditable(parentAdaptor);
}

void AggregatedPropertyModel::propagateWrite(GammaRay::PropertyAdaptor *adaptor)
{
    const auto parentAdaptor = adaptor->parentAdaptor();
    if (!parentAdaptor)
        return;

    if (adaptor->object().isValueType()) {
        const auto row = m_parentChildrenMap.at(parentAdaptor).indexOf(adaptor);
        Q_ASSERT(row >= 0);

        parentAdaptor->writeProperty(row, adaptor->object().variant());
    }

    propagateWrite(parentAdaptor);
}