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