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