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