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