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