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