Change bufferview icons
[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("user-online")),
49     _channelPartedIcon(SmallIcon("user-offline")),
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     int numBuffers = config()->bufferList().count();
145     QSet<BufferId>::const_iterator iter;
146     for(iter = _toAdd.constBegin(); iter != _toAdd.constEnd(); iter++) {
147       if(config()->bufferList().contains(*iter))
148         continue;
149       config()->requestAddBuffer(*iter, numBuffers);
150     }
151     for(iter = _toTempRemove.constBegin(); iter != _toTempRemove.constEnd(); iter++) {
152       if(config()->temporarilyRemovedBuffers().contains(*iter))
153          continue;
154       config()->requestRemoveBuffer(*iter);
155     }
156     for(iter = _toRemove.constBegin(); iter != _toRemove.constEnd(); iter++) {
157       if(config()->removedBuffers().contains(*iter))
158          continue;
159       config()->requestRemoveBufferPermanently(*iter);
160     }
161   }
162   _toAdd.clear();
163   _toTempRemove.clear();
164   _toRemove.clear();
165
166   invalidate();
167 }
168
169
170 Qt::ItemFlags BufferViewFilter::flags(const QModelIndex &index) const {
171   QModelIndex source_index = mapToSource(index);
172   Qt::ItemFlags flags = sourceModel()->flags(source_index);
173   if(config()) {
174     NetworkModel::ItemType itemType = (NetworkModel::ItemType)sourceModel()->data(source_index, NetworkModel::ItemTypeRole).toInt();
175     BufferInfo::Type bufferType = (BufferInfo::Type)sourceModel()->data(source_index, NetworkModel::BufferTypeRole).toInt();
176     if(source_index == QModelIndex() || itemType == NetworkModel::NetworkItemType) {
177       flags |= Qt::ItemIsDropEnabled;
178     } else if(_editMode) {
179       flags |= Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
180     }
181
182     // prohibit dragging of most items. and most drop places
183     // only query to query is allowed for merging
184     if(bufferType != BufferInfo::QueryBuffer) {
185       ClientBufferViewConfig *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
186       if(clientConf && clientConf->isLocked()) {
187         flags &= ~(Qt::ItemIsDropEnabled | Qt::ItemIsDragEnabled);
188       }
189     }
190   }
191   return flags;
192 }
193
194 bool BufferViewFilter::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
195   if(!config() || !NetworkModel::mimeContainsBufferList(data))
196     return QSortFilterProxyModel::dropMimeData(data, action, row, column, parent);
197
198   NetworkId droppedNetworkId;
199   QModelIndex source_parent = mapToSource(parent);
200   if(sourceModel()->data(source_parent, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
201     droppedNetworkId = sourceModel()->data(source_parent, NetworkModel::NetworkIdRole).value<NetworkId>();
202
203   QList< QPair<NetworkId, BufferId> > bufferList = NetworkModel::mimeDataToBufferList(data);
204   BufferId bufferId;
205   NetworkId networkId;
206   int pos;
207   for(int i = 0; i < bufferList.count(); i++) {
208     networkId = bufferList[i].first;
209     bufferId = bufferList[i].second;
210     if(droppedNetworkId == networkId) {
211       if(row < 0)
212         row = 0;
213
214       if(row < rowCount(parent)) {
215         QModelIndex source_child = mapToSource(index(row, 0, parent));
216         BufferId beforeBufferId = sourceModel()->data(source_child, NetworkModel::BufferIdRole).value<BufferId>();
217         pos = config()->bufferList().indexOf(beforeBufferId);
218         if(_sortOrder == Qt::DescendingOrder)
219           pos++;
220       } else {
221         if(_sortOrder == Qt::AscendingOrder)
222           pos = config()->bufferList().count();
223         else
224           pos = 0;
225       }
226
227       if(config()->bufferList().contains(bufferId)) {
228         if(config()->bufferList().indexOf(bufferId) < pos)
229           pos--;
230         config()->requestMoveBuffer(bufferId, pos);
231       } else {
232         config()->requestAddBuffer(bufferId, pos);
233       }
234
235     } else {
236       addBuffer(bufferId);
237     }
238   }
239   return true;
240 }
241
242 void BufferViewFilter::sort(int column, Qt::SortOrder order) {
243   _sortOrder = order;
244   QSortFilterProxyModel::sort(column, order);
245 }
246
247 void BufferViewFilter::addBuffer(const BufferId &bufferId) const {
248   if(!config() || config()->bufferList().contains(bufferId))
249     return;
250
251   int pos = config()->bufferList().count();
252   bool lt;
253   for(int i = 0; i < config()->bufferList().count(); i++) {
254     if(config() && config()->sortAlphabetically())
255       lt = bufferIdLessThan(bufferId, config()->bufferList()[i]);
256     else
257       lt = bufferId < config()->bufferList()[i];
258
259     if(lt) {
260       pos = i;
261       break;
262     }
263   }
264   config()->requestAddBuffer(bufferId, pos);
265 }
266
267 bool BufferViewFilter::filterAcceptBuffer(const QModelIndex &source_bufferIndex) const {
268   // no config -> "all buffers" -> accept everything
269   if(!config())
270     return true;
271
272   BufferId bufferId = sourceModel()->data(source_bufferIndex, NetworkModel::BufferIdRole).value<BufferId>();
273   Q_ASSERT(bufferId.isValid());
274
275   int activityLevel = sourceModel()->data(source_bufferIndex, NetworkModel::BufferActivityRole).toInt();
276
277   if(!config()->bufferList().contains(bufferId) && !_editMode) {
278     // add the buffer if...
279     if(config()->isInitialized()
280        && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
281        && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
282            || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
283       addBuffer(bufferId);
284     }
285     // note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
286     return false;
287   }
288
289   if(config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
290     return false;
291
292   int allowedBufferTypes = config()->allowedBufferTypes();
293   if(!config()->networkId().isValid())
294     allowedBufferTypes &= ~BufferInfo::StatusBuffer;
295   if(!(allowedBufferTypes & sourceModel()->data(source_bufferIndex, NetworkModel::BufferTypeRole).toInt()))
296     return false;
297
298   // the following dynamic filters may not trigger if the buffer is currently selected.
299   QModelIndex currentIndex = Client::bufferModel()->standardSelectionModel()->currentIndex();
300   if(bufferId == Client::bufferModel()->data(currentIndex, NetworkModel::BufferIdRole).value<BufferId>())
301     return true;
302
303   if(config()->hideInactiveBuffers() && !sourceModel()->data(source_bufferIndex, NetworkModel::ItemActiveRole).toBool() && activityLevel <= BufferInfo::OtherActivity)
304     return false;
305
306   if(config()->minimumActivity() > activityLevel)
307     return false;
308
309   return true;
310 }
311
312 bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const {
313   if(!config())
314     return true;
315
316   if(!config()->networkId().isValid()) {
317     return true;
318   } else {
319     return config()->networkId() == sourceModel()->data(source_index, NetworkModel::NetworkIdRole).value<NetworkId>();
320   }
321 }
322
323 bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const {
324   QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
325
326   if(!child.isValid()) {
327     qWarning() << "filterAcceptsRow has been called with an invalid Child";
328     return false;
329   }
330
331   NetworkModel::ItemType childType = (NetworkModel::ItemType)sourceModel()->data(child, NetworkModel::ItemTypeRole).toInt();
332   switch(childType) {
333   case NetworkModel::NetworkItemType:
334     return filterAcceptNetwork(child);
335   case NetworkModel::BufferItemType:
336     return filterAcceptBuffer(child);
337   default:
338     return false;
339   }
340 }
341
342 bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
343   int leftItemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
344   int rightItemType = sourceModel()->data(source_right, NetworkModel::ItemTypeRole).toInt();
345   int itemType = leftItemType & rightItemType;
346   switch(itemType) {
347   case NetworkModel::NetworkItemType:
348     return networkLessThan(source_left, source_right);
349   case NetworkModel::BufferItemType:
350     return bufferLessThan(source_left, source_right);
351   default:
352     return QSortFilterProxyModel::lessThan(source_left, source_right);
353   }
354 }
355
356 bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
357   BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
358   BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
359   if(config()) {
360     int leftPos = config()->bufferList().indexOf(leftBufferId);
361     int rightPos = config()->bufferList().indexOf(rightBufferId);
362     if(leftPos == -1 && rightPos == -1)
363       return QSortFilterProxyModel::lessThan(source_left, source_right);
364     if(leftPos == -1 || rightPos == -1)
365       return !(leftPos < rightPos);
366     return leftPos < rightPos;
367   } else
368     return bufferIdLessThan(leftBufferId, rightBufferId);
369 }
370
371 bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
372   NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
373   NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
374
375   return QSortFilterProxyModel::lessThan(source_left, source_right);
376 }
377
378 QVariant BufferViewFilter::data(const QModelIndex &index, int role) const {
379   switch(role) {
380   case Qt::DecorationRole:
381     return icon(index);
382   case Qt::CheckStateRole:
383     return checkedState(index);
384   default:
385     return QSortFilterProxyModel::data(index, role);
386   }
387 }
388
389 QVariant BufferViewFilter::icon(const QModelIndex &index) const {
390   if(!_showUserStateIcons || (config() && config()->disableDecoration()))
391     return QVariant();
392
393   if(index.column() != 0)
394     return QVariant();
395
396   QModelIndex source_index = mapToSource(index);
397   NetworkModel::ItemType itemType = (NetworkModel::ItemType)sourceModel()->data(source_index, NetworkModel::ItemTypeRole).toInt();
398   BufferInfo::Type bufferType = (BufferInfo::Type)sourceModel()->data(source_index, NetworkModel::BufferTypeRole).toInt();
399   bool isActive = sourceModel()->data(source_index, NetworkModel::ItemActiveRole).toBool();
400
401   if(itemType != NetworkModel::BufferItemType)
402     return QVariant();
403
404   switch(bufferType) {
405   case BufferInfo::ChannelBuffer:
406     if(isActive)
407       return _channelJoinedIcon;
408     else
409       return _channelPartedIcon;
410   case BufferInfo::QueryBuffer:
411     if(!isActive)
412       return _userOfflineIcon;
413     if(sourceModel()->data(source_index, NetworkModel::UserAwayRole).toBool())
414       return _userAwayIcon;
415     else
416       return _userOnlineIcon;
417   default:
418     return QVariant();
419   }
420 }
421
422 QVariant BufferViewFilter::checkedState(const QModelIndex &index) const {
423   if(!_editMode || !config())
424     return QVariant();
425
426   QModelIndex source_index = mapToSource(index);
427   if(source_index == QModelIndex() || sourceModel()->data(source_index, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
428     return QVariant();
429
430   BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
431   if(_toAdd.contains(bufferId))
432     return Qt::Checked;
433
434   if(_toTempRemove.contains(bufferId))
435     return Qt::PartiallyChecked;
436
437   if(_toRemove.contains(bufferId))
438     return Qt::Unchecked;
439
440   if(config()->bufferList().contains(bufferId))
441     return Qt::Checked;
442
443   if(config()->temporarilyRemovedBuffers().contains(bufferId))
444     return Qt::PartiallyChecked;
445
446   return Qt::Unchecked;
447 }
448
449 bool BufferViewFilter::setData(const QModelIndex &index, const QVariant &value, int role) {
450   switch(role) {
451   case Qt::CheckStateRole:
452     return setCheckedState(index, Qt::CheckState(value.toInt()));
453   default:
454     return QSortFilterProxyModel::setData(index, value, role);
455   }
456 }
457
458 bool BufferViewFilter::setCheckedState(const QModelIndex &index, Qt::CheckState state) {
459   QModelIndex source_index = mapToSource(index);
460   BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
461   if(!bufferId.isValid())
462     return false;
463
464   switch(state) {
465   case Qt::Unchecked:
466     _toAdd.remove(bufferId);
467     _toTempRemove.remove(bufferId);
468     _toRemove << bufferId;
469     break;
470   case Qt::PartiallyChecked:
471     _toAdd.remove(bufferId);
472     _toTempRemove << bufferId;
473     _toRemove.remove(bufferId);
474     break;
475   case Qt::Checked:
476     _toAdd << bufferId;
477     _toTempRemove.remove(bufferId);
478     _toRemove.remove(bufferId);
479     break;
480   default:
481     return false;
482   }
483   emit dataChanged(index, index);
484   return true;
485 }
486
487 void BufferViewFilter::checkPreviousCurrentForRemoval(const QModelIndex &current, const QModelIndex &previous) {
488   Q_UNUSED(current);
489   if(previous.isValid())
490     QCoreApplication::postEvent(this, new CheckRemovalEvent(previous));
491 }
492
493 void BufferViewFilter::customEvent(QEvent *event) {
494   if(event->type() != QEvent::User)
495     return;
496
497   CheckRemovalEvent *removalEvent = static_cast<CheckRemovalEvent *>(event);
498   checkItemForRemoval(removalEvent->index);
499
500   event->accept();
501 }
502
503 void BufferViewFilter::checkItemsForRemoval(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
504   QModelIndex source_topLeft = mapToSource(topLeft);
505   QModelIndex source_bottomRight = mapToSource(bottomRight);
506   emit _dataChanged(source_topLeft, source_bottomRight);
507 }
508
509 bool BufferViewFilter::bufferIdLessThan(const BufferId &left, const BufferId &right) {
510   Q_CHECK_PTR(Client::networkModel());
511   if(!Client::networkModel())
512     return true;
513
514   QModelIndex leftIndex = Client::networkModel()->bufferIndex(left);
515   QModelIndex rightIndex = Client::networkModel()->bufferIndex(right);
516
517   int leftType = Client::networkModel()->data(leftIndex, NetworkModel::BufferTypeRole).toInt();
518   int rightType = Client::networkModel()->data(rightIndex, NetworkModel::BufferTypeRole).toInt();
519
520   if(leftType != rightType)
521     return leftType < rightType;
522   else
523     return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
524 }
525