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