remove show/hide checkboxes from network items
[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() && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
266        && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
267            || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
268       addBuffer(bufferId);
269     }
270     // note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
271     return false;
272   }
273
274   if(config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
275     return false;
276
277   int allowedBufferTypes = config()->allowedBufferTypes();
278   if(!config()->networkId().isValid())
279     allowedBufferTypes &= ~BufferInfo::StatusBuffer;
280   if(!(allowedBufferTypes & sourceModel()->data(source_bufferIndex, NetworkModel::BufferTypeRole).toInt()))
281     return false;
282
283   // the following dynamic filters may not trigger if the buffer is currently selected.
284   QModelIndex currentIndex = Client::bufferModel()->standardSelectionModel()->currentIndex();
285   if(bufferId == Client::bufferModel()->data(currentIndex, NetworkModel::BufferIdRole).value<BufferId>())
286     return true;
287
288   if(config()->hideInactiveBuffers() && !sourceModel()->data(source_bufferIndex, NetworkModel::ItemActiveRole).toBool() && activityLevel <= BufferInfo::OtherActivity)
289     return false;
290
291   if(config()->minimumActivity() > activityLevel)
292     return false;
293
294   return true;
295 }
296
297 bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const {
298   if(!config())
299     return true;
300
301   if(!config()->networkId().isValid()) {
302     return true;
303   } else {
304     return config()->networkId() == sourceModel()->data(source_index, NetworkModel::NetworkIdRole).value<NetworkId>();
305   }
306 }
307
308 bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const {
309   QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
310
311   if(!child.isValid()) {
312     qWarning() << "filterAcceptsRow has been called with an invalid Child";
313     return false;
314   }
315
316   if(!source_parent.isValid())
317     return filterAcceptNetwork(child);
318   else
319     return filterAcceptBuffer(child);
320 }
321
322 bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
323   int leftItemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
324   int rightItemType = sourceModel()->data(source_right, NetworkModel::ItemTypeRole).toInt();
325   int itemType = leftItemType & rightItemType;
326   switch(itemType) {
327   case NetworkModel::NetworkItemType:
328     return networkLessThan(source_left, source_right);
329   case NetworkModel::BufferItemType:
330     return bufferLessThan(source_left, source_right);
331   default:
332     return QSortFilterProxyModel::lessThan(source_left, source_right);
333   }
334 }
335
336 bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
337   BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
338   BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
339   if(config()) {
340     int leftPos = config()->bufferList().indexOf(leftBufferId);
341     int rightPos = config()->bufferList().indexOf(rightBufferId);
342     if(leftPos == -1 && rightPos == -1)
343       return QSortFilterProxyModel::lessThan(source_left, source_right);
344     if(leftPos == -1 || rightPos == -1)
345       return !(leftPos < rightPos);
346     return leftPos < rightPos;
347   } else
348     return bufferIdLessThan(leftBufferId, rightBufferId);
349 }
350
351 bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
352   NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
353   NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
354
355   if(config() && config()->sortAlphabetically())
356     return QSortFilterProxyModel::lessThan(source_left, source_right);
357   else
358     return leftNetworkId < rightNetworkId;
359 }
360
361 QVariant BufferViewFilter::data(const QModelIndex &index, int role) const {
362   switch(role) {
363   case Qt::DecorationRole:
364     return icon(index);
365   case Qt::CheckStateRole:
366     return checkedState(index);
367   default:
368     return QSortFilterProxyModel::data(index, role);
369   }
370 }
371
372 QVariant BufferViewFilter::icon(const QModelIndex &index) const {
373   if(!_showUserStateIcons || (config() && config()->disableDecoration()))
374     return QVariant();
375
376   if(index.column() != 0)
377     return QVariant();
378
379   QModelIndex source_index = mapToSource(index);
380   if(sourceModel()->data(index, NetworkModel::BufferTypeRole).toInt() != BufferInfo::QueryBuffer)
381     return QVariant();
382
383   if(!sourceModel()->data(index, NetworkModel::ItemActiveRole).toBool())
384     return _userOfflineIcon;
385
386   if(sourceModel()->data(index, NetworkModel::UserAwayRole).toBool())
387     return _userAwayIcon;
388   else
389     return _userOnlineIcon;
390
391   return QVariant();
392 }
393
394 QVariant BufferViewFilter::checkedState(const QModelIndex &index) const {
395   if(!_editMode || !config())
396     return QVariant();
397
398   QModelIndex source_index = mapToSource(index);
399   if(source_index == QModelIndex() || sourceModel()->data(source_index, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
400     return QVariant();
401
402   BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
403   if(_toAdd.contains(bufferId))
404     return Qt::Checked;
405
406   if(_toTempRemove.contains(bufferId))
407     return Qt::PartiallyChecked;
408
409   if(_toRemove.contains(bufferId))
410     return Qt::Unchecked;
411
412   if(config()->bufferList().contains(bufferId))
413     return Qt::Checked;
414
415   if(config()->temporarilyRemovedBuffers().contains(bufferId))
416     return Qt::PartiallyChecked;
417
418   return Qt::Unchecked;
419 }
420
421 bool BufferViewFilter::setData(const QModelIndex &index, const QVariant &value, int role) {
422   switch(role) {
423   case Qt::CheckStateRole:
424     return setCheckedState(index, Qt::CheckState(value.toInt()));
425   default:
426     return QSortFilterProxyModel::setData(index, value, role);
427   }
428 }
429
430 bool BufferViewFilter::setCheckedState(const QModelIndex &index, Qt::CheckState state) {
431   QModelIndex source_index = mapToSource(index);
432   BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
433   if(!bufferId.isValid())
434     return false;
435
436   switch(state) {
437   case Qt::Unchecked:
438     _toAdd.remove(bufferId);
439     _toTempRemove.remove(bufferId);
440     _toRemove << bufferId;
441     break;
442   case Qt::PartiallyChecked:
443     _toAdd.remove(bufferId);
444     _toTempRemove << bufferId;
445     _toRemove.remove(bufferId);
446     break;
447   case Qt::Checked:
448     _toAdd << bufferId;
449     _toTempRemove.remove(bufferId);
450     _toRemove.remove(bufferId);
451     break;
452   default:
453     return false;
454   }
455   emit dataChanged(index, index);
456   return true;
457 }
458
459 void BufferViewFilter::checkPreviousCurrentForRemoval(const QModelIndex &current, const QModelIndex &previous) {
460   Q_UNUSED(current);
461   if(previous.isValid())
462     QCoreApplication::postEvent(this, new CheckRemovalEvent(previous));
463 }
464
465 void BufferViewFilter::customEvent(QEvent *event) {
466   if(event->type() != QEvent::User)
467     return;
468
469   CheckRemovalEvent *removalEvent = static_cast<CheckRemovalEvent *>(event);
470   checkItemForRemoval(removalEvent->index);
471
472   event->accept();
473 }
474
475 void BufferViewFilter::checkItemsForRemoval(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
476   QModelIndex source_topLeft = mapToSource(topLeft);
477   QModelIndex source_bottomRight = mapToSource(bottomRight);
478   emit _dataChanged(source_topLeft, source_bottomRight);
479 }
480
481 bool BufferViewFilter::bufferIdLessThan(const BufferId &left, const BufferId &right) {
482   Q_CHECK_PTR(Client::networkModel());
483   if(!Client::networkModel())
484     return true;
485
486   QModelIndex leftIndex = Client::networkModel()->bufferIndex(left);
487   QModelIndex rightIndex = Client::networkModel()->bufferIndex(right);
488
489   int leftType = Client::networkModel()->data(leftIndex, NetworkModel::BufferTypeRole).toInt();
490   int rightType = Client::networkModel()->data(rightIndex, NetworkModel::BufferTypeRole).toInt();
491
492   if(leftType != rightType)
493     return leftType < rightType;
494   else
495     return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
496 }
497