File: multilevellistview.cpp

package info (click to toggle)
kdevelop 4%3A22.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 70,096 kB
  • sloc: cpp: 284,635; javascript: 3,558; python: 3,422; sh: 1,319; ansic: 685; xml: 331; php: 95; lisp: 66; makefile: 39; sed: 12
file content (479 lines) | stat: -rw-r--r-- 13,567 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
/*
    SPDX-FileCopyrightText: 2012 Miha Čančula <miha@noughmad.eu>

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

#include "multilevellistview.h"

#include <QHBoxLayout>
#include <QTreeView>
#include <QSortFilterProxyModel>

#include <KSelectionProxyModel>

/**
 * Interface to set the label of a model.
 */
class LabeledProxy
{
public:
    virtual ~LabeledProxy()
    {
    }
    void setLabel(const QString& label)
    {
        m_label = label;
    }

    QVariant header(QAbstractItemModel* model, int section, Qt::Orientation orientation, int role) const
    {
        if (model && section == 0 && orientation == Qt::Horizontal && role == Qt::DisplayRole) {
            return m_label;
        } else {
            return QVariant();
        }
    }

protected:
    QString m_label;
};

/**
 * The left-most view's model which only contains the root nodes of the source model.
 */
class RootProxyModel : public QSortFilterProxyModel
    , public LabeledProxy
{
    Q_OBJECT

public:
    explicit RootProxyModel(QObject* parent = nullptr)
        : QSortFilterProxyModel(parent)
    {
    }
    bool filterAcceptsRow(int /*source_row*/, const QModelIndex& source_parent) const override
    {
        return !source_parent.isValid();
    }
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override
    {
        return header(sourceModel(), section, orientation, role);
    }
};

/**
 * A class that automatically updates its contents based on the selection in another view.
 */
class SubTreeProxyModel : public KSelectionProxyModel
    , public LabeledProxy
{
    Q_OBJECT

public:
    explicit SubTreeProxyModel(QItemSelectionModel* selectionModel, QObject* parent = nullptr)
        : KSelectionProxyModel(selectionModel, parent)
    {}
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override
    {
        return header(sourceModel(), section, orientation, role);
    }
    Qt::ItemFlags flags(const QModelIndex& index) const override
    {
        Qt::ItemFlags ret = KSelectionProxyModel::flags(index);
        if (filterBehavior() == KSelectionProxyModel::SubTreesWithoutRoots && hasChildren(index)) {
            // we want to select child items
            ret &= ~Qt::ItemIsSelectable;
        }
        return ret;
    }
};

using namespace KDevelop;

class KDevelop::MultiLevelListViewPrivate
{
public:
    explicit MultiLevelListViewPrivate(MultiLevelListView* view);
    ~MultiLevelListViewPrivate();

    void viewSelectionChanged(const QModelIndex& current, const QModelIndex& previous);
    void lastViewsContentsChanged();
    void ensureViewSelected(QTreeView* view);

    /**
     * @param index index in any of our proxy models
     * @return an index in the source model
     */
    QModelIndex mapToSource(QModelIndex index) const;
    /**
     * @param index an index in the source model
     * @return an index in the view's model at level @p level
     */
    QModelIndex mapFromSource(QModelIndex index, int level) const;

    MultiLevelListView* view;

    int levels;
    QList<QTreeView*> views;
    QList<LabeledProxy*> proxies;
    QList<QVBoxLayout*> layouts;

    QAbstractItemModel* model;
};

MultiLevelListViewPrivate::MultiLevelListViewPrivate(MultiLevelListView* view_)
    : view(view_)
    , levels(0)
    , model(nullptr)
{
}

MultiLevelListViewPrivate::~MultiLevelListViewPrivate()
{
}

void MultiLevelListViewPrivate::viewSelectionChanged(const QModelIndex& current,
                                                     const QModelIndex& previous)
{
    if (!current.isValid()) {
        // ignore, as we should always have some kind of selection
        return;
    }

    // figure out which proxy this signal belongs to
    auto* proxy = qobject_cast<QAbstractProxyModel*>(
        const_cast<QAbstractItemModel*>(current.model()));
    Q_ASSERT(proxy);

    // what level is this proxy in
    int level = -1;
    for (int i = 0; i < levels; ++i) {
        if (views.at(i)->model() == proxy) {
            level = i;
            break;
        }
    }

    Q_ASSERT(level >= 0 && level < levels);

    if (level + 1 == levels) {
        // right-most view
        if (proxy->hasIndex(0, 0, current)) {
            // select the first leaf node for this view
            QModelIndex idx = current;
            QModelIndex child = proxy->index(0, 0, idx);
            while (child.isValid()) {
                idx = child;
                child = proxy->index(0, 0, idx);
            }
            views.last()->setCurrentIndex(idx);
            return;
        }
        // signal that our actual selection has changed
        emit view->currentIndexChanged(mapToSource(current), mapToSource(previous));
    } else {
        // some leftish view
        // ensure the next view's first item is selected
        QTreeView* treeView = views.at(level + 1);

        // we need to delay the call, because at this point the child view
        // will still have its old data which is going to be invalidated
        // right after this method exits
        // be we must not set the index to 0,0 here directly, since e.g.
        // MultiLevelListView::setCurrentIndex might have been used, which
        // sets a proper index already.
        QMetaObject::invokeMethod(view, "ensureViewSelected", Qt::QueuedConnection,
                                  Q_ARG(QTreeView*, treeView));
    }
}

void MultiLevelListViewPrivate::lastViewsContentsChanged()
{
    views.last()->expandAll();
}

void MultiLevelListViewPrivate::ensureViewSelected(QTreeView* view)
{
    if (!view->currentIndex().isValid()) {
        view->setCurrentIndex(view->model()->index(0, 0));
    }
}

QModelIndex MultiLevelListViewPrivate::mapToSource(QModelIndex index) const
{
    if (!index.isValid()) {
        return index;
    }

    while (index.model() != model) {
        auto* proxy = qobject_cast<QAbstractProxyModel*>(
            const_cast<QAbstractItemModel*>(index.model()));
        Q_ASSERT(proxy);
        index = proxy->mapToSource(index);
        Q_ASSERT(index.isValid());
    }
    return index;
}

QModelIndex MultiLevelListViewPrivate::mapFromSource(QModelIndex index, int level) const
{
    if (!index.isValid()) {
        return index;
    }

    Q_ASSERT(index.model() == model);

    auto* proxy = qobject_cast<QAbstractProxyModel*>(views.at(level)->model());
    Q_ASSERT(proxy);

    // find all proxies between the source and our view
    QVector<QAbstractProxyModel*> proxies;
    proxies << proxy;
    forever {
        auto* child = qobject_cast<QAbstractProxyModel*>(proxy->sourceModel());
        if (child) {
            proxy = child;
            proxies << proxy;
        } else {
            Q_ASSERT(proxy->sourceModel() == model);
            break;
        }
    }
    // iterate in reverse order to find the view's index
    for (int i = proxies.size() - 1; i >= 0; --i) {
        proxy = proxies.at(i);
        index = proxy->mapFromSource(index);
        Q_ASSERT(index.isValid());
    }

    return index;
}

MultiLevelListView::MultiLevelListView(QWidget* parent, Qt::WindowFlags f)
    : QWidget(parent, f)
    , d_ptr(new MultiLevelListViewPrivate(this))
{
    setLayout(new QHBoxLayout());
    layout()->setContentsMargins(0, 0, 0, 0);

    qRegisterMetaType<QTreeView*>("QTreeView*");
}

MultiLevelListView::~MultiLevelListView() = default;

int MultiLevelListView::levels() const
{
    Q_D(const MultiLevelListView);

    return d->levels;
}

void MultiLevelListView::setLevels(int levels)
{
    Q_D(MultiLevelListView);

    qDeleteAll(d->views);
    qDeleteAll(d->proxies);
    qDeleteAll(d->layouts);
    d->views.clear();
    d->proxies.clear();
    d->layouts.clear();

    d->levels = levels;
    d->views.reserve(levels);
    d->proxies.reserve(levels);
    d->layouts.reserve(levels);

    QTreeView* previousView = nullptr;
    for (int i = 0; i < d->levels; ++i) {
        auto* levelLayout = new QVBoxLayout();

        auto* view = new QTreeView(this);
        view->setContentsMargins(0, 0, 0, 0);
        // only the right-most view is decorated
        view->setRootIsDecorated(i + 1 == d->levels);
        view->setHeaderHidden(false);
        view->setSelectionMode(QAbstractItemView::SingleSelection);

        if (!previousView) {
            // the root, i.e. left-most view
            auto* root = new RootProxyModel(this);
            root->setDynamicSortFilter(true);
            d->proxies << root;
            root->setSourceModel(d->model);
            view->setModel(root);
        } else {
            auto* subTreeProxy = new SubTreeProxyModel(previousView->selectionModel(), this);
            if (i + 1 < d->levels) {
                // middel views only shows children of selection
                subTreeProxy->setFilterBehavior(KSelectionProxyModel::ChildrenOfExactSelection);
            } else {
                // right-most view shows the rest
                subTreeProxy->setFilterBehavior(KSelectionProxyModel::SubTreesWithoutRoots);
            }
            d->proxies << subTreeProxy;
            subTreeProxy->setSourceModel(d->model);
            // sorting requires another proxy in-between
            auto* sortProxy = new QSortFilterProxyModel(subTreeProxy);
            sortProxy->setSourceModel(subTreeProxy);
            sortProxy->setDynamicSortFilter(true);
            view->setModel(sortProxy);
        }

        // view->setModel creates the selection model
        connect(view->selectionModel(), &QItemSelectionModel::currentChanged,
                this, [this](const QModelIndex& current, const QModelIndex& previous) {
            Q_D(MultiLevelListView);
            d->viewSelectionChanged(current, previous);
        });

        if (i + 1 == d->levels) {
            connect(view->model(), &QAbstractItemModel::rowsInserted,
                    this, [this] {
                Q_D(MultiLevelListView);
                d->lastViewsContentsChanged();
            });
        }

        view->setSortingEnabled(true);
        view->sortByColumn(0, Qt::AscendingOrder);

        levelLayout->addWidget(view);
        layout()->addItem(levelLayout);

        d->layouts << levelLayout;
        d->views << view;

        previousView = view;
    }

    setModel(d->model);
}

QAbstractItemModel* MultiLevelListView::model() const
{
    Q_D(const MultiLevelListView);

    return d->model;
}

void MultiLevelListView::setModel(QAbstractItemModel* model)
{
    Q_D(MultiLevelListView);

    d->model = model;

    for (LabeledProxy* proxy : qAsConst(d->proxies)) {
        dynamic_cast<QAbstractProxyModel*>(proxy)->setSourceModel(model);
    }

    if (model && !d->views.isEmpty()) {
        d->views.first()->setCurrentIndex(d->views.first()->model()->index(0, 0));
    }
}

QTreeView* MultiLevelListView::viewForLevel(int level) const
{
    Q_D(const MultiLevelListView);

    return d->views.value(level);
}

void MultiLevelListView::addWidget(int level, QWidget* widget)
{
    Q_D(MultiLevelListView);

    Q_ASSERT(level < d->levels);
    d->layouts[level]->addWidget(widget);
}

QModelIndex MultiLevelListView::currentIndex() const
{
    Q_D(const MultiLevelListView);

    return d->mapToSource(d->views.last()->currentIndex());
}

void MultiLevelListView::setCurrentIndex(const QModelIndex& index)
{
    Q_D(MultiLevelListView);

    // incoming index is for the original model
    Q_ASSERT(!index.isValid() || index.model() == d->model);

    const QModelIndex previous = currentIndex();

    QModelIndex idx(index);
    QVector<QModelIndex> indexes;

    while (idx.isValid()) {
        indexes.prepend(idx);
        idx = idx.parent();
    }

    for (int i = 0; i < d->levels; ++i) {
        QTreeView* view = d->views.at(i);
        if (indexes.size() <= i) {
            // select first item by default
            view->setCurrentIndex(view->model()->index(0, 0));
            continue;
        }

        QModelIndex index;
        if (i + 1 == d->levels) {
            // select the very last index in the list (i.e. might be deep down in the actual tree)
            index = indexes.last();
        } else {
            // select the first index for that level
            index = indexes.at(i);
        }
        view->setCurrentIndex(d->mapFromSource(index, i));
    }

    emit currentIndexChanged(index, previous);
}

void MultiLevelListView::setRootIndex(const QModelIndex& index)
{
    Q_D(MultiLevelListView);

    Q_ASSERT(!index.isValid() || index.model() == d->model);
    d->views.first()->setRootIndex(index);
}

void MultiLevelListView::setHeaderLabels(const QStringList& labels)
{
    Q_D(MultiLevelListView);

    int n = qMin(d->levels, labels.size());
    for (int i = 0; i < n; ++i) {
        d->proxies.at(i)->setLabel(labels[i]);
    }
}

static
KSelectionProxyModel::FilterBehavior toSelectionProxyModelFilterBehavior(MultiLevelListView::LastLevelViewMode mode)
{
    switch (mode) {
    case MultiLevelListView::SubTrees:
        return KSelectionProxyModel::SubTreesWithoutRoots;
    case MultiLevelListView::DirectChildren:
        return KSelectionProxyModel::ChildrenOfExactSelection;
    }
    Q_UNREACHABLE();
}

void MultiLevelListView::setLastLevelViewMode(LastLevelViewMode mode)
{
    Q_D(MultiLevelListView);

    if (d->proxies.isEmpty()) {
        return;
    }
    const auto filterBehavior = toSelectionProxyModelFilterBehavior(mode);
    dynamic_cast<KSelectionProxyModel*>(d->proxies.last())->setFilterBehavior(filterBehavior);
}

#include "multilevellistview.moc"
#include "moc_multilevellistview.cpp"