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