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