fa66ba60552a5920f9053c85b0857661a05b7931
[quassel.git] / src / client / treemodel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "treemodel.h"
22
23 #include <QCoreApplication>
24 #include <QDebug>
25
26 #include "quassel.h"
27
28 class RemoveChildLaterEvent : public QEvent
29 {
30 public:
31     RemoveChildLaterEvent(AbstractTreeItem *child) : QEvent(QEvent::User), _child(child) {};
32     inline AbstractTreeItem *child() { return _child; }
33 private:
34     AbstractTreeItem *_child;
35 };
36
37
38 /*****************************************
39  *  Abstract Items of a TreeModel
40  *****************************************/
41 AbstractTreeItem::AbstractTreeItem(AbstractTreeItem *parent)
42     : QObject(parent),
43     _flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled),
44     _treeItemFlags(nullptr)
45 {
46 }
47
48
49 bool AbstractTreeItem::newChild(AbstractTreeItem *item)
50 {
51     int newRow = childCount();
52     emit beginAppendChilds(newRow, newRow);
53     _childItems.append(item);
54     emit endAppendChilds();
55     return true;
56 }
57
58
59 bool AbstractTreeItem::newChilds(const QList<AbstractTreeItem *> &items)
60 {
61     if (items.isEmpty())
62         return false;
63
64     int nextRow = childCount();
65     int lastRow = nextRow + items.count() - 1;
66
67     emit beginAppendChilds(nextRow, lastRow);
68     _childItems << items;
69     emit endAppendChilds();
70
71     return true;
72 }
73
74
75 bool AbstractTreeItem::removeChild(int row)
76 {
77     if (row < 0 || childCount() <= row)
78         return false;
79
80     child(row)->removeAllChilds();
81     emit beginRemoveChilds(row, row);
82     AbstractTreeItem *treeitem = _childItems.takeAt(row);
83     delete treeitem;
84     emit endRemoveChilds();
85
86     checkForDeletion();
87
88     return true;
89 }
90
91
92 void AbstractTreeItem::removeAllChilds()
93 {
94     const int numChilds = childCount();
95
96     if (numChilds == 0)
97         return;
98
99     AbstractTreeItem *child;
100
101     QList<AbstractTreeItem *>::iterator childIter;
102
103     childIter = _childItems.begin();
104     while (childIter != _childItems.end()) {
105         child = *childIter;
106         child->setTreeItemFlags(nullptr); // disable self deletion, as this would only fuck up consitency and the child gets deleted anyways
107         child->removeAllChilds();
108         ++childIter;
109     }
110
111     emit beginRemoveChilds(0, numChilds - 1);
112     childIter = _childItems.begin();
113     while (childIter != _childItems.end()) {
114         child = *childIter;
115         childIter = _childItems.erase(childIter);
116         delete child;
117     }
118     emit endRemoveChilds();
119
120     checkForDeletion();
121 }
122
123
124 void AbstractTreeItem::removeChildLater(AbstractTreeItem *child)
125 {
126     Q_ASSERT(child);
127     QCoreApplication::postEvent(this, new RemoveChildLaterEvent(child));
128 }
129
130
131 void AbstractTreeItem::customEvent(QEvent *event)
132 {
133     if (event->type() != QEvent::User)
134         return;
135
136     event->accept();
137
138     RemoveChildLaterEvent *removeEvent = static_cast<RemoveChildLaterEvent *>(event);
139     int childRow = _childItems.indexOf(removeEvent->child());
140     if (childRow == -1)
141         return;
142
143     // since we are called asynchronously we have to recheck if the item in question still has no childs
144     if (removeEvent->child()->childCount())
145         return;
146
147     removeChild(childRow);
148 }
149
150
151 bool AbstractTreeItem::reParent(AbstractTreeItem *newParent)
152 {
153     // currently we support only re parenting if the child that's about to be
154     // adopted does not have any children itself.
155     if (childCount() != 0) {
156         qDebug() << "AbstractTreeItem::reParent(): cannot reparent"  << this << "with children.";
157         return false;
158     }
159
160     int oldRow = row();
161     if (oldRow == -1)
162         return false;
163
164     emit parent()->beginRemoveChilds(oldRow, oldRow);
165     parent()->_childItems.removeAt(oldRow);
166     emit parent()->endRemoveChilds();
167
168     AbstractTreeItem *oldParent = parent();
169     setParent(newParent);
170
171     bool success = newParent->newChild(this);
172     if (!success)
173         qWarning() << "AbstractTreeItem::reParent(): failed to attach to new parent after removing from old parent! this:" << this << "new parent:" << newParent;
174
175     if (oldParent)
176         oldParent->checkForDeletion();
177
178     return success;
179 }
180
181
182 AbstractTreeItem *AbstractTreeItem::child(int row) const
183 {
184     if (childCount() <= row)
185         return nullptr;
186     else
187         return _childItems[row];
188 }
189
190
191 int AbstractTreeItem::childCount(int column) const
192 {
193     if (column > 0)
194         return 0;
195     else
196         return _childItems.count();
197 }
198
199
200 int AbstractTreeItem::row() const
201 {
202     if (!parent()) {
203         qWarning() << "AbstractTreeItem::row():" << this << "has no parent AbstractTreeItem as it's parent! parent is" << QObject::parent();
204         return -1;
205     }
206
207     int row_ = parent()->_childItems.indexOf(const_cast<AbstractTreeItem *>(this));
208     if (row_ == -1)
209         qWarning() << "AbstractTreeItem::row():" << this << "is not in the child list of" << QObject::parent();
210     return row_;
211 }
212
213
214 void AbstractTreeItem::dumpChildList()
215 {
216     qDebug() << "==== Childlist for Item:" << this << "====";
217     if (childCount() > 0) {
218         AbstractTreeItem *child;
219         QList<AbstractTreeItem *>::const_iterator childIter = _childItems.constBegin();
220         while (childIter != _childItems.constEnd()) {
221             child = *childIter;
222             qDebug() << "Row:" << child->row() << child << child->data(0, Qt::DisplayRole);
223             ++childIter;
224         }
225     }
226     qDebug() << "==== End Of Childlist ====";
227 }
228
229
230 /*****************************************
231  * SimpleTreeItem
232  *****************************************/
233 SimpleTreeItem::SimpleTreeItem(const QList<QVariant> &data, AbstractTreeItem *parent)
234     : AbstractTreeItem(parent),
235     _itemData(data)
236 {
237 }
238
239
240 SimpleTreeItem::~SimpleTreeItem()
241 {
242 }
243
244
245 QVariant SimpleTreeItem::data(int column, int role) const
246 {
247     if (column >= columnCount() || role != Qt::DisplayRole)
248         return QVariant();
249     else
250         return _itemData[column];
251 }
252
253
254 bool SimpleTreeItem::setData(int column, const QVariant &value, int role)
255 {
256     if (column > columnCount() || role != Qt::DisplayRole)
257         return false;
258
259     if (column == columnCount())
260         _itemData.append(value);
261     else
262         _itemData[column] = value;
263
264     emit dataChanged(column);
265     return true;
266 }
267
268
269 int SimpleTreeItem::columnCount() const
270 {
271     return _itemData.count();
272 }
273
274
275 /*****************************************
276  * PropertyMapItem
277  *****************************************/
278 PropertyMapItem::PropertyMapItem(AbstractTreeItem *parent)
279     : AbstractTreeItem(parent)
280 {
281 }
282
283
284 QVariant PropertyMapItem::data(int column, int role) const
285 {
286     if (column >= columnCount())
287         return QVariant();
288
289     switch (role) {
290     case Qt::ToolTipRole:
291         return toolTip(column);
292     case Qt::DisplayRole:
293     case TreeModel::SortRole: // fallthrough, since SortRole should default to DisplayRole
294         return property(propertyOrder()[column].toLatin1());
295     default:
296         return QVariant();
297     }
298 }
299
300
301 bool PropertyMapItem::setData(int column, const QVariant &value, int role)
302 {
303     if (column >= columnCount() || role != Qt::DisplayRole)
304         return false;
305
306     setProperty(propertyOrder()[column].toLatin1(), value);
307     emit dataChanged(column);
308     return true;
309 }
310
311
312 int PropertyMapItem::columnCount() const
313 {
314     return propertyOrder().count();
315 }
316
317
318 /*****************************************
319  * TreeModel
320  *****************************************/
321 TreeModel::TreeModel(const QList<QVariant> &data, QObject *parent)
322     : QAbstractItemModel(parent),
323     _childStatus(QModelIndex(), 0, 0, 0),
324     _aboutToRemoveOrInsert(false)
325 {
326     rootItem = new SimpleTreeItem(data, nullptr);
327     connectItem(rootItem);
328
329     if (Quassel::isOptionSet("debugmodel")) {
330         connect(this, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)),
331             this, SLOT(debug_rowsAboutToBeInserted(const QModelIndex &, int, int)));
332         connect(this, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
333             this, SLOT(debug_rowsAboutToBeRemoved(const QModelIndex &, int, int)));
334         connect(this, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
335             this, SLOT(debug_rowsInserted(const QModelIndex &, int, int)));
336         connect(this, SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
337             this, SLOT(debug_rowsRemoved(const QModelIndex &, int, int)));
338         connect(this, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),
339             this, SLOT(debug_dataChanged(const QModelIndex &, const QModelIndex &)));
340     }
341 }
342
343
344 TreeModel::~TreeModel()
345 {
346     delete rootItem;
347 }
348
349
350 AbstractTreeItem *TreeModel::root() const
351 {
352     return rootItem;
353 }
354
355
356 QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
357 {
358     if (row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent))
359         return QModelIndex();
360
361     AbstractTreeItem *parentItem;
362
363     if (!parent.isValid())
364         parentItem = rootItem;
365     else
366         parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
367
368     AbstractTreeItem *childItem = parentItem->child(row);
369
370     if (childItem)
371         return createIndex(row, column, childItem);
372     else
373         return QModelIndex();
374 }
375
376
377 QModelIndex TreeModel::indexByItem(AbstractTreeItem *item) const
378 {
379     if (item == nullptr) {
380         qWarning() << "TreeModel::indexByItem(AbstractTreeItem *item) received NULL-Pointer";
381         return QModelIndex();
382     }
383
384     if (item == rootItem)
385         return QModelIndex();
386     else
387         return createIndex(item->row(), 0, item);
388 }
389
390
391 QModelIndex TreeModel::parent(const QModelIndex &index) const
392 {
393     if (!index.isValid()) {
394         // ModelTest does this
395         // qWarning() << "TreeModel::parent(): has been asked for the rootItems Parent!";
396         return QModelIndex();
397     }
398
399     AbstractTreeItem *childItem = static_cast<AbstractTreeItem *>(index.internalPointer());
400     AbstractTreeItem *parentItem = childItem->parent();
401
402     Q_ASSERT(parentItem);
403     if (parentItem == rootItem)
404         return QModelIndex();
405
406     return createIndex(parentItem->row(), 0, parentItem);
407 }
408
409
410 int TreeModel::rowCount(const QModelIndex &parent) const
411 {
412     AbstractTreeItem *parentItem;
413     if (!parent.isValid())
414         parentItem = rootItem;
415     else
416         parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
417
418     return parentItem->childCount(parent.column());
419 }
420
421
422 int TreeModel::columnCount(const QModelIndex &parent) const
423 {
424     Q_UNUSED(parent)
425     return rootItem->columnCount();
426     // since there the Qt Views don't draw more columns than the header has columns
427     // we can be lazy and simply return the count of header columns
428     // actually this gives us more freedom cause we don't have to ensure that a rows parent
429     // has equal or more columns than that row
430
431 //   AbstractTreeItem *parentItem;
432 //   if(!parent.isValid())
433 //     parentItem = rootItem;
434 //   else
435 //     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
436 //   return parentItem->columnCount();
437 }
438
439
440 QVariant TreeModel::data(const QModelIndex &index, int role) const
441 {
442     if (!index.isValid())
443         return QVariant();
444
445     AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
446     return item->data(index.column(), role);
447 }
448
449
450 bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
451 {
452     if (!index.isValid())
453         return false;
454
455     AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
456     return item->setData(index.column(), value, role);
457 }
458
459
460 Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
461 {
462     if (!index.isValid()) {
463         return rootItem->flags() & Qt::ItemIsDropEnabled;
464     }
465     else {
466         AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
467         return item->flags();
468     }
469 }
470
471
472 QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
473 {
474     if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
475         return rootItem->data(section, role);
476     else
477         return QVariant();
478 }
479
480
481 void TreeModel::itemDataChanged(int column)
482 {
483     AbstractTreeItem *item = qobject_cast<AbstractTreeItem *>(sender());
484     QModelIndex leftIndex, rightIndex;
485
486     if (item == rootItem)
487         return;
488
489     if (column == -1) {
490         leftIndex = createIndex(item->row(), 0, item);
491         rightIndex = createIndex(item->row(), item->columnCount() - 1, item);
492     }
493     else {
494         leftIndex = createIndex(item->row(), column, item);
495         rightIndex = leftIndex;
496     }
497
498     emit dataChanged(leftIndex, rightIndex);
499 }
500
501
502 void TreeModel::connectItem(AbstractTreeItem *item)
503 {
504     connect(item, SIGNAL(dataChanged(int)),
505         this, SLOT(itemDataChanged(int)));
506
507     connect(item, SIGNAL(beginAppendChilds(int, int)),
508         this, SLOT(beginAppendChilds(int, int)));
509     connect(item, SIGNAL(endAppendChilds()),
510         this, SLOT(endAppendChilds()));
511
512     connect(item, SIGNAL(beginRemoveChilds(int, int)),
513         this, SLOT(beginRemoveChilds(int, int)));
514     connect(item, SIGNAL(endRemoveChilds()),
515         this, SLOT(endRemoveChilds()));
516 }
517
518
519 void TreeModel::beginAppendChilds(int firstRow, int lastRow)
520 {
521     AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
522     if (!parentItem) {
523         qWarning() << "TreeModel::beginAppendChilds(): cannot append Children to unknown parent";
524         return;
525     }
526
527     QModelIndex parent = indexByItem(parentItem);
528     Q_ASSERT(!_aboutToRemoveOrInsert);
529
530     _aboutToRemoveOrInsert = true;
531     _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
532     beginInsertRows(parent, firstRow, lastRow);
533 }
534
535
536 void TreeModel::endAppendChilds()
537 {
538     AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
539     if (!parentItem) {
540         qWarning() << "TreeModel::endAppendChilds(): cannot append Children to unknown parent";
541         return;
542     }
543     Q_ASSERT(_aboutToRemoveOrInsert);
544     ChildStatus cs = _childStatus;
545 #ifndef QT_NO_DEBUG
546     QModelIndex parent = indexByItem(parentItem);
547     Q_ASSERT(cs.parent == parent);
548     Q_ASSERT(rowCount(parent) == cs.childCount + cs.end - cs.start + 1);
549 #endif
550     _aboutToRemoveOrInsert = false;
551     for (int i = cs.start; i <= cs.end; i++) {
552         connectItem(parentItem->child(i));
553     }
554     endInsertRows();
555 }
556
557
558 void TreeModel::beginRemoveChilds(int firstRow, int lastRow)
559 {
560     AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
561     if (!parentItem) {
562         qWarning() << "TreeModel::beginRemoveChilds(): cannot append Children to unknown parent";
563         return;
564     }
565
566     for (int i = firstRow; i <= lastRow; i++) {
567         disconnect(parentItem->child(i), nullptr, this, nullptr);
568     }
569
570     // consitency checks
571     QModelIndex parent = indexByItem(parentItem);
572     Q_ASSERT(firstRow <= lastRow);
573     Q_ASSERT(parentItem->childCount() > lastRow);
574     Q_ASSERT(!_aboutToRemoveOrInsert);
575     _aboutToRemoveOrInsert = true;
576     _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
577
578     beginRemoveRows(parent, firstRow, lastRow);
579 }
580
581
582 void TreeModel::endRemoveChilds()
583 {
584     AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
585     if (!parentItem) {
586         qWarning() << "TreeModel::endRemoveChilds(): cannot remove Children from unknown parent";
587         return;
588     }
589
590     // concistency checks
591     Q_ASSERT(_aboutToRemoveOrInsert);
592 #ifndef QT_NO_DEBUG
593     ChildStatus cs = _childStatus;
594     QModelIndex parent = indexByItem(parentItem);
595     Q_ASSERT(cs.parent == parent);
596     Q_ASSERT(rowCount(parent) == cs.childCount - cs.end + cs.start - 1);
597 #endif
598     _aboutToRemoveOrInsert = false;
599
600     endRemoveRows();
601 }
602
603
604 void TreeModel::clear()
605 {
606     rootItem->removeAllChilds();
607 }
608
609
610 void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
611 {
612     qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
613 }
614
615
616 void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
617 {
618     AbstractTreeItem *parentItem;
619     parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
620     if (!parentItem)
621         parentItem = rootItem;
622     qDebug() << "debug_rowsAboutToBeRemoved" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
623
624     QModelIndex child;
625     for (int i = end; i >= start; i--) {
626         child = parent.child(i, 0);
627         Q_ASSERT(parentItem->child(i));
628         qDebug() << ">>>" << i << child << child.data().toString();
629     }
630 }
631
632
633 void TreeModel::debug_rowsInserted(const QModelIndex &parent, int start, int end)
634 {
635     AbstractTreeItem *parentItem;
636     parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
637     if (!parentItem)
638         parentItem = rootItem;
639     qDebug() << "debug_rowsInserted:" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
640
641     QModelIndex child;
642     for (int i = start; i <= end; i++) {
643         child = parent.child(i, 0);
644         Q_ASSERT(parentItem->child(i));
645         qDebug() << "<<<" << i << child << child.data().toString();
646     }
647 }
648
649
650 void TreeModel::debug_rowsRemoved(const QModelIndex &parent, int start, int end)
651 {
652     qDebug() << "debug_rowsRemoved" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
653 }
654
655
656 void TreeModel::debug_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
657 {
658     qDebug() << "debug_dataChanged" << topLeft << bottomRight;
659     QStringList displayData;
660     for (int row = topLeft.row(); row <= bottomRight.row(); row++) {
661         displayData = QStringList();
662         for (int column = topLeft.column(); column <= bottomRight.column(); column++) {
663             displayData << data(topLeft.sibling(row, column), Qt::DisplayRole).toString();
664         }
665         qDebug() << "  row:" << row << displayData;
666     }
667 }