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