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