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