Query state (offline / online / away) is now properly indicated with an icon.
[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 "client.h"
30 #include "iconloader.h"
31 #include "networkmodel.h"
32
33 #include "uisettings.h"
34
35 class CheckRemovalEvent : public QEvent {
36 public:
37   CheckRemovalEvent(const QModelIndex &source_index) : QEvent(QEvent::User), index(source_index) {};
38   QPersistentModelIndex index;
39 };
40
41 /*****************************************
42 * The Filter for the Tree View
43 *****************************************/
44 BufferViewFilter::BufferViewFilter(QAbstractItemModel *model, BufferViewConfig *config)
45   : QSortFilterProxyModel(model),
46     _config(0),
47     _sortOrder(Qt::AscendingOrder),
48     _userOfflineIcon(SmallIcon("user-offline")),
49     _userAwayIcon(SmallIcon("user-away")),
50     _userOnlineIcon(SmallIcon("user-online"))
51 {
52   setConfig(config);
53   setSourceModel(model);
54
55   setDynamicSortFilter(true);
56
57   loadColors();
58
59   connect(this, SIGNAL(_dataChanged(const QModelIndex &, const QModelIndex &)),
60           this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
61 }
62
63 void BufferViewFilter::loadColors() {
64   UiSettings s("QtUiStyle/Colors");
65   _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
66   _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
67   _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
68   _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
69   _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
70 }
71
72 void BufferViewFilter::setConfig(BufferViewConfig *config) {
73   if(_config == config)
74     return;
75
76   if(_config) {
77     disconnect(_config, 0, this, 0);
78   }
79
80   _config = config;
81
82   if(!config) {
83     invalidate();
84     return;
85   }
86
87   if(config->isInitialized()) {
88     configInitialized();
89   } else {
90     connect(config, SIGNAL(initDone()), this, SLOT(configInitialized()));
91     invalidate();
92   }
93 }
94
95 void BufferViewFilter::configInitialized() {
96   if(!config())
97     return;
98
99   connect(config(), SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(invalidate()));
100   connect(config(), SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(invalidate()));
101   connect(config(), SIGNAL(addNewBuffersAutomaticallySet(bool)), this, SLOT(invalidate()));
102   connect(config(), SIGNAL(sortAlphabeticallySet(bool)), this, SLOT(invalidate()));
103   connect(config(), SIGNAL(hideInactiveBuffersSet(bool)), this, SLOT(invalidate()));
104   connect(config(), SIGNAL(allowedBufferTypesSet(int)), this, SLOT(invalidate()));
105   connect(config(), SIGNAL(minimumActivitySet(int)), this, SLOT(invalidate()));
106   connect(config(), SIGNAL(bufferListSet()), this, SLOT(invalidate()));
107   connect(config(), SIGNAL(bufferAdded(const BufferId &, int)), this, SLOT(invalidate()));
108   connect(config(), SIGNAL(bufferMoved(const BufferId &, int)), this, SLOT(invalidate()));
109   connect(config(), SIGNAL(bufferRemoved(const BufferId &)), this, SLOT(invalidate()));
110   connect(config(), SIGNAL(bufferPermanentlyRemoved(const BufferId &)), this, SLOT(invalidate()));
111
112   disconnect(config(), SIGNAL(initDone()), this, SLOT(configInitialized()));
113
114   invalidate();
115   emit configChanged();
116 }
117
118 Qt::ItemFlags BufferViewFilter::flags(const QModelIndex &index) const {
119   Qt::ItemFlags flags = mapToSource(index).flags();
120   if(_config && (index == QModelIndex() || index.parent() == QModelIndex()))
121     flags |= Qt::ItemIsDropEnabled;
122   return flags;
123 }
124
125 bool BufferViewFilter::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
126   if(!config() || !NetworkModel::mimeContainsBufferList(data))
127     return QSortFilterProxyModel::dropMimeData(data, action, row, column, parent);
128
129   NetworkId droppedNetworkId;
130   if(parent.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
131     droppedNetworkId = parent.data(NetworkModel::NetworkIdRole).value<NetworkId>();
132
133   QList< QPair<NetworkId, BufferId> > bufferList = NetworkModel::mimeDataToBufferList(data);
134   BufferId bufferId;
135   NetworkId networkId;
136   int pos;
137   for(int i = 0; i < bufferList.count(); i++) {
138     networkId = bufferList[i].first;
139     bufferId = bufferList[i].second;
140     if(droppedNetworkId == networkId) {
141       if(row < 0)
142         row = 0;
143
144       if(row < rowCount(parent)) {
145         BufferId beforeBufferId = parent.child(row, 0).data(NetworkModel::BufferIdRole).value<BufferId>();
146         pos = config()->bufferList().indexOf(beforeBufferId);
147         if(_sortOrder == Qt::DescendingOrder)
148           pos++;
149       } else {
150         if(_sortOrder == Qt::AscendingOrder)
151           pos = config()->bufferList().count();
152         else
153           pos = 0;
154       }
155
156       if(config()->bufferList().contains(bufferId)) {
157         if(config()->bufferList().indexOf(bufferId) < pos)
158           pos--;
159         config()->requestMoveBuffer(bufferId, pos);
160       } else {
161         config()->requestAddBuffer(bufferId, pos);
162       }
163
164     } else {
165       addBuffer(bufferId);
166     }
167   }
168   return true;
169 }
170
171 void BufferViewFilter::sort(int column, Qt::SortOrder order) {
172   _sortOrder = order;
173   QSortFilterProxyModel::sort(column, order);
174 }
175
176 void BufferViewFilter::addBuffer(const BufferId &bufferId) const {
177   if(!config() || config()->bufferList().contains(bufferId))
178     return;
179
180   int pos = config()->bufferList().count();
181   bool lt;
182   for(int i = 0; i < config()->bufferList().count(); i++) {
183     if(config() && config()->sortAlphabetically())
184       lt = bufferIdLessThan(bufferId, config()->bufferList()[i]);
185     else
186       lt = bufferId < config()->bufferList()[i];
187
188     if(lt) {
189       pos = i;
190       break;
191     }
192   }
193   config()->requestAddBuffer(bufferId, pos);
194 }
195
196 bool BufferViewFilter::filterAcceptBuffer(const QModelIndex &source_bufferIndex) const {
197   // no config -> "all buffers" -> accept everything
198   if(!config())
199     return true;
200
201   BufferId bufferId = sourceModel()->data(source_bufferIndex, NetworkModel::BufferIdRole).value<BufferId>();
202   Q_ASSERT(bufferId.isValid());
203
204   int activityLevel = source_bufferIndex.data(NetworkModel::BufferActivityRole).toInt();
205
206   if(!config()->bufferList().contains(bufferId)) {
207     // add the buffer if...
208     if(config()->isInitialized() && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
209        && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
210            || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
211       addBuffer(bufferId);
212     }
213     // note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
214     return false;
215   }
216
217   if(config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
218     return false;
219
220   if(!(config()->allowedBufferTypes() & (BufferInfo::Type)source_bufferIndex.data(NetworkModel::BufferTypeRole).toInt()))
221     return false;
222
223   // the following dynamic filters may not trigger if the buffer is currently selected.
224   if(bufferId == Client::bufferModel()->standardSelectionModel()->currentIndex().data(NetworkModel::BufferIdRole).value<BufferId>())
225     return true;
226
227   if(config()->hideInactiveBuffers() && !source_bufferIndex.data(NetworkModel::ItemActiveRole).toBool() && activityLevel <= BufferInfo::OtherActivity)
228     return false;
229
230   if(config()->minimumActivity() > activityLevel)
231     return false;
232
233   return true;
234 }
235
236 bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const {
237   if(!config())
238     return true;
239
240   if(!config()->networkId().isValid()) {
241     return true;
242   } else {
243     return config()->networkId() == sourceModel()->data(source_index, NetworkModel::NetworkIdRole).value<NetworkId>();
244   }
245 }
246
247 bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const {
248   QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
249
250   if(!child.isValid()) {
251     qWarning() << "filterAcceptsRow has been called with an invalid Child";
252     return false;
253   }
254
255   if(!source_parent.isValid())
256     return filterAcceptNetwork(child);
257   else
258     return filterAcceptBuffer(child);
259 }
260
261 bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
262   int itemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
263   switch(itemType) {
264   case NetworkModel::NetworkItemType:
265     return networkLessThan(source_left, source_right);
266   case NetworkModel::BufferItemType:
267     return bufferLessThan(source_left, source_right);
268   default:
269     return QSortFilterProxyModel::lessThan(source_left, source_right);
270   }
271 }
272
273 bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
274   BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
275   BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
276   if(config()) {
277     return config()->bufferList().indexOf(leftBufferId) < config()->bufferList().indexOf(rightBufferId);
278   } else
279     return bufferIdLessThan(leftBufferId, rightBufferId);
280 }
281
282 bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
283   NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
284   NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
285
286   if(config() && config()->sortAlphabetically())
287     return QSortFilterProxyModel::lessThan(source_left, source_right);
288   else
289     return leftNetworkId < rightNetworkId;
290 }
291
292 QVariant BufferViewFilter::data(const QModelIndex &index, int role) const {
293   switch(role) {
294   case Qt::DecorationRole:
295     return icon(index);
296   case Qt::ForegroundRole:
297     return foreground(index);
298   default:
299     return QSortFilterProxyModel::data(index, role);
300   }
301 }
302
303 QVariant BufferViewFilter::icon(const QModelIndex &index) const {
304   if(index.column() != 0)
305     return QVariant();
306
307   if(index.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::QueryBuffer)
308     return QVariant();
309
310   if(!index.data(NetworkModel::ItemActiveRole).toBool())
311     return _userOfflineIcon;
312
313   if(index.data(NetworkModel::UserAwayRole).toBool())
314     return _userAwayIcon;
315   else
316     return _userOnlineIcon;
317
318   return QVariant();
319 }
320
321 QVariant BufferViewFilter::foreground(const QModelIndex &index) const {
322   BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
323
324   if(activity & BufferInfo::Highlight)
325     return _FgColorHighlightActivity;
326   if(activity & BufferInfo::NewMessage)
327     return _FgColorNewMessageActivity;
328   if(activity & BufferInfo::OtherActivity)
329     return _FgColorOtherActivity;
330
331   if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool())
332     return _FgColorInactiveActivity;
333
334   return _FgColorNoActivity;
335 }
336
337 void BufferViewFilter::checkPreviousCurrentForRemoval(const QModelIndex &current, const QModelIndex &previous) {
338   Q_UNUSED(current);
339   if(previous.isValid())
340     QCoreApplication::postEvent(this, new CheckRemovalEvent(previous));
341 }
342
343 void BufferViewFilter::customEvent(QEvent *event) {
344   if(event->type() != QEvent::User)
345     return;
346
347   CheckRemovalEvent *removalEvent = static_cast<CheckRemovalEvent *>(event);
348   checkItemForRemoval(removalEvent->index);
349
350   event->accept();
351 }
352
353 void BufferViewFilter::checkItemsForRemoval(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
354   QModelIndex source_topLeft = mapToSource(topLeft);
355   QModelIndex source_bottomRight = mapToSource(bottomRight);
356   emit _dataChanged(source_topLeft, source_bottomRight);
357 }
358
359 // ******************************
360 //  Helper
361 // ******************************
362 bool bufferIdLessThan(const BufferId &left, const BufferId &right) {
363   Q_CHECK_PTR(Client::networkModel());
364   if(!Client::networkModel())
365     return true;
366
367   QModelIndex leftIndex = Client::networkModel()->bufferIndex(left);
368   QModelIndex rightIndex = Client::networkModel()->bufferIndex(right);
369
370   int leftType = Client::networkModel()->data(leftIndex, NetworkModel::BufferTypeRole).toInt();
371   int rightType = Client::networkModel()->data(rightIndex, NetworkModel::BufferTypeRole).toInt();
372
373   if(leftType != rightType)
374     return leftType < rightType;
375   else
376     return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
377 }
378