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