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