1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include <math.h>
5#include <QtCore/qstack.h>
6#include <QtCore/qdebug.h>
7
8#include "qqmltreemodeltotablemodel_p_p.h"
9
10QT_BEGIN_NAMESPACE
11
12//#define QQMLTREEMODELADAPTOR_DEBUG
13#if defined(QQMLTREEMODELADAPTOR_DEBUG) && !defined(QT_TESTLIB_LIB)
14# define ASSERT_CONSISTENCY() Q_ASSERT_X(testConsistency(true /* dumpOnFail */), Q_FUNC_INFO, "Consistency test failed")
15#else
16# define ASSERT_CONSISTENCY qt_noop
17#endif
18
19QQmlTreeModelToTableModel::QQmlTreeModelToTableModel(QObject *parent)
20 : QAbstractItemModel(parent)
21{
22}
23
24QAbstractItemModel *QQmlTreeModelToTableModel::model() const
25{
26 return m_model;
27}
28
29void QQmlTreeModelToTableModel::connectToModel()
30{
31 m_connections = {
32 QObject::connect(sender: m_model, signal: &QAbstractItemModel::destroyed,
33 context: this, slot: &QQmlTreeModelToTableModel::modelHasBeenDestroyed),
34 QObject::connect(sender: m_model, signal: &QAbstractItemModel::modelReset,
35 context: this, slot: &QQmlTreeModelToTableModel::modelHasBeenReset),
36 QObject::connect(sender: m_model, signal: &QAbstractItemModel::dataChanged,
37 context: this, slot: &QQmlTreeModelToTableModel::modelDataChanged),
38
39 QObject::connect(sender: m_model, signal: &QAbstractItemModel::layoutAboutToBeChanged,
40 context: this, slot: &QQmlTreeModelToTableModel::modelLayoutAboutToBeChanged),
41 QObject::connect(sender: m_model, signal: &QAbstractItemModel::layoutChanged,
42 context: this, slot: &QQmlTreeModelToTableModel::modelLayoutChanged),
43
44 QObject::connect(sender: m_model, signal: &QAbstractItemModel::rowsAboutToBeInserted,
45 context: this, slot: &QQmlTreeModelToTableModel::modelRowsAboutToBeInserted),
46 QObject::connect(sender: m_model, signal: &QAbstractItemModel::rowsInserted,
47 context: this, slot: &QQmlTreeModelToTableModel::modelRowsInserted),
48 QObject::connect(sender: m_model, signal: &QAbstractItemModel::rowsAboutToBeRemoved,
49 context: this, slot: &QQmlTreeModelToTableModel::modelRowsAboutToBeRemoved),
50 QObject::connect(sender: m_model, signal: &QAbstractItemModel::rowsRemoved,
51 context: this, slot: &QQmlTreeModelToTableModel::modelRowsRemoved),
52 QObject::connect(sender: m_model, signal: &QAbstractItemModel::rowsAboutToBeMoved,
53 context: this, slot: &QQmlTreeModelToTableModel::modelRowsAboutToBeMoved),
54 QObject::connect(sender: m_model, signal: &QAbstractItemModel::rowsMoved,
55 context: this, slot: &QQmlTreeModelToTableModel::modelRowsMoved),
56
57 QObject::connect(sender: m_model, signal: &QAbstractItemModel::columnsAboutToBeInserted,
58 context: this, slot: &QQmlTreeModelToTableModel::modelColumnsAboutToBeInserted),
59 QObject::connect(sender: m_model, signal: &QAbstractItemModel::columnsAboutToBeRemoved,
60 context: this, slot: &QQmlTreeModelToTableModel::modelColumnsAboutToBeRemoved),
61 QObject::connect(sender: m_model, signal: &QAbstractItemModel::columnsInserted,
62 context: this, slot: &QQmlTreeModelToTableModel::modelColumnsInserted),
63 QObject::connect(sender: m_model, signal: &QAbstractItemModel::columnsRemoved,
64 context: this, slot: &QQmlTreeModelToTableModel::modelColumnsRemoved)
65 };
66}
67
68void QQmlTreeModelToTableModel::setModel(QAbstractItemModel *arg)
69{
70 if (m_model != arg) {
71 if (m_model) {
72 for (const auto &c : m_connections)
73 QObject::disconnect(c);
74 m_connections.fill(u: {});
75 }
76
77 clearModelData();
78 m_model = arg;
79
80 if (m_rootIndex.isValid() && m_rootIndex.model() != m_model)
81 m_rootIndex = QModelIndex();
82
83 if (m_model) {
84 connectToModel();
85 showModelTopLevelItems();
86 }
87
88 emit modelChanged(model: arg);
89 }
90}
91
92void QQmlTreeModelToTableModel::clearModelData()
93{
94 beginResetModel();
95 m_items.clear();
96 m_expandedItems.clear();
97 endResetModel();
98}
99
100QModelIndex QQmlTreeModelToTableModel::rootIndex() const
101{
102 return m_rootIndex;
103}
104
105void QQmlTreeModelToTableModel::setRootIndex(const QModelIndex &idx)
106{
107 if (m_rootIndex == idx)
108 return;
109
110 if (m_model)
111 clearModelData();
112 m_rootIndex = idx;
113 if (m_model)
114 showModelTopLevelItems();
115 emit rootIndexChanged();
116}
117
118void QQmlTreeModelToTableModel::resetRootIndex()
119{
120 setRootIndex(QModelIndex());
121}
122
123QModelIndex QQmlTreeModelToTableModel::index(int row, int column, const QModelIndex &parent) const
124{
125 return hasIndex(row, column, parent) ? createIndex(arow: row, acolumn: column) : QModelIndex();
126}
127
128QModelIndex QQmlTreeModelToTableModel::parent(const QModelIndex &child) const
129{
130 Q_UNUSED(child)
131 return QModelIndex();
132}
133
134QHash<int, QByteArray> QQmlTreeModelToTableModel::roleNames() const
135{
136 if (!m_model)
137 return QHash<int, QByteArray>();
138 return m_model->roleNames();
139}
140
141int QQmlTreeModelToTableModel::rowCount(const QModelIndex &) const
142{
143 if (!m_model)
144 return 0;
145 return m_items.size();
146}
147
148int QQmlTreeModelToTableModel::columnCount(const QModelIndex &parent) const
149{
150 if (!m_model)
151 return 0;
152 return m_model->columnCount(parent);
153}
154
155QVariant QQmlTreeModelToTableModel::data(const QModelIndex &index, int role) const
156{
157 if (!m_model)
158 return QVariant();
159
160 return m_model->data(index: mapToModel(index), role);
161}
162
163bool QQmlTreeModelToTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
164{
165 if (!m_model)
166 return false;
167
168 return m_model->setData(index: mapToModel(index), value, role);
169}
170
171QVariant QQmlTreeModelToTableModel::headerData(int section, Qt::Orientation orientation, int role) const
172{
173 return m_model->headerData(section, orientation, role);
174}
175
176Qt::ItemFlags QQmlTreeModelToTableModel::flags(const QModelIndex &index) const
177{
178 return m_model->flags(index: mapToModel(index));
179}
180
181int QQmlTreeModelToTableModel::depthAtRow(int row) const
182{
183 if (row < 0 || row >= m_items.size())
184 return 0;
185 return m_items.at(i: row).depth;
186}
187
188int QQmlTreeModelToTableModel::itemIndex(const QModelIndex &index) const
189{
190 // This is basically a plagiarism of QTreeViewPrivate::viewIndex()
191 if (!index.isValid() || index == m_rootIndex || m_items.isEmpty())
192 return -1;
193
194 const int totalCount = m_items.size();
195
196 // We start nearest to the lastViewedItem
197 int localCount = qMin(a: m_lastItemIndex - 1, b: totalCount - m_lastItemIndex);
198
199 for (int i = 0; i < localCount; ++i) {
200 const TreeItem &item1 = m_items.at(i: m_lastItemIndex + i);
201 if (item1.index == index) {
202 m_lastItemIndex = m_lastItemIndex + i;
203 return m_lastItemIndex;
204 }
205 const TreeItem &item2 = m_items.at(i: m_lastItemIndex - i - 1);
206 if (item2.index == index) {
207 m_lastItemIndex = m_lastItemIndex - i - 1;
208 return m_lastItemIndex;
209 }
210 }
211
212 for (int j = qMax(a: 0, b: m_lastItemIndex + localCount); j < totalCount; ++j) {
213 const TreeItem &item = m_items.at(i: j);
214 if (item.index == index) {
215 m_lastItemIndex = j;
216 return j;
217 }
218 }
219
220 for (int j = qMin(a: totalCount, b: m_lastItemIndex - localCount) - 1; j >= 0; --j) {
221 const TreeItem &item = m_items.at(i: j);
222 if (item.index == index) {
223 m_lastItemIndex = j;
224 return j;
225 }
226 }
227
228 // nothing found
229 return -1;
230}
231
232bool QQmlTreeModelToTableModel::isVisible(const QModelIndex &index)
233{
234 return itemIndex(index) != -1;
235}
236
237bool QQmlTreeModelToTableModel::childrenVisible(const QModelIndex &index)
238{
239 return (index == m_rootIndex && !m_items.isEmpty())
240 || (m_expandedItems.contains(value: index) && isVisible(index));
241}
242
243QModelIndex QQmlTreeModelToTableModel::mapToModel(const QModelIndex &index) const
244{
245 if (!index.isValid())
246 return QModelIndex();
247
248 const int row = index.row();
249 if (row < 0 || row > m_items.size() - 1)
250 return QModelIndex();
251
252 const QModelIndex sourceIndex = m_items.at(i: row).index;
253 return m_model->index(row: sourceIndex.row(), column: index.column(), parent: sourceIndex.parent());
254}
255
256QModelIndex QQmlTreeModelToTableModel::mapFromModel(const QModelIndex &index) const
257{
258 if (!index.isValid())
259 return QModelIndex();
260
261 int row = -1;
262 for (int i = 0; i < m_items.size(); ++i) {
263 const QModelIndex proxyIndex = m_items[i].index;
264 if (proxyIndex.row() == index.row() && proxyIndex.parent() == index.parent()) {
265 row = i;
266 break;
267 }
268 }
269
270 if (row == -1)
271 return QModelIndex();
272
273 return this->index(row, column: index.column());
274}
275
276QModelIndex QQmlTreeModelToTableModel::mapToModel(int row) const
277{
278 if (row < 0 || row >= m_items.size())
279 return QModelIndex();
280 return m_items.at(i: row).index;
281}
282
283QItemSelection QQmlTreeModelToTableModel::selectionForRowRange(const QModelIndex &fromIndex, const QModelIndex &toIndex) const
284{
285 int from = itemIndex(index: fromIndex);
286 int to = itemIndex(index: toIndex);
287 if (from == -1) {
288 if (to == -1)
289 return QItemSelection();
290 return QItemSelection(toIndex, toIndex);
291 }
292
293 to = qMax(a: to, b: 0);
294 if (from > to)
295 qSwap(value1&: from, value2&: to);
296
297 typedef std::pair<QModelIndex, QModelIndex> MIPair;
298 typedef QHash<QModelIndex, MIPair> MI2MIPairHash;
299 MI2MIPairHash ranges;
300 QModelIndex firstIndex = m_items.at(i: from).index;
301 QModelIndex lastIndex = firstIndex;
302 QModelIndex previousParent = firstIndex.parent();
303 bool selectLastRow = false;
304 for (int i = from + 1; i <= to || (selectLastRow = true); i++) {
305 // We run an extra iteration to make sure the last row is
306 // added to the selection. (And also to avoid duplicating
307 // the insertion code.)
308 QModelIndex index;
309 QModelIndex parent;
310 if (!selectLastRow) {
311 index = m_items.at(i).index;
312 parent = index.parent();
313 }
314 if (selectLastRow || previousParent != parent) {
315 const MI2MIPairHash::iterator &it = ranges.find(key: previousParent);
316 if (it == ranges.end())
317 ranges.insert(key: previousParent, value: MIPair(firstIndex, lastIndex));
318 else
319 it->second = lastIndex;
320
321 if (selectLastRow)
322 break;
323
324 firstIndex = index;
325 previousParent = parent;
326 }
327 lastIndex = index;
328 }
329
330 QItemSelection sel;
331 sel.reserve(asize: ranges.size());
332 for (const MIPair &pair : std::as_const(t&: ranges))
333 sel.append(t: QItemSelectionRange(pair.first, pair.second));
334
335 return sel;
336}
337
338void QQmlTreeModelToTableModel::showModelTopLevelItems(bool doInsertRows)
339{
340 if (!m_model)
341 return;
342
343 if (m_model->hasChildren(parent: m_rootIndex) && m_model->canFetchMore(parent: m_rootIndex))
344 m_model->fetchMore(parent: m_rootIndex);
345 const long topLevelRowCount = m_model->rowCount(parent: m_rootIndex);
346 if (topLevelRowCount == 0)
347 return;
348
349 showModelChildItems(parent: TreeItem(m_rootIndex), start: 0, end: topLevelRowCount - 1, doInsertRows);
350}
351
352void QQmlTreeModelToTableModel::showModelChildItems(const TreeItem &parentItem, int start, int end, bool doInsertRows, bool doExpandPendingRows)
353{
354 const QModelIndex &parentIndex = parentItem.index;
355 int rowIdx = parentIndex.isValid() && parentIndex != m_rootIndex ? itemIndex(index: parentIndex) + 1 : 0;
356 Q_ASSERT(rowIdx == 0 || parentItem.expanded);
357 if (parentIndex.isValid() && parentIndex != m_rootIndex && (rowIdx == 0 || !parentItem.expanded))
358 return;
359
360 if (m_model->rowCount(parent: parentIndex) == 0) {
361 if (m_model->hasChildren(parent: parentIndex) && m_model->canFetchMore(parent: parentIndex))
362 m_model->fetchMore(parent: parentIndex);
363 return;
364 }
365
366 int insertCount = end - start + 1;
367 int startIdx;
368 if (start == 0) {
369 startIdx = rowIdx;
370 } else {
371 // Prefer to insert before next sibling instead of after last child of previous, as
372 // the latter is potentially buggy, see QTBUG-66062
373 const QModelIndex &nextSiblingIdx = m_model->index(row: end + 1, column: 0, parent: parentIndex);
374 if (nextSiblingIdx.isValid()) {
375 startIdx = itemIndex(index: nextSiblingIdx);
376 } else {
377 const QModelIndex &prevSiblingIdx = m_model->index(row: start - 1, column: 0, parent: parentIndex);
378 startIdx = lastChildIndex(index: prevSiblingIdx) + 1;
379 }
380 }
381
382 int rowDepth = rowIdx == 0 ? 0 : parentItem.depth + 1;
383 if (doInsertRows)
384 beginInsertRows(parent: QModelIndex(), first: startIdx, last: startIdx + insertCount - 1);
385 m_items.reserve(asize: m_items.size() + insertCount);
386
387 for (int i = 0; i < insertCount; i++) {
388 const QModelIndex &cmi = m_model->index(row: start + i, column: 0, parent: parentIndex);
389 const bool expanded = m_expandedItems.contains(value: cmi);
390 const TreeItem treeItem(cmi, rowDepth, expanded);
391 m_items.insert(i: startIdx + i, t: treeItem);
392
393 if (expanded)
394 m_itemsToExpand.append(t: treeItem);
395 }
396
397 if (doInsertRows)
398 endInsertRows();
399
400 if (doExpandPendingRows)
401 expandPendingRows(doInsertRows);
402}
403
404
405void QQmlTreeModelToTableModel::expand(const QModelIndex &idx)
406{
407 ASSERT_CONSISTENCY();
408 if (!m_model)
409 return;
410
411 Q_ASSERT(!idx.isValid() || idx.model() == m_model);
412
413 if (!idx.isValid() || !m_model->hasChildren(parent: idx))
414 return;
415 if (m_expandedItems.contains(value: idx))
416 return;
417
418 int row = itemIndex(index: idx);
419 if (row != -1)
420 expandRow(n: row);
421 else
422 m_expandedItems.insert(value: idx);
423 ASSERT_CONSISTENCY();
424
425 emit expanded(index: idx);
426}
427
428void QQmlTreeModelToTableModel::collapse(const QModelIndex &idx)
429{
430 ASSERT_CONSISTENCY();
431 if (!m_model)
432 return;
433
434 Q_ASSERT(!idx.isValid() || idx.model() == m_model);
435
436 if (!idx.isValid() || !m_model->hasChildren(parent: idx))
437 return;
438 if (!m_expandedItems.contains(value: idx))
439 return;
440
441 int row = itemIndex(index: idx);
442 if (row != -1)
443 collapseRow(n: row);
444 else
445 m_expandedItems.remove(value: idx);
446 ASSERT_CONSISTENCY();
447
448 emit collapsed(index: idx);
449}
450
451bool QQmlTreeModelToTableModel::isExpanded(const QModelIndex &index) const
452{
453 ASSERT_CONSISTENCY();
454 if (!m_model)
455 return false;
456
457 Q_ASSERT(!index.isValid() || index.model() == m_model);
458 return !index.isValid() || m_expandedItems.contains(value: index);
459}
460
461bool QQmlTreeModelToTableModel::isExpanded(int row) const
462{
463 if (row < 0 || row >= m_items.size())
464 return false;
465 return m_items.at(i: row).expanded;
466}
467
468bool QQmlTreeModelToTableModel::hasChildren(int row) const
469{
470 if (row < 0 || row >= m_items.size())
471 return false;
472 return m_model->hasChildren(parent: m_items[row].index);
473}
474
475bool QQmlTreeModelToTableModel::hasSiblings(int row) const
476{
477 const QModelIndex &index = mapToModel(row);
478 return index.row() != m_model->rowCount(parent: index.parent()) - 1;
479}
480
481void QQmlTreeModelToTableModel::expandRow(int n)
482{
483 if (!m_model || isExpanded(row: n))
484 return;
485
486 TreeItem &item = m_items[n];
487 if ((item.index.flags() & Qt::ItemNeverHasChildren) || !m_model->hasChildren(parent: item.index))
488 return;
489 item.expanded = true;
490 m_expandedItems.insert(value: item.index);
491 emit dataChanged(topLeft: index(row: n, column: 0), bottomRight: index(row: n, column: 0), roles: {ExpandedRole});
492
493 m_itemsToExpand.append(t: item);
494 expandPendingRows();
495}
496
497void QQmlTreeModelToTableModel::expandRecursively(int row, int depth)
498{
499 Q_ASSERT(depth == -1 || depth > 0);
500 const int startDepth = depthAtRow(row);
501
502 auto expandHelp = [this, depth, startDepth] (const auto expandHelp, const QModelIndex &index) -> void {
503 const int rowToExpand = itemIndex(index);
504 if (!m_expandedItems.contains(value: index))
505 expandRow(n: rowToExpand);
506
507 if (depth != -1 && depthAtRow(row: rowToExpand) == startDepth + depth - 1)
508 return;
509
510 const int childCount = m_model->rowCount(parent: index);
511 for (int childRow = 0; childRow < childCount; ++childRow) {
512 const QModelIndex childIndex = m_model->index(row: childRow, column: 0, parent: index);
513 if (m_model->hasChildren(parent: childIndex))
514 expandHelp(expandHelp, childIndex);
515 }
516 };
517
518 const QModelIndex index = m_items[row].index;
519 if (index.isValid())
520 expandHelp(expandHelp, index);
521}
522
523void QQmlTreeModelToTableModel::expandPendingRows(bool doInsertRows)
524{
525 while (!m_itemsToExpand.isEmpty()) {
526 const TreeItem item = m_itemsToExpand.takeFirst();
527 Q_ASSERT(item.expanded);
528 const QModelIndex &index = item.index;
529 int childrenCount = m_model->rowCount(parent: index);
530 if (childrenCount == 0) {
531 if (m_model->hasChildren(parent: index) && m_model->canFetchMore(parent: index))
532 m_model->fetchMore(parent: index);
533 continue;
534 }
535
536 // TODO Pre-compute the total number of items made visible
537 // so that we only call a single beginInsertRows()/endInsertRows()
538 // pair per expansion (same as we do for collapsing).
539 showModelChildItems(parentItem: item, start: 0, end: childrenCount - 1, doInsertRows, doExpandPendingRows: false);
540 }
541}
542
543void QQmlTreeModelToTableModel::collapseRecursively(int row)
544{
545 auto collapseHelp = [this] (const auto collapseHelp, const QModelIndex &index) -> void {
546 if (m_expandedItems.contains(value: index)) {
547 const int rowToCollapse = itemIndex(index);
548 if (rowToCollapse != -1)
549 collapseRow(n: rowToCollapse);
550 else
551 m_expandedItems.remove(value: index);
552 }
553
554 const int childCount = m_model->rowCount(parent: index);
555 for (int childRow = 0; childRow < childCount; ++childRow) {
556 const QModelIndex childIndex = m_model->index(row: childRow, column: 0, parent: index);
557 if (m_model->hasChildren(parent: childIndex))
558 collapseHelp(collapseHelp, childIndex);
559 }
560 };
561
562 const QModelIndex index = m_items[row].index;
563 if (index.isValid())
564 collapseHelp(collapseHelp, index);
565}
566
567void QQmlTreeModelToTableModel::collapseRow(int n)
568{
569 if (!m_model || !isExpanded(row: n))
570 return;
571
572 SignalFreezer aggregator(this);
573
574 TreeItem &item = m_items[n];
575 item.expanded = false;
576 m_expandedItems.remove(value: item.index);
577 queueDataChanged(top: n, bottom: n, roles: {ExpandedRole});
578 int childrenCount = m_model->rowCount(parent: item.index);
579 if ((item.index.flags() & Qt::ItemNeverHasChildren) || !m_model->hasChildren(parent: item.index) || childrenCount == 0)
580 return;
581
582 const QModelIndex &emi = m_model->index(row: childrenCount - 1, column: 0, parent: item.index);
583 int lastIndex = lastChildIndex(index: emi);
584 removeVisibleRows(startIndex: n + 1, endIndex: lastIndex);
585}
586
587int QQmlTreeModelToTableModel::lastChildIndex(const QModelIndex &index) const
588{
589 // The purpose of this function is to return the row of the last decendant of a node N.
590 // But note: index should point to the last child of N, and not N itself!
591 // This means that if index is not expanded, the last child will simply be index itself.
592 // Otherwise, since the tree underneath index can be of any depth, it will instead find
593 // the first sibling of N, get its table row, and simply return the row above.
594 if (!m_expandedItems.contains(value: index))
595 return itemIndex(index);
596
597 QModelIndex parent = index.parent();
598 QModelIndex nextSiblingIndex;
599 while (parent.isValid()) {
600 nextSiblingIndex = parent.sibling(arow: parent.row() + 1, acolumn: 0);
601 if (nextSiblingIndex.isValid())
602 break;
603 parent = parent.parent();
604 }
605
606 int firstIndex = nextSiblingIndex.isValid() ? itemIndex(index: nextSiblingIndex) : m_items.size();
607 return firstIndex - 1;
608}
609
610void QQmlTreeModelToTableModel::removeVisibleRows(int startIndex, int endIndex, bool doRemoveRows)
611{
612 if (startIndex < 0 || endIndex < 0 || startIndex > endIndex)
613 return;
614
615 if (doRemoveRows)
616 beginRemoveRows(parent: QModelIndex(), first: startIndex, last: endIndex);
617 m_items.erase(abegin: m_items.begin() + startIndex, aend: m_items.begin() + endIndex + 1);
618 if (doRemoveRows) {
619 endRemoveRows();
620
621 /* We need to update the model index for all the items below the removed ones */
622 int lastIndex = m_items.size() - 1;
623 if (startIndex <= lastIndex)
624 queueDataChanged(top: startIndex, bottom: lastIndex, roles: {ModelIndexRole});
625 }
626}
627
628void QQmlTreeModelToTableModel::modelHasBeenDestroyed()
629{
630 // The model has been deleted. This should behave as if no model was set
631 clearModelData();
632 emit modelChanged(model: nullptr);
633}
634
635void QQmlTreeModelToTableModel::modelHasBeenReset()
636{
637 clearModelData();
638
639 showModelTopLevelItems();
640 ASSERT_CONSISTENCY();
641}
642
643void QQmlTreeModelToTableModel::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles)
644{
645 Q_ASSERT(topLeft.parent() == bottomRight.parent());
646 const QModelIndex &parent = topLeft.parent();
647 if (parent.isValid() && !childrenVisible(index: parent)) {
648 ASSERT_CONSISTENCY();
649 return;
650 }
651
652 int topIndex = itemIndex(index: topLeft.siblingAtColumn(acolumn: 0));
653 if (topIndex == -1) // 'parent' is not visible anymore, though it's been expanded previously
654 return;
655 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
656 // Group items with same parent to minize the number of 'dataChanged()' emits
657 int bottomIndex = topIndex;
658 while (bottomIndex < m_items.size()) {
659 const QModelIndex &idx = m_items.at(i: bottomIndex).index;
660 if (idx.parent() != parent) {
661 --bottomIndex;
662 break;
663 }
664 if (idx.row() == bottomRight.row())
665 break;
666 ++bottomIndex;
667 }
668 emit dataChanged(topLeft: index(row: topIndex, column: topLeft.column()), bottomRight: index(row: bottomIndex, column: bottomRight.column()), roles);
669
670 i += bottomIndex - topIndex;
671 if (i == bottomRight.row())
672 break;
673 topIndex = bottomIndex + 1;
674 while (topIndex < m_items.size()
675 && m_items.at(i: topIndex).index.parent() != parent)
676 topIndex++;
677 }
678 ASSERT_CONSISTENCY();
679}
680
681void QQmlTreeModelToTableModel::modelLayoutAboutToBeChanged(const QList<QPersistentModelIndex> &parents, QAbstractItemModel::LayoutChangeHint hint)
682{
683 Q_UNUSED(hint)
684
685 // Since the m_items is a list of TreeItems that contains QPersistentModelIndexes, we
686 // cannot wait until we get a modelLayoutChanged() before we remove the affected rows
687 // from that list. After the layout has changed, the list (or, the persistent indexes
688 // that it contains) is no longer in sync with the model (after all, that is what we're
689 // supposed to correct in modelLayoutChanged()).
690 // This means that vital functions, like itemIndex(index), cannot be trusted at that point.
691 // Therefore we need to do the update in two steps; First remove all the affected rows
692 // from here (while we're still in sync with the model), and then add back the
693 // affected rows, and notify about it, from modelLayoutChanged().
694 m_modelLayoutChanged = false;
695
696 if (parents.isEmpty() || !parents[0].isValid()) {
697 // Update entire model
698 emit layoutAboutToBeChanged();
699 m_modelLayoutChanged = true;
700 m_items.clear();
701 return;
702 }
703
704 for (const QPersistentModelIndex &pmi : parents) {
705 if (!m_expandedItems.contains(value: pmi))
706 continue;
707 const int row = itemIndex(index: pmi);
708 if (row == -1)
709 continue;
710 const int rowCount = m_model->rowCount(parent: pmi);
711 if (rowCount == 0)
712 continue;
713
714 if (!m_modelLayoutChanged) {
715 emit layoutAboutToBeChanged();
716 m_modelLayoutChanged = true;
717 }
718
719 const QModelIndex &lmi = m_model->index(row: rowCount - 1, column: 0, parent: pmi);
720 const int lastRow = lastChildIndex(index: lmi);
721 removeVisibleRows(startIndex: row + 1, endIndex: lastRow, doRemoveRows: false /*doRemoveRows*/);
722 }
723
724 ASSERT_CONSISTENCY();
725}
726
727void QQmlTreeModelToTableModel::modelLayoutChanged(const QList<QPersistentModelIndex> &parents, QAbstractItemModel::LayoutChangeHint hint)
728{
729 Q_UNUSED(hint)
730
731 if (!m_modelLayoutChanged) {
732 // No relevant changes done from modelLayoutAboutToBeChanged()
733 return;
734 }
735
736 if (m_items.isEmpty()) {
737 // Entire model has changed. Add back all rows.
738 showModelTopLevelItems(doInsertRows: false /*doInsertRows*/);
739 const QModelIndex &mi = m_model->index(row: 0, column: 0);
740 const int columnCount = m_model->columnCount(parent: mi);
741 emit dataChanged(topLeft: index(row: 0, column: 0), bottomRight: index(row: m_items.size() - 1, column: columnCount - 1));
742 emit layoutChanged();
743 return;
744 }
745
746 for (const QPersistentModelIndex &pmi : parents) {
747 if (!m_expandedItems.contains(value: pmi))
748 continue;
749 const int row = itemIndex(index: pmi);
750 if (row == -1)
751 continue;
752 const int rowCount = m_model->rowCount(parent: pmi);
753 if (rowCount == 0)
754 continue;
755
756 const QModelIndex &lmi = m_model->index(row: rowCount - 1, column: 0, parent: pmi);
757 const int columnCount = m_model->columnCount(parent: lmi);
758 showModelChildItems(parentItem: m_items.at(i: row), start: 0, end: rowCount - 1, doInsertRows: false /*doInsertRows*/);
759 const int lastRow = lastChildIndex(index: lmi);
760 emit dataChanged(topLeft: index(row: row + 1, column: 0), bottomRight: index(row: lastRow, column: columnCount - 1));
761 }
762
763 emit layoutChanged();
764
765 ASSERT_CONSISTENCY();
766}
767
768void QQmlTreeModelToTableModel::modelRowsAboutToBeInserted(const QModelIndex & parent, int start, int end)
769{
770 Q_UNUSED(parent)
771 Q_UNUSED(start)
772 Q_UNUSED(end)
773 ASSERT_CONSISTENCY();
774}
775
776void QQmlTreeModelToTableModel::modelRowsInserted(const QModelIndex & parent, int start, int end)
777{
778 TreeItem item;
779 int parentRow = itemIndex(index: parent);
780 if (parentRow >= 0) {
781 queueDataChanged(top: parentRow, bottom: parentRow, roles: {HasChildrenRole});
782 item = m_items.at(i: parentRow);
783 if (!item.expanded) {
784 ASSERT_CONSISTENCY();
785 return;
786 }
787 } else if (parent == m_rootIndex) {
788 item = TreeItem(parent);
789 } else {
790 ASSERT_CONSISTENCY();
791 return;
792 }
793 showModelChildItems(parentItem: item, start, end);
794 ASSERT_CONSISTENCY();
795}
796
797void QQmlTreeModelToTableModel::modelRowsAboutToBeRemoved(const QModelIndex & parent, int start, int end)
798{
799 ASSERT_CONSISTENCY();
800 enableSignalAggregation();
801 if (parent == m_rootIndex || childrenVisible(index: parent)) {
802 const QModelIndex &smi = m_model->index(row: start, column: 0, parent);
803 int startIndex = itemIndex(index: smi);
804 const QModelIndex &emi = m_model->index(row: end, column: 0, parent);
805 int endIndex = -1;
806 if (isExpanded(index: emi)) {
807 int rowCount = m_model->rowCount(parent: emi);
808 if (rowCount > 0) {
809 const QModelIndex &idx = m_model->index(row: rowCount - 1, column: 0, parent: emi);
810 endIndex = lastChildIndex(index: idx);
811 }
812 }
813 if (endIndex == -1)
814 endIndex = itemIndex(index: emi);
815
816 removeVisibleRows(startIndex, endIndex);
817 }
818
819 for (int r = start; r <= end; r++) {
820 const QModelIndex &cmi = m_model->index(row: r, column: 0, parent);
821 m_expandedItems.remove(value: cmi);
822 }
823}
824
825void QQmlTreeModelToTableModel::modelRowsRemoved(const QModelIndex & parent, int start, int end)
826{
827 Q_UNUSED(start)
828 Q_UNUSED(end)
829 int parentRow = itemIndex(index: parent);
830 if (parentRow >= 0)
831 queueDataChanged(top: parentRow, bottom: parentRow, roles: {HasChildrenRole});
832 disableSignalAggregation();
833 ASSERT_CONSISTENCY();
834}
835
836void QQmlTreeModelToTableModel::modelRowsAboutToBeMoved(const QModelIndex & sourceParent, int sourceStart, int sourceEnd, const QModelIndex & destinationParent, int destinationRow)
837{
838 ASSERT_CONSISTENCY();
839 enableSignalAggregation();
840 m_visibleRowsMoved = false;
841 if (!childrenVisible(index: sourceParent))
842 return; // Do nothing now. See modelRowsMoved() below.
843
844 if (!childrenVisible(index: destinationParent)) {
845 modelRowsAboutToBeRemoved(parent: sourceParent, start: sourceStart, end: sourceEnd);
846 /* If the destination parent has no children, we'll need to
847 * report a change on the HasChildrenRole */
848 if (isVisible(index: destinationParent) && m_model->rowCount(parent: destinationParent) == 0) {
849 const int parentRow = itemIndex(index: destinationParent);
850 queueDataChanged(top: parentRow, bottom: parentRow, roles: {HasChildrenRole});
851 }
852 } else {
853 int depthDifference = -1;
854 if (destinationParent.isValid()) {
855 int destParentIndex = itemIndex(index: destinationParent);
856 depthDifference = m_items.at(i: destParentIndex).depth;
857 }
858 if (sourceParent.isValid()) {
859 int sourceParentIndex = itemIndex(index: sourceParent);
860 depthDifference -= m_items.at(i: sourceParentIndex).depth;
861 } else {
862 depthDifference++;
863 }
864
865 int startIndex = itemIndex(index: m_model->index(row: sourceStart, column: 0, parent: sourceParent));
866 const QModelIndex &emi = m_model->index(row: sourceEnd, column: 0, parent: sourceParent);
867 int endIndex = -1;
868 if (isExpanded(index: emi)) {
869 int rowCount = m_model->rowCount(parent: emi);
870 if (rowCount > 0)
871 endIndex = lastChildIndex(index: m_model->index(row: rowCount - 1, column: 0, parent: emi));
872 }
873 if (endIndex == -1)
874 endIndex = itemIndex(index: emi);
875
876 int destIndex = -1;
877 if (destinationRow == m_model->rowCount(parent: destinationParent)) {
878 const QModelIndex &emi = m_model->index(row: destinationRow - 1, column: 0, parent: destinationParent);
879 destIndex = lastChildIndex(index: emi) + 1;
880 } else {
881 destIndex = itemIndex(index: m_model->index(row: destinationRow, column: 0, parent: destinationParent));
882 }
883
884 int totalMovedCount = endIndex - startIndex + 1;
885
886 /* This beginMoveRows() is matched by a endMoveRows() in the
887 * modelRowsMoved() method below. */
888 m_visibleRowsMoved = startIndex != destIndex &&
889 beginMoveRows(sourceParent: QModelIndex(), sourceFirst: startIndex, sourceLast: endIndex, destinationParent: QModelIndex(), destinationRow: destIndex);
890
891 const QList<TreeItem> &buffer = m_items.mid(pos: startIndex, len: totalMovedCount);
892 int bufferCopyOffset;
893 if (destIndex > endIndex) {
894 for (int i = endIndex + 1; i < destIndex; i++) {
895 m_items.swapItemsAt(i, j: i - totalMovedCount); // Fast move from 1st to 2nd position
896 }
897 bufferCopyOffset = destIndex - totalMovedCount;
898 } else {
899 // NOTE: we will not enter this loop if startIndex == destIndex
900 for (int i = startIndex - 1; i >= destIndex; i--) {
901 m_items.swapItemsAt(i, j: i + totalMovedCount); // Fast move from 1st to 2nd position
902 }
903 bufferCopyOffset = destIndex;
904 }
905 for (int i = 0; i < buffer.size(); i++) {
906 TreeItem item = buffer.at(i);
907 item.depth += depthDifference;
908 m_items.replace(i: bufferCopyOffset + i, t: item);
909 }
910
911 /* If both source and destination items are visible, the indexes of
912 * all the items in between will change. If they share the same
913 * parent, then this is all; however, if they belong to different
914 * parents, their bottom siblings will also get displaced, so their
915 * index also needs to be updated.
916 * Given that the bottom siblings of the top moved elements are
917 * already included in the update (since they lie between the
918 * source and the dest elements), we only need to worry about the
919 * siblings of the bottom moved element.
920 */
921 const int top = qMin(a: startIndex, b: bufferCopyOffset);
922 int bottom = qMax(a: endIndex, b: bufferCopyOffset + totalMovedCount - 1);
923 if (sourceParent != destinationParent) {
924 const QModelIndex &bottomParent =
925 bottom == endIndex ? sourceParent : destinationParent;
926
927 const int rowCount = m_model->rowCount(parent: bottomParent);
928 if (rowCount > 0)
929 bottom = qMax(a: bottom, b: lastChildIndex(index: m_model->index(row: rowCount - 1, column: 0, parent: bottomParent)));
930 }
931 queueDataChanged(top, bottom, roles: {ModelIndexRole});
932
933 if (depthDifference != 0)
934 queueDataChanged(top: bufferCopyOffset, bottom: bufferCopyOffset + totalMovedCount - 1, roles: {DepthRole});
935 }
936}
937
938void QQmlTreeModelToTableModel::modelRowsMoved(const QModelIndex & sourceParent, int sourceStart, int sourceEnd, const QModelIndex & destinationParent, int destinationRow)
939{
940 if (!childrenVisible(index: sourceParent)) {
941 modelRowsInserted(parent: destinationParent, start: destinationRow, end: destinationRow + sourceEnd - sourceStart);
942 } else if (!childrenVisible(index: destinationParent)) {
943 modelRowsRemoved(parent: sourceParent, start: sourceStart, end: sourceEnd);
944 }
945
946 if (m_visibleRowsMoved)
947 endMoveRows();
948
949 if (isVisible(index: sourceParent) && m_model->rowCount(parent: sourceParent) == 0) {
950 int parentRow = itemIndex(index: sourceParent);
951 collapseRow(n: parentRow);
952 queueDataChanged(top: parentRow, bottom: parentRow, roles: {ExpandedRole, HasChildrenRole});
953 }
954
955 disableSignalAggregation();
956
957 ASSERT_CONSISTENCY();
958}
959
960void QQmlTreeModelToTableModel::modelColumnsAboutToBeInserted(const QModelIndex & parent, int start, int end)
961{
962 Q_UNUSED(parent);
963 beginInsertColumns(parent: {}, first: start, last: end);
964}
965
966void QQmlTreeModelToTableModel::modelColumnsAboutToBeRemoved(const QModelIndex & parent, int start, int end)
967{
968 Q_UNUSED(parent);
969 beginRemoveColumns(parent: {}, first: start, last: end);
970}
971
972void QQmlTreeModelToTableModel::modelColumnsInserted(const QModelIndex & parent, int start, int end)
973{
974 Q_UNUSED(parent);
975 Q_UNUSED(start);
976 Q_UNUSED(end);
977 endInsertColumns();
978 m_items.clear();
979 showModelTopLevelItems();
980 ASSERT_CONSISTENCY();
981}
982
983void QQmlTreeModelToTableModel::modelColumnsRemoved(const QModelIndex & parent, int start, int end)
984{
985 Q_UNUSED(parent);
986 Q_UNUSED(start);
987 Q_UNUSED(end);
988 endRemoveColumns();
989 m_items.clear();
990 showModelTopLevelItems();
991 ASSERT_CONSISTENCY();
992}
993
994void QQmlTreeModelToTableModel::dump() const
995{
996 if (!m_model)
997 return;
998 int count = m_items.size();
999 if (count == 0)
1000 return;
1001 int countWidth = floor(x: log10(x: double(count))) + 1;
1002 qInfo() << "Dumping" << this;
1003 for (int i = 0; i < count; i++) {
1004 const TreeItem &item = m_items.at(i);
1005 bool hasChildren = m_model->hasChildren(parent: item.index);
1006 int children = m_model->rowCount(parent: item.index);
1007 qInfo().noquote().nospace()
1008 << QStringLiteral("%1 ").arg(a: i, fieldWidth: countWidth) << QString(4 * item.depth, QChar::fromLatin1(c: '.'))
1009 << QLatin1String(!hasChildren ? ".. " : item.expanded ? " v " : " > ")
1010 << item.index << children;
1011 }
1012}
1013
1014bool QQmlTreeModelToTableModel::testConsistency(bool dumpOnFail) const
1015{
1016 if (!m_model) {
1017 if (!m_items.isEmpty()) {
1018 qWarning() << "Model inconsistency: No model but stored visible items";
1019 return false;
1020 }
1021 if (!m_expandedItems.isEmpty()) {
1022 qWarning() << "Model inconsistency: No model but stored expanded items";
1023 return false;
1024 }
1025 return true;
1026 }
1027 QModelIndex parent = m_rootIndex;
1028 QStack<QModelIndex> ancestors;
1029 QModelIndex idx = m_model->index(row: 0, column: 0, parent);
1030 for (int i = 0; i < m_items.size(); i++) {
1031 bool isConsistent = true;
1032 const TreeItem &item = m_items.at(i);
1033 if (item.index != idx) {
1034 qWarning() << "QModelIndex inconsistency" << i << item.index;
1035 qWarning() << " expected" << idx;
1036 isConsistent = false;
1037 }
1038 if (item.index.parent() != parent) {
1039 qWarning() << "Parent inconsistency" << i << item.index;
1040 qWarning() << " stored index parent" << item.index.parent() << "model parent" << parent;
1041 isConsistent = false;
1042 }
1043 if (item.depth != ancestors.size()) {
1044 qWarning() << "Depth inconsistency" << i << item.index;
1045 qWarning() << " item depth" << item.depth << "ancestors stack" << ancestors.size();
1046 isConsistent = false;
1047 }
1048 if (item.expanded && !m_expandedItems.contains(value: item.index)) {
1049 qWarning() << "Expanded inconsistency" << i << item.index;
1050 qWarning() << " set" << m_expandedItems.contains(value: item.index) << "item" << item.expanded;
1051 isConsistent = false;
1052 }
1053 if (!isConsistent) {
1054 if (dumpOnFail)
1055 dump();
1056 return false;
1057 }
1058 QModelIndex firstChildIndex;
1059 if (item.expanded)
1060 firstChildIndex = m_model->index(row: 0, column: 0, parent: idx);
1061 if (firstChildIndex.isValid()) {
1062 ancestors.push(t: parent);
1063 parent = idx;
1064 idx = m_model->index(row: 0, column: 0, parent);
1065 } else {
1066 while (idx.row() == m_model->rowCount(parent) - 1) {
1067 if (ancestors.isEmpty())
1068 break;
1069 idx = parent;
1070 parent = ancestors.pop();
1071 }
1072 idx = m_model->index(row: idx.row() + 1, column: 0, parent);
1073 }
1074 }
1075
1076 return true;
1077}
1078
1079void QQmlTreeModelToTableModel::enableSignalAggregation() {
1080 m_signalAggregatorStack++;
1081}
1082
1083void QQmlTreeModelToTableModel::disableSignalAggregation() {
1084 m_signalAggregatorStack--;
1085 Q_ASSERT(m_signalAggregatorStack >= 0);
1086 if (m_signalAggregatorStack == 0) {
1087 emitQueuedSignals();
1088 }
1089}
1090
1091void QQmlTreeModelToTableModel::queueDataChanged(int top, int bottom,
1092 std::initializer_list<int> roles)
1093{
1094 if (isAggregatingSignals())
1095 m_queuedDataChanged.append(t: DataChangedParams { .top: top, .bottom: bottom, .roles: roles });
1096 else
1097 emit dataChanged(topLeft: index(row: top, column: 0), bottomRight: index(row: bottom, column: 0), roles);
1098}
1099
1100void QQmlTreeModelToTableModel::emitQueuedSignals()
1101{
1102 QVarLengthArray<DataChangedParams> combinedUpdates;
1103 /* First, iterate through the queued updates and merge the overlapping ones
1104 * to reduce the number of updates.
1105 * We don't merge adjacent updates, because they are typically filed with a
1106 * different role (a parent row is next to its children).
1107 */
1108 for (const DataChangedParams &dataChange : std::as_const(t&: m_queuedDataChanged)) {
1109 const int startRow = dataChange.top;
1110 const int endRow = dataChange.bottom;
1111 bool merged = false;
1112 for (DataChangedParams &combined : combinedUpdates) {
1113 int combinedStartRow = combined.top;
1114 int combinedEndRow = combined.bottom;
1115 if ((startRow <= combinedStartRow && endRow >= combinedStartRow) ||
1116 (startRow <= combinedEndRow && endRow >= combinedEndRow)) {
1117 if (startRow < combinedStartRow) {
1118 combined.top = dataChange.top;
1119 }
1120 if (endRow > combinedEndRow) {
1121 combined.bottom = dataChange.bottom;
1122 }
1123 for (int role : dataChange.roles) {
1124 if (!combined.roles.contains(t: role))
1125 combined.roles.append(t: role);
1126 }
1127 merged = true;
1128 break;
1129 }
1130 }
1131 if (!merged) {
1132 combinedUpdates.append(t: dataChange);
1133 }
1134 }
1135
1136 /* Finally, emit the dataChanged signals */
1137 for (const DataChangedParams &dataChange : combinedUpdates) {
1138 const QModelIndex topLeft = index(row: dataChange.top, column: 0);
1139 const QModelIndex bottomRight = index(row: dataChange.bottom, column: 0);
1140 emit dataChanged(topLeft, bottomRight, roles: {dataChange.roles.begin(), dataChange.roles.end()});
1141 }
1142 m_queuedDataChanged.clear();
1143}
1144
1145QT_END_NAMESPACE
1146
1147#include "moc_qqmltreemodeltotablemodel_p_p.cpp"
1148

source code of qtdeclarative/src/qmlmodels/qqmltreemodeltotablemodel.cpp