fixes #609 - bufferview not correctly sorted
[quassel.git] / src / uisupport / bufferviewfilter.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "bufferviewfilter.h"
22
23 #include <QApplication>
24 #include <QPalette>
25 #include <QBrush>
26
27 #include "bufferinfo.h"
28 #include "buffermodel.h"
29 #include "buffersettings.h"
30 #include "client.h"
31 #include "clientbufferviewconfig.h"
32 #include "iconloader.h"
33 #include "networkmodel.h"
34
35 class CheckRemovalEvent : public QEvent {
36 public:
37   CheckRemovalEvent(const QModelIndex &source_index) : QEvent(QEvent::User), index(source_index) {};
38   QPersistentModelIndex index;
39 };
40
41 /*****************************************
42 * The Filter for the Tree View
43 *****************************************/
44 BufferViewFilter::BufferViewFilter(QAbstractItemModel *model, BufferViewConfig *config)
45   : QSortFilterProxyModel(model),
46     _config(0),
47     _sortOrder(Qt::AscendingOrder),
48     _channelJoinedIcon(SmallIcon("irc-channel-active")),
49     _channelPartedIcon(SmallIcon("irc-channel-inactive")),
50     _userOfflineIcon(SmallIcon("im-user-offline")),
51     _userAwayIcon(SmallIcon("im-user-away")),
52     _userOnlineIcon(SmallIcon("im-user")),
53     _editMode(false),
54     _enableEditMode(tr("Show / Hide buffers"), this)
55 {
56   setConfig(config);
57   setSourceModel(model);
58
59   setDynamicSortFilter(true);
60
61   connect(this, SIGNAL(_dataChanged(const QModelIndex &, const QModelIndex &)),
62           this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
63
64   _enableEditMode.setCheckable(true);
65   _enableEditMode.setChecked(_editMode);
66   connect(&_enableEditMode, SIGNAL(toggled(bool)), this, SLOT(enableEditMode(bool)));
67
68   BufferSettings bufferSettings;
69   _showUserStateIcons = bufferSettings.showUserStateIcons();
70   bufferSettings.notify("ShowUserStateIcons", this, SLOT(showUserStateIconsChanged()));
71 }
72
73 void BufferViewFilter::showUserStateIconsChanged() {
74   BufferSettings bufferSettings;
75   _showUserStateIcons = bufferSettings.showUserStateIcons();
76 }
77
78 void BufferViewFilter::setConfig(BufferViewConfig *config) {
79   if(_config == config)
80     return;
81
82   if(_config) {
83     disconnect(_config, 0, this, 0);
84   }
85
86   _config = config;
87
88   if(!config) {
89     invalidate();
90     setObjectName("");
91     return;
92   }
93
94   if(config->isInitialized()) {
95     configInitialized();
96   } else {
97     connect(config, SIGNAL(initDone()), this, SLOT(configInitialized()));
98     invalidate();
99   }
100 }
101
102 void BufferViewFilter::configInitialized() {
103   if(!config())
104     return;
105
106   connect(config(), SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(invalidate()));
107   connect(config(), SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(invalidate()));
108   connect(config(), SIGNAL(addNewBuffersAutomaticallySet(bool)), this, SLOT(invalidate()));
109   connect(config(), SIGNAL(sortAlphabeticallySet(bool)), this, SLOT(invalidate()));
110   connect(config(), SIGNAL(hideInactiveBuffersSet(bool)), this, SLOT(invalidate()));
111   connect(config(), SIGNAL(allowedBufferTypesSet(int)), this, SLOT(invalidate()));
112   connect(config(), SIGNAL(minimumActivitySet(int)), this, SLOT(invalidate()));
113   connect(config(), SIGNAL(bufferListSet()), this, SLOT(invalidate()));
114   connect(config(), SIGNAL(bufferAdded(const BufferId &, int)), this, SLOT(invalidate()));
115   connect(config(), SIGNAL(bufferMoved(const BufferId &, int)), this, SLOT(invalidate()));
116   connect(config(), SIGNAL(bufferRemoved(const BufferId &)), this, SLOT(invalidate()));
117   connect(config(), SIGNAL(bufferPermanentlyRemoved(const BufferId &)), this, SLOT(invalidate()));
118
119   disconnect(config(), SIGNAL(initDone()), this, SLOT(configInitialized()));
120
121   setObjectName(config()->bufferViewName());
122
123   invalidate();
124   emit configChanged();
125 }
126
127 QList<QAction *> BufferViewFilter::actions(const QModelIndex &index) {
128   Q_UNUSED(index)
129   QList<QAction *> actionList;
130   actionList << &_enableEditMode;
131   return actionList;
132 }
133
134 void BufferViewFilter::enableEditMode(bool enable) {
135   if(_editMode == enable) {
136     return;
137   }
138   _editMode = enable;
139
140   if(!config())
141     return;
142
143   if(enable == false) {
144     addBuffers(QList<BufferId>::fromSet(_toAdd));
145     QSet<BufferId>::const_iterator iter;
146     for(iter = _toTempRemove.constBegin(); iter != _toTempRemove.constEnd(); iter++) {
147       if(config()->temporarilyRemovedBuffers().contains(*iter))
148          continue;
149       config()->requestRemoveBuffer(*iter);
150     }
151     for(iter = _toRemove.constBegin(); iter != _toRemove.constEnd(); iter++) {
152       if(config()->removedBuffers().contains(*iter))
153          continue;
154       config()->requestRemoveBufferPermanently(*iter);
155     }
156   }
157   _toAdd.clear();
158   _toTempRemove.clear();
159   _toRemove.clear();
160
161   invalidate();
162 }
163
164
165 Qt::ItemFlags BufferViewFilter::flags(const QModelIndex &index) const {
166   QModelIndex source_index = mapToSource(index);
167   Qt::ItemFlags flags = sourceModel()->flags(source_index);
168   if(config()) {
169     NetworkModel::ItemType itemType = (NetworkModel::ItemType)sourceModel()->data(source_index, NetworkModel::ItemTypeRole).toInt();
170     BufferInfo::Type bufferType = (BufferInfo::Type)sourceModel()->data(source_index, NetworkModel::BufferTypeRole).toInt();
171     if(source_index == QModelIndex() || itemType == NetworkModel::NetworkItemType) {
172       flags |= Qt::ItemIsDropEnabled;
173     } else if(_editMode) {
174       flags |= Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
175     }
176
177     // prohibit dragging of most items. and most drop places
178     // only query to query is allowed for merging
179     if(bufferType != BufferInfo::QueryBuffer) {
180       ClientBufferViewConfig *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
181       if(clientConf && clientConf->isLocked()) {
182         flags &= ~(Qt::ItemIsDropEnabled | Qt::ItemIsDragEnabled);
183       }
184     }
185   }
186   return flags;
187 }
188
189 bool BufferViewFilter::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
190   if(!config() || !NetworkModel::mimeContainsBufferList(data))
191     return QSortFilterProxyModel::dropMimeData(data, action, row, column, parent);
192
193   NetworkId droppedNetworkId;
194   QModelIndex source_parent = mapToSource(parent);
195   if(sourceModel()->data(source_parent, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
196     droppedNetworkId = sourceModel()->data(source_parent, NetworkModel::NetworkIdRole).value<NetworkId>();
197
198   QList< QPair<NetworkId, BufferId> > bufferList = NetworkModel::mimeDataToBufferList(data);
199   BufferId bufferId;
200   NetworkId networkId;
201   int pos;
202   for(int i = 0; i < bufferList.count(); i++) {
203     networkId = bufferList[i].first;
204     bufferId = bufferList[i].second;
205     if(droppedNetworkId == networkId) {
206       if(row < 0)
207         row = 0;
208
209       if(row < rowCount(parent)) {
210         QModelIndex source_child = mapToSource(index(row, 0, parent));
211         BufferId beforeBufferId = sourceModel()->data(source_child, NetworkModel::BufferIdRole).value<BufferId>();
212         pos = config()->bufferList().indexOf(beforeBufferId);
213         if(_sortOrder == Qt::DescendingOrder)
214           pos++;
215       } else {
216         if(_sortOrder == Qt::AscendingOrder)
217           pos = config()->bufferList().count();
218         else
219           pos = 0;
220       }
221
222       if(config()->bufferList().contains(bufferId) && !config()->sortAlphabetically()) {
223         if(config()->bufferList().indexOf(bufferId) < pos)
224           pos--;
225         ClientBufferViewConfig *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
226         if(!clientConf || !clientConf->isLocked())
227           config()->requestMoveBuffer(bufferId, pos);
228       } else {
229         config()->requestAddBuffer(bufferId, pos);
230       }
231
232     } else {
233       addBuffer(bufferId);
234     }
235   }
236   return true;
237 }
238
239 void BufferViewFilter::sort(int column, Qt::SortOrder order) {
240   _sortOrder = order;
241   QSortFilterProxyModel::sort(column, order);
242 }
243
244 void BufferViewFilter::addBuffer(const BufferId &bufferId) const {
245   if(!config() || config()->bufferList().contains(bufferId))
246     return;
247
248   int pos = config()->bufferList().count();
249   bool lt;
250   for(int i = 0; i < config()->bufferList().count(); i++) {
251     if(config() && config()->sortAlphabetically())
252       lt = bufferIdLessThan(bufferId, config()->bufferList()[i]);
253     else
254       lt = bufferId < config()->bufferList()[i];
255
256     if(lt) {
257       pos = i;
258       break;
259     }
260   }
261   config()->requestAddBuffer(bufferId, pos);
262 }
263
264 void BufferViewFilter::addBuffers(const QList<BufferId> &bufferIds) const {
265   if(!config())
266     return;
267
268   QList<BufferId> bufferList = config()->bufferList();
269   foreach(BufferId bufferId, bufferIds) {
270     if(bufferList.contains(bufferId))
271       continue;
272
273     int pos = bufferList.count();
274     bool lt;
275     for(int i = 0; i < bufferList.count(); i++) {
276       if(config() && config()->sortAlphabetically())
277         lt = bufferIdLessThan(bufferId, bufferList[i]);
278       else
279         lt = bufferId < config()->bufferList()[i];
280
281       if(lt) {
282         pos = i;
283         bufferList.insert(pos, bufferId);
284         break;
285       }
286     }
287     config()->requestAddBuffer(bufferId, pos);
288   }
289 }
290
291 bool BufferViewFilter::filterAcceptBuffer(const QModelIndex &source_bufferIndex) const {
292   // no config -> "all buffers" -> accept everything
293   if(!config())
294     return true;
295
296   BufferId bufferId = sourceModel()->data(source_bufferIndex, NetworkModel::BufferIdRole).value<BufferId>();
297   Q_ASSERT(bufferId.isValid());
298
299   int activityLevel = sourceModel()->data(source_bufferIndex, NetworkModel::BufferActivityRole).toInt();
300
301   if(!config()->bufferList().contains(bufferId) && !_editMode) {
302     // add the buffer if...
303     if(config()->isInitialized()
304        && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
305        && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
306            || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
307       addBuffer(bufferId);
308     }
309     // note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
310     return false;
311   }
312
313   if(config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
314     return false;
315
316   int allowedBufferTypes = config()->allowedBufferTypes();
317   if(!config()->networkId().isValid())
318     allowedBufferTypes &= ~BufferInfo::StatusBuffer;
319   if(!(allowedBufferTypes & sourceModel()->data(source_bufferIndex, NetworkModel::BufferTypeRole).toInt()))
320     return false;
321
322   // the following dynamic filters may not trigger if the buffer is currently selected.
323   QModelIndex currentIndex = Client::bufferModel()->standardSelectionModel()->currentIndex();
324   if(bufferId == Client::bufferModel()->data(currentIndex, NetworkModel::BufferIdRole).value<BufferId>())
325     return true;
326
327   if(config()->hideInactiveBuffers() && !sourceModel()->data(source_bufferIndex, NetworkModel::ItemActiveRole).toBool() && activityLevel <= BufferInfo::OtherActivity)
328     return false;
329
330   if(config()->minimumActivity() > activityLevel)
331     return false;
332
333   return true;
334 }
335
336 bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const {
337   if(!config())
338     return true;
339
340   if(!config()->networkId().isValid()) {
341     return true;
342   } else {
343     return config()->networkId() == sourceModel()->data(source_index, NetworkModel::NetworkIdRole).value<NetworkId>();
344   }
345 }
346
347 bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const {
348   QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
349
350   if(!child.isValid()) {
351     qWarning() << "filterAcceptsRow has been called with an invalid Child";
352     return false;
353   }
354
355   NetworkModel::ItemType childType = (NetworkModel::ItemType)sourceModel()->data(child, NetworkModel::ItemTypeRole).toInt();
356   switch(childType) {
357   case NetworkModel::NetworkItemType:
358     return filterAcceptNetwork(child);
359   case NetworkModel::BufferItemType:
360     return filterAcceptBuffer(child);
361   default:
362     return false;
363   }
364 }
365
366 bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
367   int leftItemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
368   int rightItemType = sourceModel()->data(source_right, NetworkModel::ItemTypeRole).toInt();
369   int itemType = leftItemType & rightItemType;
370   switch(itemType) {
371   case NetworkModel::NetworkItemType:
372     return networkLessThan(source_left, source_right);
373   case NetworkModel::BufferItemType:
374     return bufferLessThan(source_left, source_right);
375   default:
376     return QSortFilterProxyModel::lessThan(source_left, source_right);
377   }
378 }
379
380 bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
381   BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
382   BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
383   if(config()) {
384     int leftPos = config()->bufferList().indexOf(leftBufferId);
385     int rightPos = config()->bufferList().indexOf(rightBufferId);
386     if(leftPos == -1 && rightPos == -1)
387       return QSortFilterProxyModel::lessThan(source_left, source_right);
388     if(leftPos == -1 || rightPos == -1)
389       return !(leftPos < rightPos);
390     return leftPos < rightPos;
391   } else
392     return bufferIdLessThan(leftBufferId, rightBufferId);
393 }
394
395 bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
396   NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
397   NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
398
399   return QSortFilterProxyModel::lessThan(source_left, source_right);
400 }
401
402 QVariant BufferViewFilter::data(const QModelIndex &index, int role) const {
403   switch(role) {
404   case Qt::DecorationRole:
405     return icon(index);
406   case Qt::CheckStateRole:
407     return checkedState(index);
408   default:
409     return QSortFilterProxyModel::data(index, role);
410   }
411 }
412
413 QVariant BufferViewFilter::icon(const QModelIndex &index) const {
414   if(!_showUserStateIcons || (config() && config()->disableDecoration()))
415     return QVariant();
416
417   if(index.column() != 0)
418     return QVariant();
419
420   QModelIndex source_index = mapToSource(index);
421   NetworkModel::ItemType itemType = (NetworkModel::ItemType)sourceModel()->data(source_index, NetworkModel::ItemTypeRole).toInt();
422   BufferInfo::Type bufferType = (BufferInfo::Type)sourceModel()->data(source_index, NetworkModel::BufferTypeRole).toInt();
423   bool isActive = sourceModel()->data(source_index, NetworkModel::ItemActiveRole).toBool();
424
425   if(itemType != NetworkModel::BufferItemType)
426     return QVariant();
427
428   switch(bufferType) {
429   case BufferInfo::ChannelBuffer:
430     if(isActive)
431       return _channelJoinedIcon;
432     else
433       return _channelPartedIcon;
434   case BufferInfo::QueryBuffer:
435     if(!isActive)
436       return _userOfflineIcon;
437     if(sourceModel()->data(source_index, NetworkModel::UserAwayRole).toBool())
438       return _userAwayIcon;
439     else
440       return _userOnlineIcon;
441   default:
442     return QVariant();
443   }
444 }
445
446 QVariant BufferViewFilter::checkedState(const QModelIndex &index) const {
447   if(!_editMode || !config())
448     return QVariant();
449
450   QModelIndex source_index = mapToSource(index);
451   if(source_index == QModelIndex() || sourceModel()->data(source_index, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
452     return QVariant();
453
454   BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
455   if(_toAdd.contains(bufferId))
456     return Qt::Checked;
457
458   if(_toTempRemove.contains(bufferId))
459     return Qt::PartiallyChecked;
460
461   if(_toRemove.contains(bufferId))
462     return Qt::Unchecked;
463
464   if(config()->bufferList().contains(bufferId))
465     return Qt::Checked;
466
467   if(config()->temporarilyRemovedBuffers().contains(bufferId))
468     return Qt::PartiallyChecked;
469
470   return Qt::Unchecked;
471 }
472
473 bool BufferViewFilter::setData(const QModelIndex &index, const QVariant &value, int role) {
474   switch(role) {
475   case Qt::CheckStateRole:
476     return setCheckedState(index, Qt::CheckState(value.toInt()));
477   default:
478     return QSortFilterProxyModel::setData(index, value, role);
479   }
480 }
481
482 bool BufferViewFilter::setCheckedState(const QModelIndex &index, Qt::CheckState state) {
483   QModelIndex source_index = mapToSource(index);
484   BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
485   if(!bufferId.isValid())
486     return false;
487
488   switch(state) {
489   case Qt::Unchecked:
490     _toAdd.remove(bufferId);
491     _toTempRemove.remove(bufferId);
492     _toRemove << bufferId;
493     break;
494   case Qt::PartiallyChecked:
495     _toAdd.remove(bufferId);
496     _toTempRemove << bufferId;
497     _toRemove.remove(bufferId);
498     break;
499   case Qt::Checked:
500     _toAdd << bufferId;
501     _toTempRemove.remove(bufferId);
502     _toRemove.remove(bufferId);
503     break;
504   default:
505     return false;
506   }
507   emit dataChanged(index, index);
508   return true;
509 }
510
511 void BufferViewFilter::checkPreviousCurrentForRemoval(const QModelIndex &current, const QModelIndex &previous) {
512   Q_UNUSED(current);
513   if(previous.isValid())
514     QCoreApplication::postEvent(this, new CheckRemovalEvent(previous));
515 }
516
517 void BufferViewFilter::customEvent(QEvent *event) {
518   if(event->type() != QEvent::User)
519     return;
520
521   CheckRemovalEvent *removalEvent = static_cast<CheckRemovalEvent *>(event);
522   checkItemForRemoval(removalEvent->index);
523
524   event->accept();
525 }
526
527 void BufferViewFilter::checkItemsForRemoval(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
528   QModelIndex source_topLeft = mapToSource(topLeft);
529   QModelIndex source_bottomRight = mapToSource(bottomRight);
530   emit _dataChanged(source_topLeft, source_bottomRight);
531 }
532
533 bool BufferViewFilter::bufferIdLessThan(const BufferId &left, const BufferId &right) {
534   Q_CHECK_PTR(Client::networkModel());
535   if(!Client::networkModel())
536     return true;
537
538   QModelIndex leftIndex = Client::networkModel()->bufferIndex(left);
539   QModelIndex rightIndex = Client::networkModel()->bufferIndex(right);
540
541   int leftType = Client::networkModel()->data(leftIndex, NetworkModel::BufferTypeRole).toInt();
542   int rightType = Client::networkModel()->data(rightIndex, NetworkModel::BufferTypeRole).toInt();
543
544   if(leftType != rightType)
545     return leftType < rightType;
546   else
547     return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
548 }
549