Fix includes
[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   // since we are called asynchronously we have to recheck if the item in question still has no childs
131   if(removeEvent->child()->childCount())
132     return;
133
134   removeChild(childRow);
135 }
136
137 bool AbstractTreeItem::reParent(AbstractTreeItem *newParent) {
138   // currently we support only re parenting if the child that's about to be
139   // adopted does not have any children itself.
140   if(childCount() != 0) {
141     qDebug() << "AbstractTreeItem::reParent(): cannot reparent"  << this << "with children.";
142     return false;
143   }
144
145   int oldRow = row();
146   if(oldRow == -1)
147     return false;
148
149   emit parent()->beginRemoveChilds(oldRow, oldRow);
150   parent()->_childItems.removeAt(oldRow);
151   emit parent()->endRemoveChilds();
152
153   AbstractTreeItem *oldParent = parent();
154   setParent(newParent);
155
156   bool success = newParent->newChild(this);
157   if(!success)
158     qWarning() << "AbstractTreeItem::reParent(): failed to attach to new parent after removing from old parent! this:" << this << "new parent:" << newParent;
159
160   if(oldParent)
161     oldParent->checkForDeletion();
162
163   return success;
164 }
165
166 AbstractTreeItem *AbstractTreeItem::child(int row) const {
167   if(childCount() <= row)
168     return 0;
169   else
170     return _childItems[row];
171 }
172
173 int AbstractTreeItem::childCount(int column) const {
174   if(column > 0)
175     return 0;
176   else
177     return _childItems.count();
178 }
179
180 int AbstractTreeItem::row() const {
181   if(!parent()) {
182     qWarning() << "AbstractTreeItem::row():" << this << "has no parent AbstractTreeItem as it's parent! parent is" << QObject::parent();
183     return -1;
184   }
185
186   int row_ = parent()->_childItems.indexOf(const_cast<AbstractTreeItem *>(this));
187   if(row_ == -1)
188     qWarning() << "AbstractTreeItem::row():" << this << "is not in the child list of" << QObject::parent();
189   return row_;
190 }
191
192 void AbstractTreeItem::dumpChildList() {
193   qDebug() << "==== Childlist for Item:" << this << "====";
194   if(childCount() > 0) {
195     AbstractTreeItem *child;
196     QList<AbstractTreeItem *>::const_iterator childIter = _childItems.constBegin();
197     while(childIter != _childItems.constEnd()) {
198       child = *childIter;
199       qDebug() << "Row:" << child->row() << child << child->data(0, Qt::DisplayRole);
200       childIter++;
201     }
202   }
203   qDebug() << "==== End Of Childlist ====";
204 }
205
206 /*****************************************
207  * SimpleTreeItem
208  *****************************************/
209 SimpleTreeItem::SimpleTreeItem(const QList<QVariant> &data, AbstractTreeItem *parent)
210   : AbstractTreeItem(parent),
211     _itemData(data)
212 {
213 }
214
215 SimpleTreeItem::~SimpleTreeItem() {
216 }
217
218 QVariant SimpleTreeItem::data(int column, int role) const {
219   if(column >= columnCount() || role != Qt::DisplayRole)
220     return QVariant();
221   else
222     return _itemData[column];
223 }
224
225 bool SimpleTreeItem::setData(int column, const QVariant &value, int role) {
226   if(column > columnCount() || role != Qt::DisplayRole)
227     return false;
228
229   if(column == columnCount())
230     _itemData.append(value);
231   else
232     _itemData[column] = value;
233
234   emit dataChanged(column);
235   return true;
236 }
237
238 int SimpleTreeItem::columnCount() const {
239   return _itemData.count();
240 }
241
242 /*****************************************
243  * PropertyMapItem
244  *****************************************/
245 PropertyMapItem::PropertyMapItem(const QStringList &propertyOrder, AbstractTreeItem *parent)
246   : AbstractTreeItem(parent),
247     _propertyOrder(propertyOrder)
248 {
249 }
250
251 PropertyMapItem::PropertyMapItem(AbstractTreeItem *parent)
252   : AbstractTreeItem(parent),
253     _propertyOrder(QStringList())
254 {
255 }
256
257
258 PropertyMapItem::~PropertyMapItem() {
259 }
260
261 QVariant PropertyMapItem::data(int column, int role) const {
262   if(column >= columnCount())
263     return QVariant();
264
265   switch(role) {
266   case Qt::ToolTipRole:
267     return toolTip(column);
268   case Qt::DisplayRole:
269   case TreeModel::SortRole:  // fallthrough, since SortRole should default to DisplayRole
270     return property(_propertyOrder[column].toAscii());
271   default:
272     return QVariant();
273   }
274
275 }
276
277 bool PropertyMapItem::setData(int column, const QVariant &value, int role) {
278   if(column >= columnCount() || role != Qt::DisplayRole)
279     return false;
280
281   emit dataChanged(column);
282   return setProperty(_propertyOrder[column].toAscii(), value);
283 }
284
285 int PropertyMapItem::columnCount() const {
286   return _propertyOrder.count();
287 }
288
289 void PropertyMapItem::appendProperty(const QString &property) {
290   _propertyOrder << property;
291 }
292
293
294
295 /*****************************************
296  * TreeModel
297  *****************************************/
298 TreeModel::TreeModel(const QList<QVariant> &data, QObject *parent)
299   : QAbstractItemModel(parent),
300     _childStatus(QModelIndex(), 0, 0, 0),
301     _aboutToRemoveOrInsert(false)
302 {
303   rootItem = new SimpleTreeItem(data, 0);
304   connectItem(rootItem);
305
306   if(Quassel::isOptionSet("debugmodel")) {
307     connect(this, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)),
308             this, SLOT(debug_rowsAboutToBeInserted(const QModelIndex &, int, int)));
309     connect(this, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
310             this, SLOT(debug_rowsAboutToBeRemoved(const QModelIndex &, int, int)));
311     connect(this, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
312             this, SLOT(debug_rowsInserted(const QModelIndex &, int, int)));
313     connect(this, SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
314             this, SLOT(debug_rowsRemoved(const QModelIndex &, int, int)));
315     connect(this, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),
316             this, SLOT(debug_dataChanged(const QModelIndex &, const QModelIndex &)));
317   }
318 }
319
320 TreeModel::~TreeModel() {
321   delete rootItem;
322 }
323
324 QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const {
325   if(row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent))
326     return QModelIndex();
327
328   AbstractTreeItem *parentItem;
329
330   if(!parent.isValid())
331     parentItem = rootItem;
332   else
333     parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
334
335   AbstractTreeItem *childItem = parentItem->child(row);
336
337   if(childItem)
338     return createIndex(row, column, childItem);
339   else
340     return QModelIndex();
341 }
342
343 QModelIndex TreeModel::indexByItem(AbstractTreeItem *item) const {
344   if(item == 0) {
345     qWarning() << "TreeModel::indexByItem(AbstractTreeItem *item) received NULL-Pointer";
346     return QModelIndex();
347   }
348
349   if(item == rootItem)
350     return QModelIndex();
351   else
352     return createIndex(item->row(), 0, item);
353 }
354
355 QModelIndex TreeModel::parent(const QModelIndex &index) const {
356   if(!index.isValid()) {
357     // ModelTest does this
358     // qWarning() << "TreeModel::parent(): has been asked for the rootItems Parent!";
359     return QModelIndex();
360   }
361
362   AbstractTreeItem *childItem = static_cast<AbstractTreeItem *>(index.internalPointer());
363   AbstractTreeItem *parentItem = childItem->parent();
364
365   Q_ASSERT(parentItem);
366   if(parentItem == rootItem)
367     return QModelIndex();
368
369   return createIndex(parentItem->row(), 0, parentItem);
370 }
371
372 int TreeModel::rowCount(const QModelIndex &parent) const {
373   AbstractTreeItem *parentItem;
374   if(!parent.isValid())
375     parentItem = rootItem;
376   else
377     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
378
379   return parentItem->childCount(parent.column());
380 }
381
382 int TreeModel::columnCount(const QModelIndex &parent) const {
383   Q_UNUSED(parent)
384   return rootItem->columnCount();
385   // since there the Qt Views don't draw more columns than the header has columns
386   // we can be lazy and simply return the count of header columns
387   // actually this gives us more freedom cause we don't have to ensure that a rows parent
388   // has equal or more columns than that row
389
390 //   AbstractTreeItem *parentItem;
391 //   if(!parent.isValid())
392 //     parentItem = rootItem;
393 //   else
394 //     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
395 //   return parentItem->columnCount();
396 }
397
398 QVariant TreeModel::data(const QModelIndex &index, int role) const {
399   if(!index.isValid())
400     return QVariant();
401
402   AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
403   return item->data(index.column(), role);
404 }
405
406 bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role) {
407   if(!index.isValid())
408     return false;
409
410   AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
411   return item->setData(index.column(), value, role);
412 }
413
414 Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const {
415   if(!index.isValid()) {
416     return rootItem->flags() & Qt::ItemIsDropEnabled;
417   } else {
418     AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
419     return item->flags();
420   }
421 }
422
423 QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const {
424   if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
425     return rootItem->data(section, role);
426   else
427     return QVariant();
428 }
429
430 void TreeModel::itemDataChanged(int column) {
431   AbstractTreeItem *item = qobject_cast<AbstractTreeItem *>(sender());
432   QModelIndex leftIndex, rightIndex;
433
434   if(item == rootItem)
435     return;
436
437   if(column == -1) {
438     leftIndex = createIndex(item->row(), 0, item);
439     rightIndex = createIndex(item->row(), item->columnCount() - 1, item);
440   } else {
441     leftIndex = createIndex(item->row(), column, item);
442     rightIndex = leftIndex;
443   }
444
445   emit dataChanged(leftIndex, rightIndex);
446 }
447
448 void TreeModel::connectItem(AbstractTreeItem *item) {
449   connect(item, SIGNAL(dataChanged(int)),
450           this, SLOT(itemDataChanged(int)));
451
452   connect(item, SIGNAL(beginAppendChilds(int, int)),
453           this, SLOT(beginAppendChilds(int, int)));
454   connect(item, SIGNAL(endAppendChilds()),
455           this, SLOT(endAppendChilds()));
456
457   connect(item, SIGNAL(beginRemoveChilds(int, int)),
458           this, SLOT(beginRemoveChilds(int, int)));
459   connect(item, SIGNAL(endRemoveChilds()),
460           this, SLOT(endRemoveChilds()));
461 }
462
463 void TreeModel::beginAppendChilds(int firstRow, int lastRow) {
464   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
465   if(!parentItem) {
466     qWarning() << "TreeModel::beginAppendChilds(): cannot append Children to unknown parent";
467     return;
468   }
469
470   QModelIndex parent = indexByItem(parentItem);
471   Q_ASSERT(!_aboutToRemoveOrInsert);
472
473   _aboutToRemoveOrInsert = true;
474   _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
475   beginInsertRows(parent, firstRow, lastRow);
476 }
477
478 void TreeModel::endAppendChilds() {
479   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
480   if(!parentItem) {
481     qWarning() << "TreeModel::endAppendChilds(): cannot append Children to unknown parent";
482     return;
483   }
484   Q_ASSERT(_aboutToRemoveOrInsert);
485   ChildStatus cs = _childStatus;
486   QModelIndex parent = indexByItem(parentItem);
487   Q_ASSERT(cs.parent == parent);
488   Q_ASSERT(rowCount(parent) == cs.childCount + cs.end - cs.start + 1);
489
490   _aboutToRemoveOrInsert = false;
491   for(int i = cs.start; i <= cs.end; i++) {
492     connectItem(parentItem->child(i));
493   }
494   endInsertRows();
495 }
496
497 void TreeModel::beginRemoveChilds(int firstRow, int lastRow) {
498   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
499   if(!parentItem) {
500     qWarning() << "TreeModel::beginRemoveChilds(): cannot append Children to unknown parent";
501     return;
502   }
503
504   for(int i = firstRow; i <= lastRow; i++) {
505     disconnect(parentItem->child(i), 0, this, 0);
506   }
507
508   // consitency checks
509   QModelIndex parent = indexByItem(parentItem);
510   Q_ASSERT(firstRow <= lastRow);
511   Q_ASSERT(parentItem->childCount() > lastRow);
512   Q_ASSERT(!_aboutToRemoveOrInsert);
513   _aboutToRemoveOrInsert = true;
514   _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
515
516   beginRemoveRows(parent, firstRow, lastRow);
517 }
518
519 void TreeModel::endRemoveChilds() {
520   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
521   if(!parentItem) {
522     qWarning() << "TreeModel::endRemoveChilds(): cannot remove Children from unknown parent";
523     return;
524   }
525
526   // concistency checks
527   Q_ASSERT(_aboutToRemoveOrInsert);
528   ChildStatus cs = _childStatus;
529   QModelIndex parent = indexByItem(parentItem);
530   Q_ASSERT(cs.parent == parent);
531   Q_ASSERT(rowCount(parent) == cs.childCount - cs.end + cs.start - 1);
532   _aboutToRemoveOrInsert = false;
533
534   endRemoveRows();
535 }
536
537 void TreeModel::clear() {
538   rootItem->removeAllChilds();
539 }
540
541 void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end) {
542   qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
543 }
544
545 void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
546   AbstractTreeItem *parentItem;
547   parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
548   if(!parentItem)
549     parentItem = rootItem;
550   qDebug() << "debug_rowsAboutToBeRemoved" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
551
552   QModelIndex child;
553   for(int i = end; i >= start; i--) {
554     child = parent.child(i, 0);
555     Q_ASSERT(parentItem->child(i));
556     qDebug() << ">>>" << i << child << child.data().toString();
557   }
558 }
559
560 void TreeModel::debug_rowsInserted(const QModelIndex &parent, int start, int end) {
561   AbstractTreeItem *parentItem;
562   parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
563   if(!parentItem)
564     parentItem = rootItem;
565   qDebug() << "debug_rowsInserted:" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
566
567   QModelIndex child;
568   for(int i = start; i <= end; i++) {
569     child = parent.child(i, 0);
570     Q_ASSERT(parentItem->child(i));
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 }