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