File: treemodel.cpp

package info (click to toggle)
qlcplus 4.14.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 58,644 kB
  • sloc: cpp: 182,867; javascript: 7,764; xml: 2,453; ansic: 2,120; sh: 1,716; python: 634; ruby: 606; makefile: 23
file content (523 lines) | stat: -rw-r--r-- 14,453 bytes parent folder | download | duplicates (2)
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
/*
  Q Light Controller Plus
  treemodel.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QDebug>
#include <QQmlEngine>

#include "treemodel.h"
#include "treemodelitem.h"

TreeModel::TreeModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_sorting(false)
    , m_checkable(false)
{

}

TreeModel::~TreeModel()
{
    //qDebug() << "!!! WARNING TreeModel destroyed WARNING !!!";
    clear();
}

QChar TreeModel::separator()
{
    return QLatin1Char('`');
}

void TreeModel::clear()
{
    int itemsCount = m_items.count();
    if (itemsCount == 0)
        return;

    for (int i = 0; i < itemsCount; i++)
    {
        TreeModelItem *item = m_items.takeLast();
        if (item->hasChildren())
            item->children()->clear();
        beginRemoveRows(QModelIndex(), 0, itemsCount - 1);
        delete item;
        endRemoveRows();
    }
    m_items.clear();
    m_itemsPathMap.clear();
}

void TreeModel::setColumnNames(QStringList names)
{
    m_roles = names;
}

void TreeModel::enableSorting(bool enable)
{
    m_sorting = enable;
}

void TreeModel::setCheckable(bool enable)
{
    m_checkable = enable;
}

void TreeModel::setSingleSelection(TreeModelItem *item)
{
    //bool parentSignalSent = false;
    //qDebug() << "Set single selection" << this;
    for (int i = 0; i < m_items.count(); i++)
    {
        TreeModelItem *target = m_items.at(i);

        if (target != item && target->flags() & Selected)
        {
            QModelIndex index = createIndex(i, 0, &i);
            target->setFlag(Selected, false);
            emit dataChanged(index, index, QVector<int>(1, IsSelectedRole));
        }

        if (target->hasChildren())
        {
            // if this slot has been called from self or a parent node,
            // then walk down the children path
            if (sender() != target->children())
                target->children()->setSingleSelection(item);
        }
    }
}

TreeModelItem *TreeModel::addItem(QString label, QVariantList data, QString path, int flags)
{
    //qDebug() << "Adding item" << label << path;

    TreeModelItem *item = nullptr;

    // fewer roles are allowed, while exceeding are probably a mistake
    if (data.count() > m_roles.count())
        qDebug() << "Item roles exceeds tree roles!" << data.count() << m_roles.count();

    if (m_checkable)
        flags |= Checkable;

    if (path.isEmpty())
    {
        /* This is the case of a 'leaf' child */
        item = new TreeModelItem(label);
        QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
        item->setData(data);
        item->setFlags(flags);
        if (flags & EmptyNode)
        {
            item->setPath(label);
            m_itemsPathMap[label] = item;
        }
        int addIndex = getItemInsertIndex(label);
        beginInsertRows(QModelIndex(), addIndex, addIndex);
        m_items.insert(addIndex, item);
        endInsertRows();
    }
    else
    {
        QStringList pathList = path.split(TreeModel::separator());
        if (m_itemsPathMap.contains(pathList.at(0)))
        {
            item = m_itemsPathMap.value(pathList.at(0), nullptr);
        }
        else
        {
            item = new TreeModelItem(pathList.at(0));
            item->setPath(pathList.at(0));
            item->setFlags(flags);
            QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
            if (item->setChildrenColumns(m_roles) == true)
            {
                connect(item->children(), SIGNAL(roleChanged(TreeModelItem*,int,const QVariant)),
                        this, SLOT(slotRoleChanged(TreeModelItem*,int,const QVariant&)));
                qDebug() << "Tree" << this << "connected to tree" << item->children();
            }

            int addIndex = getNodeInsertIndex(label);
            beginInsertRows(QModelIndex(), addIndex, addIndex);
            m_items.insert(addIndex, item);
            endInsertRows();
            m_itemsPathMap[pathList.at(0)] = item;
        }

        if (pathList.count() == 1)
        {
            if (item->addChild(label, data, m_sorting, "", flags) == true)
            {
                connect(item->children(), SIGNAL(roleChanged(TreeModelItem*,int,const QVariant&)),
                        this, SLOT(slotRoleChanged(TreeModelItem*,int,const QVariant&)));
                qDebug() << "Tree" << this << "connected to tree" << item->children();
            }
        }
        else
        {
            QString newPath = path.mid(path.indexOf(TreeModel::separator()) + 1);
            if (item->addChild(label, data, m_sorting, newPath, flags) == true)
            {
                connect(item->children(), SIGNAL(roleChanged(TreeModelItem*,int,const QVariant&)),
                        this, SLOT(slotRoleChanged(TreeModelItem*,int,const QVariant&)));
                qDebug() << "Tree" << this << "connected to tree" << item->children();
            }
        }
    }

    return item;
}

TreeModelItem *TreeModel::itemAtPath(QString path)
{
    if (path.isEmpty())
        return nullptr;

    QStringList pathList = path.split(TreeModel::separator());

    if (pathList.count() == 1)
    {
        int index = 0;
        for (index = 0; index < m_items.count(); index++)
        {
            if (m_items.at(index)->label() == path)
                return m_items.at(index);
        }

        if (index == m_items.count())
            return nullptr;
    }

    TreeModelItem *item = m_itemsPathMap.value(pathList.at(0), nullptr);
    if (item == nullptr)
        return nullptr;

    QString subPath = path.mid(path.indexOf(TreeModel::separator()) + 1);
    return item->children()->itemAtPath(subPath);
}

bool TreeModel::removeItem(QString path)
{
    if (path.isEmpty())
        return false;

    qDebug() << "Removing item with path:" << path;

    QStringList pathList = path.split(TreeModel::separator());

    if (pathList.count() == 1)
    {
        int index = 0;
        for (index = 0; index < m_items.count(); index++)
        {
            if (m_items.at(index)->label() == path)
                break;
        }

        if (index == m_items.count())
            return false;

        beginRemoveRows(QModelIndex(), index, index);
        m_itemsPathMap.remove(path);
        delete m_items.at(index);
        m_items.removeAt(index);
        endRemoveRows();
    }
    else
    {
        TreeModelItem *item = m_itemsPathMap.value(pathList.at(0), nullptr);
        if (item == nullptr)
            return false;

        QString subPath = path.mid(path.indexOf(TreeModel::separator()) + 1);
        item->children()->removeItem(subPath);
    }

    return true;
}

void TreeModel::setItemRoleData(QString path, const QVariant &value, int role)
{
    if (path.isEmpty())
        return;

    //qDebug() << "Looking for item with path:" << path;

    QStringList pathList = path.split(TreeModel::separator());

    if (pathList.count() == 1)
    {
        int index = 0;
        for (index = 0; index < m_items.count(); index++)
        {
            if (m_items.at(index)->label() == pathList.at(0))
                break;
        }

        if (index == m_items.count())
            return;

        QModelIndex mIndex = createIndex(index, 0, &index);
        setData(mIndex, value, role);
    }
    else
    {
        TreeModelItem *item = m_itemsPathMap.value(pathList.at(0), nullptr);
        if (item == nullptr)
            return;

        QString subPath = path.mid(path.indexOf(TreeModel::separator()) + 1);
        item->children()->setItemRoleData(subPath, value, role);
    }
}

void TreeModel::setItemRoleData(TreeModelItem *item, const QVariant &value, int role)
{
    if (item == nullptr)
        return;

    int index = m_items.indexOf(item);
    if (index == -1)
        return;

    QModelIndex mIndex = createIndex(index, 0, &index);
    setData(mIndex, value, role);
}

QList<TreeModelItem *> TreeModel::items()
{
    return m_items;
}

void TreeModel::setPathData(QString path, QVariantList data)
{
    if (path.isEmpty())
        return;

    QStringList pathList = path.split(TreeModel::separator());
    TreeModelItem *item = m_itemsPathMap.value(pathList.at(0), nullptr);
    if (item == nullptr)
        return;

    if (pathList.count() == 1)
    {
        item->setData(data);
    }
    else if (item->hasChildren())
    {
        QString subPath = path.mid(path.indexOf(TreeModel::separator()) + 1);
        item->children()->setPathData(subPath, data);
    }
}

int TreeModel::roleIndex(QString role)
{
    return roleNames().key(role.toLatin1(), -1);
}

int TreeModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return m_items.count();
}

QVariant TreeModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= m_items.count())
        return QVariant();

    int itemRow = index.row();
    if (itemRow < 0 || itemRow >= m_items.count())
        return false;

    TreeModelItem *item = m_items.at(itemRow);

    switch(role)
    {
        case LabelRole:
            return item->label();
        case PathRole:
            return item->path();
        case IsExpandedRole:
            return (item->flags() & Expanded) ? true : false;
        case IsSelectedRole:
            return (item->flags() & Selected) ? true : false;
        case IsCheckableRole:
            return (item->flags() & Checkable) ? true : false;
        case IsCheckedRole:
            return (item->flags() & Checked) ? true : false;
        case IsDraggableRole:
            return (item->flags() & Draggable) ? true : false;
        case ItemsCountRole:
            return m_items.count();
        case HasChildrenRole:
            return item->hasChildren() || (item->flags() & EmptyNode);
        case ChildrenModel:
            return QVariant::fromValue(item->children());
        default:
            return m_items.at(index.row())->data(role - FixedRolesEnd);
    }
}

bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    int itemRow = index.row();
    if (itemRow < 0 || itemRow >= m_items.count())
        return false;

    TreeModelItem *item = m_items.at(itemRow);

    //qDebug() << "Setting role" << role << "on row" << itemRow << "with value" << value;

    switch(role)
    {
        case LabelRole:
            item->setLabel(value.toString());
        break;
        case PathRole:
            item->setPath(value.toString());
        break;
        case IsExpandedRole:
            item->setFlag(Expanded, value.toBool());
        break;
        case IsSelectedRole:
        {
            if (value.toInt() > 0)
            {
                item->setFlag(Selected, true);
                if (value.toInt() == 1)
                    setSingleSelection(item);
            }
            else
                item->setFlag(Selected, false);
        }
        break;
        case IsCheckableRole:
            item->setFlag(Checkable, value.toBool());
        break;
        case IsCheckedRole:
            item->setFlag(Checked, value.toBool());
        break;
        case IsDraggableRole:
            item->setFlag(Draggable, value.toBool());
        break;
        default:
            item->setRoleData(role - FixedRolesEnd, value);
        break;
    }

    emit roleChanged(item, role, value);
    emit dataChanged(index, index, QVector<int>(1, role));

    return true;
}

void TreeModel::slotRoleChanged(TreeModelItem *item, int role, const QVariant &value)
{
    if (item == nullptr)
        return;

    switch(role)
    {
        case IsSelectedRole:
        {
            if (value.toInt() == 1)
                setSingleSelection(item);
        }
        break;
    }

    if (sender() != this)
        emit roleChanged(item, role, value);
}

void TreeModel::printTree(int tab)
{
    for (TreeModelItem *item : m_items)
    {
        item->printItem(tab);
        if (item->hasChildren())
            item->children()->printTree(tab + 2);
    }
}

int TreeModel::getItemInsertIndex(QString label)
{
    if (m_sorting == true)
    {
        int index = 0;
        for (int i = 0; i < m_items.count(); i++)
        {
            if (m_items.at(i)->hasChildren() == false)
            {
                if (QString::localeAwareCompare(m_items.at(i)->label(), label) > 0)
                    return index;
            }
            index++;
        }
    }
    return rowCount();
}

int TreeModel::getNodeInsertIndex(QString label)
{
    if (m_sorting == true)
    {
        int index = 0;
        for (int i = 0; i < m_items.count(); i++)
        {
            if (m_items.at(i)->hasChildren() == true)
            {
                if (QString::localeAwareCompare(m_items.at(i)->label(), label) > 0)
                    return index;
                index++;
            }
        }
    }
    return rowCount();
}

QHash<int, QByteArray> TreeModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[LabelRole] = "label";
    roles[PathRole] = "path";
    roles[IsExpandedRole] = "isExpanded";
    // The isSelected role is tricky.
    // It always returns true/false through the data() method but
    // to set it via setData(), an integer has to be passed, to distinguish
    // between 3 cases:
    // 0: item de-selection
    // 1: item single (exclusive) selection
    // 2: item multiple selection (when Ctrl-click an item)
    roles[IsSelectedRole] = "isSelected";
    roles[IsCheckableRole] = "isCheckable";
    roles[IsCheckedRole] = "isChecked";
    roles[IsDraggableRole] = "isDraggable";
    roles[ItemsCountRole] = "itemsCount";
    roles[HasChildrenRole] = "hasChildren";
    roles[ChildrenModel] = "childrenModel";

    int roleStartIdx = FixedRolesEnd;
    for (int i = roleStartIdx, t = 0; i < roleStartIdx + m_roles.count(); i++, t++)
        roles[i] = m_roles.at(t).toLatin1();

    //qDebug() << "Returned" << roles.count() << "roles";

    return roles;
}