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