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