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