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