Quassel no longer gets a nervous breakdown when you select too many buffers - fixes...
[quassel.git] / src / client / treemodel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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(!hasIndex(row, column, 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     qWarning() << "TreeModel::parent(): has been asked for the rootItems Parent!";
354     return QModelIndex();
355   }
356
357   AbstractTreeItem *childItem = static_cast<AbstractTreeItem *>(index.internalPointer());
358   AbstractTreeItem *parentItem = childItem->parent();
359
360   Q_ASSERT(parentItem);
361   if(parentItem == rootItem)
362     return QModelIndex();
363
364   return createIndex(parentItem->row(), 0, parentItem);
365 }
366
367 int TreeModel::rowCount(const QModelIndex &parent) const {
368   AbstractTreeItem *parentItem;
369   if(!parent.isValid())
370     parentItem = rootItem;
371   else
372     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
373
374   return parentItem->childCount(parent.column());
375 }
376
377 int TreeModel::columnCount(const QModelIndex &parent) const {
378   Q_UNUSED(parent)
379   return rootItem->columnCount();
380   // since there the Qt Views don't draw more columns than the header has columns
381   // we can be lazy and simply return the count of header columns
382   // actually this gives us more freedom cause we don't have to ensure that a rows parent
383   // has equal or more columns than that row
384
385 //   AbstractTreeItem *parentItem;
386 //   if(!parent.isValid())
387 //     parentItem = rootItem;
388 //   else
389 //     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
390 //   return parentItem->columnCount();
391 }
392
393 QVariant TreeModel::data(const QModelIndex &index, int role) const {
394   if(!index.isValid())
395     return QVariant();
396
397   AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
398   return item->data(index.column(), role);
399 }
400
401 bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role) {
402   if(!index.isValid())
403     return false;
404
405   AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
406   return item->setData(index.column(), value, role);
407 }
408
409 Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const {
410   if(!index.isValid()) {
411     return rootItem->flags() & Qt::ItemIsDropEnabled;
412   } else {
413     AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
414     return item->flags();
415   }
416 }
417
418 QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const {
419   if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
420     return rootItem->data(section, role);
421   else
422     return QVariant();
423 }
424
425 void TreeModel::itemDataChanged(int column) {
426   AbstractTreeItem *item = qobject_cast<AbstractTreeItem *>(sender());
427   QModelIndex leftIndex, rightIndex;
428
429   if(item == rootItem)
430     return;
431
432   if(column == -1) {
433     leftIndex = createIndex(item->row(), 0, item);
434     rightIndex = createIndex(item->row(), item->columnCount() - 1, item);
435   } else {
436     leftIndex = createIndex(item->row(), column, item);
437     rightIndex = leftIndex;
438   }
439
440   emit dataChanged(leftIndex, rightIndex);
441 }
442
443 void TreeModel::connectItem(AbstractTreeItem *item) {
444   connect(item, SIGNAL(dataChanged(int)),
445           this, SLOT(itemDataChanged(int)));
446
447   connect(item, SIGNAL(beginAppendChilds(int, int)),
448           this, SLOT(beginAppendChilds(int, int)));
449   connect(item, SIGNAL(endAppendChilds()),
450           this, SLOT(endAppendChilds()));
451
452   connect(item, SIGNAL(beginRemoveChilds(int, int)),
453           this, SLOT(beginRemoveChilds(int, int)));
454   connect(item, SIGNAL(endRemoveChilds()),
455           this, SLOT(endRemoveChilds()));
456 }
457
458 void TreeModel::beginAppendChilds(int firstRow, int lastRow) {
459   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
460   if(!parentItem) {
461     qWarning() << "TreeModel::beginAppendChilds(): cannot append Childs to unknown parent";
462     return;
463   }
464
465   QModelIndex parent = indexByItem(parentItem);
466   Q_ASSERT(!_aboutToRemoveOrInsert);
467
468   _aboutToRemoveOrInsert = true;
469   _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
470   beginInsertRows(parent, firstRow, lastRow);
471 }
472
473 void TreeModel::endAppendChilds() {
474   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
475   if(!parentItem) {
476     qWarning() << "TreeModel::endAppendChilds(): cannot append Childs to unknown parent";
477     return;
478   }
479   Q_ASSERT(_aboutToRemoveOrInsert);
480   ChildStatus cs = _childStatus;
481   QModelIndex parent = indexByItem(parentItem);
482   Q_ASSERT(cs.parent == parent);
483   Q_ASSERT(rowCount(parent) == cs.childCount + cs.end - cs.start + 1);
484
485   _aboutToRemoveOrInsert = false;
486   for(int i = cs.start; i <= cs.end; i++) {
487     connectItem(parentItem->child(i));
488   }
489   endInsertRows();
490 }
491
492 void TreeModel::beginRemoveChilds(int firstRow, int lastRow) {
493   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
494   if(!parentItem) {
495     qWarning() << "TreeModel::beginRemoveChilds(): cannot append Childs to unknown parent";
496     return;
497   }
498
499   for(int i = firstRow; i <= lastRow; i++) {
500     disconnect(parentItem->child(i), 0, this, 0);
501   }
502
503   // consitency checks
504   QModelIndex parent = indexByItem(parentItem);
505   Q_ASSERT(firstRow <= lastRow);
506   Q_ASSERT(parentItem->childCount() > lastRow);
507   Q_ASSERT(!_aboutToRemoveOrInsert);
508   _aboutToRemoveOrInsert = true;
509   _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
510
511   beginRemoveRows(parent, firstRow, lastRow);
512 }
513
514 void TreeModel::endRemoveChilds() {
515   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
516   if(!parentItem) {
517     qWarning() << "TreeModel::endRemoveChilds(): cannot remove Childs from unknown parent";
518     return;
519   }
520
521   // concistency checks
522   Q_ASSERT(_aboutToRemoveOrInsert);
523   ChildStatus cs = _childStatus;
524   QModelIndex parent = indexByItem(parentItem);
525   Q_ASSERT(cs.parent == parent);
526   Q_ASSERT(rowCount(parent) == cs.childCount - cs.end + cs.start - 1);
527   _aboutToRemoveOrInsert = false;
528
529   endRemoveRows();
530 }
531
532 void TreeModel::clear() {
533   rootItem->removeAllChilds();
534 }
535
536 void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end) {
537   qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
538 }
539
540 void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
541   AbstractTreeItem *parentItem;
542   parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
543   if(!parentItem)
544     parentItem = rootItem;
545   qDebug() << "debug_rowsAboutToBeRemoved" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
546
547   QModelIndex child;
548   AbstractTreeItem *childItem;
549   for(int i = end; i >= start; i--) {
550     child = parent.child(i, 0);
551     childItem = parentItem->child(i);
552     Q_ASSERT(childItem);
553     qDebug() << ">>>" << i << child << child.data().toString();
554   }
555 }
556
557 void TreeModel::debug_rowsInserted(const QModelIndex &parent, int start, int end) {
558   AbstractTreeItem *parentItem;
559   parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
560   if(!parentItem)
561     parentItem = rootItem;
562   qDebug() << "debug_rowsInserted:" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
563
564   QModelIndex child;
565   AbstractTreeItem *childItem;
566   for(int i = start; i <= end; i++) {
567     child = parent.child(i, 0);
568     childItem = parentItem->child(i);
569     Q_ASSERT(childItem);
570     qDebug() << "<<<" << i << child << child.data().toString();
571   }
572 }
573
574 void TreeModel::debug_rowsRemoved(const QModelIndex &parent, int start, int end) {
575   qDebug() << "debug_rowsRemoved" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
576 }
577
578 void TreeModel::debug_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
579   qDebug() << "debug_dataChanged" << topLeft << bottomRight;
580   QStringList displayData;
581   for(int row = topLeft.row(); row <= bottomRight.row(); row++) {
582     displayData = QStringList();
583     for(int column = topLeft.column(); column <= bottomRight.column(); column++) {
584       displayData << data(topLeft.sibling(row, column), Qt::DisplayRole).toString();
585     }
586     qDebug() << "  row:" << row << displayData;
587   }
588 }