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