Fix expanding networks in Chat Monitor settings
[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 void BufferViewFilter::setFilterString(const QString string)
141 {
142     beginResetModel();
143     _filterString = string;
144     endResetModel();
145     enableEditMode(!string.isEmpty());
146 }
147
148
149 void BufferViewFilter::enableEditMode(bool enable)
150 {
151     if (_editMode == enable) {
152         return;
153     }
154     _editMode = enable;
155
156     if (!config())
157         return;
158
159     if (enable == false) {
160         addBuffers(QList<BufferId>::fromSet(_toAdd));
161         QSet<BufferId>::const_iterator iter;
162         for (iter = _toTempRemove.constBegin(); iter != _toTempRemove.constEnd(); ++iter) {
163             if (config()->temporarilyRemovedBuffers().contains(*iter))
164                 continue;
165             config()->requestRemoveBuffer(*iter);
166         }
167         for (iter = _toRemove.constBegin(); iter != _toRemove.constEnd(); ++iter) {
168             if (config()->removedBuffers().contains(*iter))
169                 continue;
170             config()->requestRemoveBufferPermanently(*iter);
171         }
172     }
173     _toAdd.clear();
174     _toTempRemove.clear();
175     _toRemove.clear();
176
177     invalidate();
178 }
179
180
181 Qt::ItemFlags BufferViewFilter::flags(const QModelIndex &index) const
182 {
183     QModelIndex source_index = mapToSource(index);
184     Qt::ItemFlags flags = sourceModel()->flags(source_index);
185     if (config()) {
186         BufferInfo::Type bufferType = (BufferInfo::Type)sourceModel()->data(source_index, NetworkModel::BufferTypeRole).toInt();
187
188         // We need Status Buffers to be a drop target, to allow for rearranging buffers.
189         // The Status Buffer "owns" the space between Channel/Query buffers in the tree.
190         // This DOES mean that it looks like you can merge a buffer into the Status buffer, but that is restricted in BufferView::dropEvent().
191         if (bufferType == BufferInfo::StatusBuffer) {
192             // But only if the layout isn't locked!
193             ClientBufferViewConfig *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
194             if (clientConf && !clientConf->isLocked()) {
195                 flags |= Qt::ItemIsDropEnabled;
196             }
197         }
198
199         // If we're in Edit Mode, everything except Status Buffers should be hideable.
200         if (_editMode && bufferType != BufferInfo::StatusBuffer) {
201             flags |= Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
202         }
203     }
204     return flags;
205 }
206
207
208 bool BufferViewFilter::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
209 {
210     if (!config() || !NetworkModel::mimeContainsBufferList(data))
211         return QSortFilterProxyModel::dropMimeData(data, action, row, column, parent);
212
213     NetworkId droppedNetworkId;
214     QModelIndex source_parent = mapToSource(parent);
215     if (sourceModel()->data(source_parent, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
216         droppedNetworkId = sourceModel()->data(source_parent, NetworkModel::NetworkIdRole).value<NetworkId>();
217
218     QList<QPair<NetworkId, BufferId> > bufferList = NetworkModel::mimeDataToBufferList(data);
219     BufferId bufferId;
220     NetworkId networkId;
221     int pos;
222     for (int i = 0; i < bufferList.count(); i++) {
223         networkId = bufferList[i].first;
224         bufferId = bufferList[i].second;
225         if (droppedNetworkId == networkId) {
226             if (row < 0)
227                 row = 0;
228
229             if (row < rowCount(parent)) {
230                 QModelIndex source_child = mapToSource(index(row, 0, parent));
231                 BufferId beforeBufferId = sourceModel()->data(source_child, NetworkModel::BufferIdRole).value<BufferId>();
232                 pos = config()->bufferList().indexOf(beforeBufferId);
233                 if (_sortOrder == Qt::DescendingOrder)
234                     pos++;
235             }
236             else {
237                 if (_sortOrder == Qt::AscendingOrder)
238                     pos = config()->bufferList().count();
239                 else
240                     pos = 0;
241             }
242
243             if (config()->bufferList().contains(bufferId) && !config()->sortAlphabetically()) {
244                 if (config()->bufferList().indexOf(bufferId) < pos)
245                     pos--;
246                 ClientBufferViewConfig *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
247                 if (!clientConf || !clientConf->isLocked())
248                     config()->requestMoveBuffer(bufferId, pos);
249             }
250             else {
251                 config()->requestAddBuffer(bufferId, pos);
252             }
253         }
254         else {
255             addBuffer(bufferId);
256         }
257     }
258     return true;
259 }
260
261
262 void BufferViewFilter::sort(int column, Qt::SortOrder order)
263 {
264     _sortOrder = order;
265     QSortFilterProxyModel::sort(column, order);
266 }
267
268
269 void BufferViewFilter::addBuffer(const BufferId &bufferId) const
270 {
271     if (!config() || config()->bufferList().contains(bufferId))
272         return;
273
274     int pos = config()->bufferList().count();
275     bool lt;
276     for (int i = 0; i < config()->bufferList().count(); i++) {
277         if (config() && config()->sortAlphabetically())
278             lt = bufferIdLessThan(bufferId, config()->bufferList()[i]);
279         else
280             lt = bufferId < config()->bufferList()[i];
281
282         if (lt) {
283             pos = i;
284             break;
285         }
286     }
287     config()->requestAddBuffer(bufferId, pos);
288 }
289
290
291 void BufferViewFilter::addBuffers(const QList<BufferId> &bufferIds) const
292 {
293     if (!config())
294         return;
295
296     QList<BufferId> bufferList = config()->bufferList();
297     foreach(BufferId bufferId, bufferIds) {
298         if (bufferList.contains(bufferId))
299             continue;
300
301         int pos = bufferList.count();
302         bool lt;
303         for (int i = 0; i < bufferList.count(); i++) {
304             if (config() && config()->sortAlphabetically())
305                 lt = bufferIdLessThan(bufferId, bufferList[i]);
306             else
307                 lt = bufferId < config()->bufferList()[i];
308
309             if (lt) {
310                 pos = i;
311                 bufferList.insert(pos, bufferId);
312                 break;
313             }
314         }
315         config()->requestAddBuffer(bufferId, pos);
316     }
317 }
318
319
320 bool BufferViewFilter::filterAcceptBuffer(const QModelIndex &source_bufferIndex) const
321 {
322     // no config -> "all buffers" -> accept everything
323     if (!config())
324         return true;
325
326     BufferId bufferId = sourceModel()->data(source_bufferIndex, NetworkModel::BufferIdRole).value<BufferId>();
327     Q_ASSERT(bufferId.isValid());
328
329     int activityLevel = sourceModel()->data(source_bufferIndex, NetworkModel::BufferActivityRole).toInt();
330
331     if (!config()->bufferList().contains(bufferId) && !_editMode) {
332         // add the buffer if...
333         if (config()->isInitialized()
334             && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
335             && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
336                 || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
337             addBuffer(bufferId);
338         }
339         // note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
340         return false;
341     }
342
343     if (config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
344         return false;
345
346     int allowedBufferTypes = config()->allowedBufferTypes();
347     if (!config()->networkId().isValid())
348         allowedBufferTypes &= ~BufferInfo::StatusBuffer;
349     int bufferType = sourceModel()->data(source_bufferIndex, NetworkModel::BufferTypeRole).toInt();
350     if (!(allowedBufferTypes & bufferType))
351         return false;
352
353     if (bufferType & BufferInfo::QueryBuffer && !_showServerQueries && sourceModel()->data(source_bufferIndex, Qt::DisplayRole).toString().contains('.')) {
354         return false;
355     }
356
357     if (!_filterString.isEmpty()) {
358         const BufferInfo info = qvariant_cast<BufferInfo>(Client::bufferModel()->data(source_bufferIndex, NetworkModel::BufferInfoRole));
359         QString name = info.bufferName();
360         if (name.contains(_filterString, Qt::CaseInsensitive)) {
361             return true;
362         } else {
363             return false;
364         }
365     }
366
367     // the following dynamic filters may not trigger if the buffer is currently selected.
368     QModelIndex currentIndex = Client::bufferModel()->standardSelectionModel()->currentIndex();
369     if (bufferId == Client::bufferModel()->data(currentIndex, NetworkModel::BufferIdRole).value<BufferId>())
370         return true;
371
372     if (config()->hideInactiveBuffers() && !sourceModel()->data(source_bufferIndex, NetworkModel::ItemActiveRole).toBool() && activityLevel <= BufferInfo::OtherActivity)
373         return false;
374
375     if (config()->minimumActivity() > activityLevel)
376         return false;
377
378     return true;
379 }
380
381
382 bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const
383 {
384     if (!config())
385         return true;
386
387     if (config()->hideInactiveNetworks() && !(sourceModel()->data(source_index, NetworkModel::ItemActiveRole).toBool())) {
388         return false;
389     }
390
391     if (!config()->networkId().isValid()) {
392         return true;
393     }
394     else {
395         return config()->networkId() == sourceModel()->data(source_index, NetworkModel::NetworkIdRole).value<NetworkId>();
396     }
397 }
398
399
400 bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
401 {
402     QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
403
404     if (!child.isValid()) {
405         qWarning() << "filterAcceptsRow has been called with an invalid Child";
406         return false;
407     }
408
409     NetworkModel::ItemType childType = (NetworkModel::ItemType)sourceModel()->data(child, NetworkModel::ItemTypeRole).toInt();
410     switch (childType) {
411     case NetworkModel::NetworkItemType:
412         return filterAcceptNetwork(child);
413     case NetworkModel::BufferItemType:
414         return filterAcceptBuffer(child);
415     default:
416         return false;
417     }
418 }
419
420
421 bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
422 {
423     int leftItemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
424     int rightItemType = sourceModel()->data(source_right, NetworkModel::ItemTypeRole).toInt();
425     int itemType = leftItemType & rightItemType;
426     switch (itemType) {
427     case NetworkModel::NetworkItemType:
428         return networkLessThan(source_left, source_right);
429     case NetworkModel::BufferItemType:
430         return bufferLessThan(source_left, source_right);
431     default:
432         return QSortFilterProxyModel::lessThan(source_left, source_right);
433     }
434 }
435
436
437 bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
438 {
439     BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
440     BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
441     if (config()) {
442         int leftPos = config()->bufferList().indexOf(leftBufferId);
443         int rightPos = config()->bufferList().indexOf(rightBufferId);
444         if (leftPos == -1 && rightPos == -1)
445             return QSortFilterProxyModel::lessThan(source_left, source_right);
446         if (leftPos == -1 || rightPos == -1)
447             return !(leftPos < rightPos);
448         return leftPos < rightPos;
449     }
450     else
451         return bufferIdLessThan(leftBufferId, rightBufferId);
452 }
453
454
455 bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
456 {
457     // NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
458     // NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
459
460     return QSortFilterProxyModel::lessThan(source_left, source_right);
461 }
462
463
464 QVariant BufferViewFilter::data(const QModelIndex &index, int role) const
465 {
466     switch (role) {
467     case Qt::FontRole:
468     case Qt::ForegroundRole:
469     case Qt::BackgroundRole:
470     case Qt::DecorationRole:
471         if ((config() && config()->disableDecoration()))
472             return QVariant();
473         return GraphicalUi::uiStyle()->bufferViewItemData(mapToSource(index), role);
474     case Qt::CheckStateRole:
475         return checkedState(index);
476     default:
477         return QSortFilterProxyModel::data(index, role);
478     }
479 }
480
481
482 QVariant BufferViewFilter::checkedState(const QModelIndex &index) const
483 {
484     if (!_editMode || !config())
485         return QVariant();
486
487     QModelIndex source_index = mapToSource(index);
488     if (source_index == QModelIndex() || sourceModel()->data(source_index, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
489         return QVariant();
490
491     BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
492     if (_toAdd.contains(bufferId))
493         return Qt::Checked;
494
495     if (_toTempRemove.contains(bufferId))
496         return Qt::PartiallyChecked;
497
498     if (_toRemove.contains(bufferId))
499         return Qt::Unchecked;
500
501     if (config()->bufferList().contains(bufferId))
502         return Qt::Checked;
503
504     if (config()->temporarilyRemovedBuffers().contains(bufferId))
505         return Qt::PartiallyChecked;
506
507     return Qt::Unchecked;
508 }
509
510
511 bool BufferViewFilter::setData(const QModelIndex &index, const QVariant &value, int role)
512 {
513     switch (role) {
514     case Qt::CheckStateRole:
515         return setCheckedState(index, Qt::CheckState(value.toInt()));
516     default:
517         return QSortFilterProxyModel::setData(index, value, role);
518     }
519 }
520
521
522 bool BufferViewFilter::setCheckedState(const QModelIndex &index, Qt::CheckState state)
523 {
524     QModelIndex source_index = mapToSource(index);
525     BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
526     if (!bufferId.isValid())
527         return false;
528
529     switch (state) {
530     case Qt::Unchecked:
531         _toAdd.remove(bufferId);
532         _toTempRemove.remove(bufferId);
533         _toRemove << bufferId;
534         break;
535     case Qt::PartiallyChecked:
536         _toAdd.remove(bufferId);
537         _toTempRemove << bufferId;
538         _toRemove.remove(bufferId);
539         break;
540     case Qt::Checked:
541         _toAdd << bufferId;
542         _toTempRemove.remove(bufferId);
543         _toRemove.remove(bufferId);
544         break;
545     default:
546         return false;
547     }
548     emit dataChanged(index, index);
549     return true;
550 }
551
552
553 bool BufferViewFilter::bufferIdLessThan(const BufferId &left, const BufferId &right)
554 {
555     Q_CHECK_PTR(Client::networkModel());
556     if (!Client::networkModel())
557         return true;
558
559     QModelIndex leftIndex = Client::networkModel()->bufferIndex(left);
560     QModelIndex rightIndex = Client::networkModel()->bufferIndex(right);
561
562     int leftType = Client::networkModel()->data(leftIndex, NetworkModel::BufferTypeRole).toInt();
563     int rightType = Client::networkModel()->data(rightIndex, NetworkModel::BufferTypeRole).toInt();
564
565     if (leftType != rightType)
566         return leftType < rightType;
567     else
568         return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
569 }