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