Rework of the TreeModel. This should finaliy *knock on wood* inconsitency issues.
[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 <QDebug>
24
25 /*****************************************
26  *  Abstract Items of a TreeModel
27  *****************************************/
28 AbstractTreeItem::AbstractTreeItem(AbstractTreeItem *parent)
29   : QObject(parent),
30     _flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled)
31 {
32 }
33
34 AbstractTreeItem::~AbstractTreeItem() {
35 }
36
37 quint64 AbstractTreeItem::id() const {
38   return (quint64)this;
39 }
40
41 int AbstractTreeItem::defaultColumn() const {
42   // invalid QModelIndexes aka rootNodes get their Childs stuffed into column -1
43   // all others to 0
44   if(parent() == 0)
45     return -1;
46   else
47     return 0;
48 }
49
50 bool AbstractTreeItem::newChild(int column, AbstractTreeItem *item) {
51   if(column >= columnCount()) {
52     qWarning() << "AbstractTreeItem::newChild() cannot append Child to not existing column!" << this << column;
53     return false;
54   }
55   
56   if(!_childItems.contains(column)) {
57     _childItems[column] = QList<AbstractTreeItem *>();
58   }
59
60   int newRow = _childItems[column].count();
61   emit beginAppendChilds(column, newRow, newRow);
62   _childItems[column].append(item);
63   emit endAppendChilds();
64   
65   return true;
66 }
67
68 bool AbstractTreeItem::newChild(AbstractTreeItem *item) {
69   return newChild(defaultColumn(), item);
70 }
71
72 bool AbstractTreeItem::removeChild(int column, int row) {
73   if(!_childItems.contains(column) || row >= childCount(column))
74     return false;
75
76   emit beginRemoveChilds(column, row, row);
77   AbstractTreeItem *treeitem = _childItems[column].takeAt(row);
78   treeitem->deleteLater();
79   emit endRemoveChilds();
80
81   return true;
82 }
83
84 bool AbstractTreeItem::removeChild(int row) {
85   return removeChild(defaultColumn(), row);
86 }
87
88 bool AbstractTreeItem::removeChildById(int column, const quint64 &id) {
89   if(!_childItems.contains(column))
90     return false;
91
92   for(int i = 0; i < _childItems[column].count(); i++) {
93     if(_childItems[column][i]->id() == id)
94       return removeChild(column, i);
95   }
96   return false;
97 }
98
99 bool AbstractTreeItem::removeChildById(const quint64 &id) {
100   return removeChildById(defaultColumn(), id);
101 }
102
103 void AbstractTreeItem::removeAllChilds() {
104   AbstractTreeItem *child;
105
106   QHash<int, QList<AbstractTreeItem *> >::iterator columnIter = _childItems.begin();
107   while(columnIter != _childItems.end()) {
108     if(columnIter->count() > 0) {
109       emit beginRemoveChilds(columnIter.key(), 0, columnIter->count() - 1);
110       QList<AbstractTreeItem *>::iterator childIter = columnIter->begin();
111       while(childIter != columnIter->end()) {
112         child = *childIter;
113         // child->removeAllChilds();
114         childIter = columnIter->erase(childIter);
115         child->deleteLater();
116       }
117       emit endRemoveChilds();
118     }
119     columnIter++;
120   }
121 }
122
123 AbstractTreeItem *AbstractTreeItem::child(int column, int row) const {
124   if(!_childItems.contains(column) || _childItems[column].size() <= row)
125     return 0;
126   else
127     return _childItems[column].value(row);
128 }
129
130 AbstractTreeItem *AbstractTreeItem::child(int row) const {
131   return child(defaultColumn(), row);
132 }
133
134 AbstractTreeItem *AbstractTreeItem::childById(int column, const quint64 &id) const {
135   if(!_childItems.contains(column))
136     return 0;
137
138   for(int i = 0; i < _childItems[column].count(); i++) {
139     if(_childItems[column][i]->id() == id)
140       return _childItems[column][i];
141   }
142   return 0;
143 }
144
145 AbstractTreeItem *AbstractTreeItem::childById(const quint64 &id) const {
146   return childById(defaultColumn(), id);
147 }
148
149 int AbstractTreeItem::childCount(int column) const {
150   if(!_childItems.contains(column))
151     return 0;
152   else
153     return _childItems[column].count();
154 }
155
156 int AbstractTreeItem::childCount() const {
157   return childCount(defaultColumn());
158 }
159
160 int AbstractTreeItem::column() const {
161   if(!parent())
162     return -1;
163
164   QHash<int, QList<AbstractTreeItem*> >::const_iterator iter = parent()->_childItems.constBegin();
165   while(iter != parent()->_childItems.constEnd()) {
166     if(iter->contains(const_cast<AbstractTreeItem *>(this)))
167       return iter.key();
168     iter++;
169   }
170
171   qWarning() << "AbstractTreeItem::column(): unable to determine the Column of" << this;
172   return parent()->defaultColumn();
173 }
174
175 int AbstractTreeItem::row() const {
176   if(!parent())
177     return -1;
178   else
179     return parent()->_childItems[column()].indexOf(const_cast<AbstractTreeItem *>(this));
180 }
181
182 AbstractTreeItem *AbstractTreeItem::parent() const {
183   return qobject_cast<AbstractTreeItem *>(QObject::parent());
184 }
185
186 Qt::ItemFlags AbstractTreeItem::flags() const {
187   return _flags;
188 }
189
190 void AbstractTreeItem::setFlags(Qt::ItemFlags flags) {
191   _flags = flags;
192 }
193
194 /*****************************************
195  * SimpleTreeItem
196  *****************************************/
197 SimpleTreeItem::SimpleTreeItem(const QList<QVariant> &data, AbstractTreeItem *parent)
198   : AbstractTreeItem(parent),
199     _itemData(data)
200 {
201 }
202
203 SimpleTreeItem::~SimpleTreeItem() {
204 }
205
206 QVariant SimpleTreeItem::data(int column, int role) const {
207   if(column >= columnCount() || role != Qt::DisplayRole)
208     return QVariant();
209   else
210     return _itemData[column];
211 }
212
213 bool SimpleTreeItem::setData(int column, const QVariant &value, int role) {
214   if(column > columnCount() || role != Qt::DisplayRole)
215     return false;
216
217   if(column == columnCount())
218     _itemData.append(value);
219   else
220     _itemData[column] = value;
221
222   emit dataChanged(column);
223   return true;
224 }
225
226 int SimpleTreeItem::columnCount() const {
227   return _itemData.count();
228 }
229
230 /*****************************************
231  * PropertyMapItem
232  *****************************************/
233 PropertyMapItem::PropertyMapItem(const QStringList &propertyOrder, AbstractTreeItem *parent)
234   : AbstractTreeItem(parent),
235     _propertyOrder(propertyOrder)
236 {
237 }
238
239 PropertyMapItem::PropertyMapItem(AbstractTreeItem *parent)
240   : AbstractTreeItem(parent),
241     _propertyOrder(QStringList())
242 {
243 }
244
245
246 PropertyMapItem::~PropertyMapItem() {
247 }
248   
249 QVariant PropertyMapItem::data(int column, int role) const {
250   if(column >= columnCount() || role != Qt::DisplayRole)
251     return QVariant();
252
253   return property(_propertyOrder[column].toAscii());
254 }
255
256 bool PropertyMapItem::setData(int column, const QVariant &value, int role) {
257   if(column >= columnCount() || role != Qt::DisplayRole)
258     return false;
259
260   emit dataChanged(column);
261   return setProperty(_propertyOrder[column].toAscii(), value);
262 }
263
264 int PropertyMapItem::columnCount() const {
265   return _propertyOrder.count();
266 }
267   
268 void PropertyMapItem::appendProperty(const QString &property) {
269   _propertyOrder << property;
270 }
271
272
273
274 /*****************************************
275  * TreeModel
276  *****************************************/
277 TreeModel::TreeModel(const QList<QVariant> &data, QObject *parent)
278   : QAbstractItemModel(parent),
279     _childStatus(QModelIndex(), 0, 0, 0),
280     _aboutToRemoveOrInsert(false)
281 {
282   rootItem = new SimpleTreeItem(data, 0);
283   connectItem(rootItem);
284 }
285
286 TreeModel::~TreeModel() {
287   delete rootItem;
288 }
289
290 QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const {
291   if(!hasIndex(row, column, parent))
292     return QModelIndex();
293   
294   AbstractTreeItem *parentItem;
295   
296   if(!parent.isValid())
297     parentItem = rootItem;
298   else
299     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
300   
301   AbstractTreeItem *childItem = parentItem->child(parent.column(), row);
302
303   if(childItem)
304     return createIndex(row, column, childItem);
305   else
306     return QModelIndex();
307 }
308
309 QModelIndex TreeModel::indexById(quint64 id, const QModelIndex &parent) const {
310   AbstractTreeItem *parentItem; 
311   
312   if(!parent.isValid())
313     parentItem = rootItem;
314   else
315     parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
316   
317   AbstractTreeItem *childItem = parentItem->childById(parent.column(), id);
318   
319   if(childItem)
320     return createIndex(childItem->row(), 0, childItem);
321   else
322     return QModelIndex();
323 }
324
325 QModelIndex TreeModel::indexByItem(AbstractTreeItem *item, int column) const {
326   if(item == 0) {
327     qWarning() << "TreeModel::indexByItem(AbstractTreeItem *item) received NULL-Pointer";
328     return QModelIndex();
329   }
330   
331   if(item == rootItem)
332     return QModelIndex();
333   else
334     return createIndex(item->row(), column, item);
335
336 }
337
338 QModelIndex TreeModel::parent(const QModelIndex &index) const {
339   if(!index.isValid())
340     return QModelIndex();
341   
342   AbstractTreeItem *childItem = static_cast<AbstractTreeItem *>(index.internalPointer());
343   AbstractTreeItem *parentItem = static_cast<AbstractTreeItem *>(childItem->parent());
344   
345   if(parentItem == rootItem)
346     return QModelIndex();
347   
348   return createIndex(parentItem->row(), childItem->column(), parentItem);
349 }
350
351 int TreeModel::rowCount(const QModelIndex &parent) const {
352   AbstractTreeItem *parentItem;
353   if(!parent.isValid())
354     parentItem = rootItem;
355   else
356     parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
357
358   return parentItem->childCount(parent.column());
359 }
360
361 int TreeModel::columnCount(const QModelIndex &parent) const {
362   Q_UNUSED(parent)
363   // since there the Qt Views don't draw more columns than the header has columns
364   // we can be lazy and simply return the count of header columns
365   // actually this gives us more freedom cause we don't have to ensure that a rows parent
366   // has equal or more columns than that row
367   
368 //   if(parent.isValid()) {
369 //     AbstractTreeItem *child;
370 //     if(child = static_cast<AbstractTreeItem *>(parent.internalPointer())->child(parent.column(), parent.row()))
371 //       return child->columnCount();
372 //     else
373 //       return static_cast<AbstractTreeItem*>(parent.internalPointer())->columnCount();
374 //   } else {
375 //     return rootItem->columnCount();
376 //   }
377
378   return rootItem->columnCount();
379 }
380
381 QVariant TreeModel::data(const QModelIndex &index, int role) const {
382   if(!index.isValid())
383     return QVariant();
384
385   AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
386   return item->data(index.column(), role);
387 }
388
389 bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role) {
390   if(!index.isValid())
391     return false;
392
393   AbstractTreeItem *item = static_cast<AbstractTreeItem *>(index.internalPointer());
394   return item->setData(index.column(), value, role);
395 }
396
397 Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const {
398   AbstractTreeItem *item;
399   if(!index.isValid())
400     item = rootItem;
401   else
402     item = static_cast<AbstractTreeItem *>(index.internalPointer());
403   return item->flags();
404 }
405
406 QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const {
407   if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
408     return rootItem->data(section, role);
409   else
410     return QVariant();
411 }
412
413 void TreeModel::itemDataChanged(int column) {
414   AbstractTreeItem *item = qobject_cast<AbstractTreeItem *>(sender());
415   QModelIndex leftIndex, rightIndex;
416
417   if(item == rootItem)
418     return;
419
420   if(column == -1) {
421     leftIndex = createIndex(item->row(), 0, item);
422     rightIndex = createIndex(item->row(), item->columnCount()-1, item);
423   } else {
424     leftIndex = createIndex(item->row(), column, item);
425     rightIndex = leftIndex;
426   }
427
428   emit dataChanged(leftIndex, rightIndex);
429 }
430
431 void TreeModel::connectItem(AbstractTreeItem *item) {
432   connect(item, SIGNAL(dataChanged(int)),
433           this, SLOT(itemDataChanged(int)));
434   
435   connect(item, SIGNAL(beginAppendChilds(int, int, int)),
436           this, SLOT(beginAppendChilds(int, int, int)));
437   connect(item, SIGNAL(endAppendChilds()),
438           this, SLOT(endAppendChilds()));
439   
440   connect(item, SIGNAL(beginRemoveChilds(int, int, int)),
441           this, SLOT(beginRemoveChilds(int, int, int)));
442   connect(item, SIGNAL(endRemoveChilds()),
443           this, SLOT(endRemoveChilds()));
444 }
445
446 void TreeModel::beginAppendChilds(int column, int firstRow, int lastRow) {
447   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
448   if(!parentItem) {
449     qWarning() << "TreeModel::beginAppendChilds(): cannot append Childs to unknown parent";
450     return;
451   }
452   QModelIndex parent = indexByItem(parentItem, column);
453   Q_ASSERT(!_aboutToRemoveOrInsert);
454   
455   _aboutToRemoveOrInsert = true;
456   _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
457   beginInsertRows(parent, firstRow, lastRow);
458 }
459
460 void TreeModel::endAppendChilds() {
461   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
462   if(!parentItem) {
463     qWarning() << "TreeModel::endAppendChilds(): cannot append Childs to unknown parent";
464     return;
465   }
466   Q_ASSERT(_aboutToRemoveOrInsert);
467   ChildStatus cs = _childStatus;
468   QModelIndex parent = indexByItem(parentItem, cs.parent.column());
469   Q_ASSERT(cs.parent == parent);
470   Q_ASSERT(rowCount(parent) == cs.childCount + cs.end - cs.start + 1);
471
472   _aboutToRemoveOrInsert = false;
473   for(int i = cs.start; i <= cs.end; i++) {
474     connectItem(parentItem->child(parent.column(), i));
475   }
476   endInsertRows();
477 }
478
479 void TreeModel::beginRemoveChilds(int column, int firstRow, int lastRow) {
480   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
481   if(!parentItem) {
482     qWarning() << "TreeModel::beginRemoveChilds(): cannot append Childs to unknown parent";
483     return;
484   }
485   QModelIndex parent = indexByItem(parentItem, column);
486   Q_ASSERT(firstRow <= lastRow);
487   Q_ASSERT(parentItem->childCount(column) > lastRow);
488   Q_ASSERT(!_aboutToRemoveOrInsert);
489   
490   _aboutToRemoveOrInsert = true;
491   _childStatus = ChildStatus(parent, rowCount(parent), firstRow, lastRow);
492   beginRemoveRows(parent, firstRow, lastRow);
493 }
494
495 void TreeModel::endRemoveChilds() {
496   AbstractTreeItem *parentItem = qobject_cast<AbstractTreeItem *>(sender());
497   if(!parentItem) {
498     qWarning() << "TreeModel::endRemoveChilds(): cannot append Childs to unknown parent";
499     return;
500   }
501   Q_ASSERT(_aboutToRemoveOrInsert);
502   ChildStatus cs = _childStatus;
503   QModelIndex parent = indexByItem(parentItem, cs.parent.column());
504   Q_ASSERT(cs.parent == parent);
505   Q_ASSERT(rowCount(parent) == cs.childCount - cs.end + cs.start - 1);
506   
507   _aboutToRemoveOrInsert = false;
508   endRemoveRows();
509 }
510
511 void TreeModel::clear() {
512   rootItem->removeAllChilds();
513 }