Cleanup allowing for tags to be available at later points, adds TAGMSG
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2019 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 "bufferview.h"
22
23 #include <QAction>
24 #include <QApplication>
25 #include <QFlags>
26 #include <QHeaderView>
27 #include <QLineEdit>
28 #include <QMenu>
29 #include <QMessageBox>
30 #include <QSet>
31 #include <QVBoxLayout>
32
33 #include "action.h"
34 #include "buffermodel.h"
35 #include "buffersettings.h"
36 #include "buffersyncer.h"
37 #include "bufferviewfilter.h"
38 #include "client.h"
39 #include "contextmenuactionprovider.h"
40 #include "graphicalui.h"
41 #include "network.h"
42 #include "networkmodel.h"
43
44 /*****************************************
45  * The TreeView showing the Buffers
46  *****************************************/
47 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
48 // to be on the safe side: call QTreeView's method aswell (or TreeViewTouch's)
49 BufferView::BufferView(QWidget* parent)
50     : TreeViewTouch(parent)
51 {
52     connect(this, &QTreeView::collapsed, this, &BufferView::storeExpandedState);
53     connect(this, &QTreeView::expanded, this, &BufferView::storeExpandedState);
54
55     setSelectionMode(QAbstractItemView::ExtendedSelection);
56
57     QAbstractItemDelegate* oldDelegate = itemDelegate();
58     auto* tristateDelegate = new BufferViewDelegate(this);
59     setItemDelegate(tristateDelegate);
60     delete oldDelegate;
61 }
62
63 void BufferView::init()
64 {
65     header()->setContextMenuPolicy(Qt::ActionsContextMenu);
66     hideColumn(1);
67     hideColumn(2);
68     setIndentation(10);
69
70     // New entries will be expanded automatically when added; no need to call expandAll()
71
72     header()->hide();  // nobody seems to use this anyway
73
74     setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
75
76     setAnimated(true);
77
78     // FIXME This is to workaround bug #663
79     setUniformRowHeights(true);
80
81 #ifndef QT_NO_DRAGANDDROP
82     setDragEnabled(true);
83     setAcceptDrops(true);
84     setDropIndicatorShown(true);
85 #endif
86
87     setSortingEnabled(true);
88     sortByColumn(0, Qt::AscendingOrder);
89
90 #if defined Q_OS_MACOS || defined Q_OS_WIN
91     // afaik this is better on Mac and Windows
92     connect(this, &QAbstractItemView::activated, this, &BufferView::joinChannel, Qt::UniqueConnection);
93 #else
94     connect(this, &QAbstractItemView::doubleClicked, this, &BufferView::joinChannel, Qt::UniqueConnection);
95 #endif
96 }
97
98 void BufferView::setModel(QAbstractItemModel* model)
99 {
100     delete selectionModel();
101
102     TreeViewTouch::setModel(model);
103     init();
104     // remove old Actions
105     QList<QAction*> oldactions = header()->actions();
106     foreach (QAction* action, oldactions) {
107         header()->removeAction(action);
108         action->deleteLater();
109     }
110
111     if (!model)
112         return;
113
114     QString sectionName;
115     QAction* showSection;
116     for (int i = 1; i < model->columnCount(); i++) {
117         sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
118         showSection = new QAction(sectionName, header());
119         showSection->setCheckable(true);
120         showSection->setChecked(!isColumnHidden(i));
121         showSection->setProperty("column", i);
122         connect(showSection, &QAction::toggled, this, &BufferView::toggleHeader);
123         header()->addAction(showSection);
124     }
125
126     connect(model, &QAbstractItemModel::layoutChanged, this, &BufferView::on_layoutChanged);
127
128     // Make sure collapsation is correct after setting a model
129     // This might not be needed here, only in BufferView::setFilteredModel().  If issues arise, just
130     // move down to setFilteredModel (which calls this function).
131     setExpandedState();
132 }
133
134 void BufferView::setFilteredModel(QAbstractItemModel* model_, BufferViewConfig* config)
135 {
136     auto* filter = qobject_cast<BufferViewFilter*>(model());
137     if (filter) {
138         filter->setConfig(config);
139         setConfig(config);
140         return;
141     }
142
143     if (model()) {
144         disconnect(this, nullptr, model(), nullptr);
145         disconnect(model(), nullptr, this, nullptr);
146     }
147
148     if (!model_) {
149         setModel(model_);
150     }
151     else {
152         auto* filter = new BufferViewFilter(model_, config);
153         setModel(filter);
154         connect(filter, &BufferViewFilter::configChanged, this, &BufferView::on_configChanged);
155     }
156     setConfig(config);
157 }
158
159 void BufferView::setConfig(BufferViewConfig* config)
160 {
161     if (_config == config)
162         return;
163
164     if (_config) {
165         disconnect(_config, nullptr, this, nullptr);
166     }
167
168     _config = config;
169     if (config) {
170         connect(config, &BufferViewConfig::networkIdSet, this, &BufferView::setRootIndexForNetworkId);
171         setRootIndexForNetworkId(config->networkId());
172     }
173     else {
174         setIndentation(10);
175         setRootIndex(QModelIndex());
176     }
177 }
178
179 void BufferView::setRootIndexForNetworkId(const NetworkId& networkId)
180 {
181     if (!networkId.isValid() || !model()) {
182         setIndentation(10);
183         setRootIndex(QModelIndex());
184     }
185     else {
186         setIndentation(5);
187         int networkCount = model()->rowCount();
188         QModelIndex child;
189         for (int i = 0; i < networkCount; i++) {
190             child = model()->index(i, 0);
191             if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
192                 setRootIndex(child);
193         }
194     }
195 }
196
197 void BufferView::joinChannel(const QModelIndex& index)
198 {
199     BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
200
201     if (bufferType != BufferInfo::ChannelBuffer)
202         return;
203
204     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
205
206     Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
207 }
208
209 void BufferView::dropEvent(QDropEvent* event)
210 {
211     QModelIndex index = indexAt(event->pos());
212
213     QRect indexRect = visualRect(index);
214     QPoint cursorPos = event->pos();
215
216     // check if we're really _on_ the item and not indicating a move to just above or below the item
217     // Magic margin number for this is from QAbstractItemViewPrivate::position()
218     const int margin = 2;
219     if (cursorPos.y() - indexRect.top() < margin || indexRect.bottom() - cursorPos.y() < margin)
220         return TreeViewTouch::dropEvent(event);
221
222     // If more than one buffer was being dragged, treat this as a rearrangement instead of a merge request
223     QList<QPair<NetworkId, BufferId>> bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
224     if (bufferList.count() != 1)
225         return TreeViewTouch::dropEvent(event);
226
227     // Get the Buffer ID of the buffer that was being dragged
228     BufferId bufferId2 = bufferList[0].second;
229
230     // Get the Buffer ID of the target buffer
231     BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
232
233     // If the source and target are the same buffer, this was an aborted rearrangement
234     if (bufferId1 == bufferId2)
235         return TreeViewTouch::dropEvent(event);
236
237     // Get index of buffer that was being dragged
238     QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
239
240     // If the buffer being dragged is a channel and we're still joined to it, treat this as a rearrangement
241     // This prevents us from being joined to a channel with no associated UI elements
242     if (index2.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && index2.data(NetworkModel::ItemActiveRole) == true)
243         return TreeViewTouch::dropEvent(event);
244
245     // If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
246     if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer
247         && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
248         return TreeViewTouch::dropEvent(event);
249
250     // If the target buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
251     if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer
252         && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
253         return TreeViewTouch::dropEvent(event);
254
255     // Confirm that the user really wants to merge the buffers before doing so
256     int res = QMessageBox::question(nullptr,
257                                     tr("Merge buffers permanently?"),
258                                     tr("Do you want to merge the buffer \"%1\" permanently into buffer \"%2\"?\n This cannot be reversed!")
259                                         .arg(Client::networkModel()->bufferName(bufferId2))
260                                         .arg(Client::networkModel()->bufferName(bufferId1)),
261                                     QMessageBox::Yes | QMessageBox::No,
262                                     QMessageBox::No);
263     if (res == QMessageBox::Yes) {
264         Client::mergeBuffersPermanently(bufferId1, bufferId2);
265     }
266 }
267
268 void BufferView::removeSelectedBuffers(bool permanently)
269 {
270     if (!config())
271         return;
272
273     BufferId bufferId;
274     QSet<BufferId> removedRows;
275     foreach (QModelIndex index, selectionModel()->selectedIndexes()) {
276         if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
277             continue;
278
279         bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
280         if (removedRows.contains(bufferId))
281             continue;
282
283         removedRows << bufferId;
284     }
285
286     foreach (BufferId bufferId, removedRows) {
287         if (permanently)
288             config()->requestRemoveBufferPermanently(bufferId);
289         else
290             config()->requestRemoveBuffer(bufferId);
291     }
292 }
293
294 void BufferView::rowsInserted(const QModelIndex& parent, int start, int end)
295 {
296     TreeViewTouch::rowsInserted(parent, start, end);
297
298     // ensure that newly inserted network nodes are expanded per default
299     if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
300         return;
301
302     setExpandedState(parent);
303 }
304
305 void BufferView::on_layoutChanged()
306 {
307     int numNets = model()->rowCount(QModelIndex());
308     for (int row = 0; row < numNets; row++) {
309         QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
310         setExpandedState(networkIdx);
311     }
312 }
313
314 void BufferView::on_configChanged()
315 {
316     Q_ASSERT(model());
317
318     // Expand/collapse as needed
319     setExpandedState();
320
321     if (config()) {
322         // update selection to current one
323         Client::bufferModel()->synchronizeView(this);
324     }
325 }
326
327 void BufferView::setExpandedState()
328 {
329     // Expand all active networks, collapse inactive ones... unless manually changed
330     QModelIndex networkIdx;
331     NetworkId networkId;
332     for (int row = 0; row < model()->rowCount(); row++) {
333         networkIdx = model()->index(row, 0);
334         if (model()->rowCount(networkIdx) == 0)
335             continue;
336
337         networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
338         if (!networkId.isValid())
339             continue;
340
341         setExpandedState(networkIdx);
342     }
343 }
344
345 void BufferView::storeExpandedState(const QModelIndex& networkIdx)
346 {
347     NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
348
349     int oldState = 0;
350     if (isExpanded(networkIdx))
351         oldState |= WasExpanded;
352     if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
353         oldState |= WasActive;
354
355     _expandedState[networkId] = oldState;
356 }
357
358 void BufferView::setExpandedState(const QModelIndex& networkIdx)
359 {
360     if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
361         return;
362
363     if (model()->rowCount(networkIdx) == 0)
364         return;
365
366     NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
367
368     bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
369     bool expandNetwork = networkActive;
370     if (_expandedState.contains(networkId)) {
371         int oldState = _expandedState[networkId];
372         if ((bool)(oldState & WasActive) == networkActive)
373             expandNetwork = (bool)(oldState & WasExpanded);
374     }
375
376     if (expandNetwork != isExpanded(networkIdx)) {
377         update(networkIdx);
378         setExpanded(networkIdx, expandNetwork);
379     }
380     storeExpandedState(networkIdx);  // this call is needed to keep track of the isActive state
381 }
382
383 void BufferView::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles)
384 {
385     TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
386
387     // determine how many items have been changed and if any of them is a networkitem
388     // which just swichted from active to inactive or vice versa
389     if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
390         return;
391
392     for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
393         QModelIndex networkIdx = topLeft.sibling(i, 0);
394         setExpandedState(networkIdx);
395     }
396 }
397
398 void BufferView::toggleHeader(bool checked)
399 {
400     auto* action = qobject_cast<QAction*>(sender());
401     header()->setSectionHidden((action->property("column")).toInt(), !checked);
402 }
403
404 void BufferView::contextMenuEvent(QContextMenuEvent* event)
405 {
406     QModelIndex index = indexAt(event->pos());
407     if (!index.isValid())
408         index = rootIndex();
409
410     QMenu contextMenu(this);
411
412     if (index.isValid()) {
413         addActionsToMenu(&contextMenu, index);
414     }
415
416     addFilterActions(&contextMenu, index);
417
418     if (!contextMenu.actions().isEmpty())
419         contextMenu.exec(QCursor::pos());
420 }
421
422 void BufferView::addActionsToMenu(QMenu* contextMenu, const QModelIndex& index)
423 {
424     QModelIndexList indexList = selectedIndexes();
425     // make sure the item we clicked on is first
426     indexList.removeAll(index);
427     indexList.prepend(index);
428
429     GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, &BufferView::menuActionTriggered, (bool)config());
430 }
431
432 void BufferView::addFilterActions(QMenu* contextMenu, const QModelIndex& index)
433 {
434     auto* filter = qobject_cast<BufferViewFilter*>(model());
435     if (filter) {
436         QList<QAction*> filterActions = filter->actions(index);
437         if (!filterActions.isEmpty()) {
438             contextMenu->addSeparator();
439             foreach (QAction* action, filterActions) {
440                 contextMenu->addAction(action);
441             }
442         }
443     }
444 }
445
446 void BufferView::menuActionTriggered(QAction* result)
447 {
448     ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
449     switch (type) {
450     case ContextMenuActionProvider::HideBufferTemporarily:
451         removeSelectedBuffers();
452         break;
453     case ContextMenuActionProvider::HideBufferPermanently:
454         removeSelectedBuffers(true);
455         break;
456     default:
457         return;
458     }
459 }
460
461 void BufferView::nextBuffer()
462 {
463     changeBuffer(Forward);
464 }
465
466 void BufferView::previousBuffer()
467 {
468     changeBuffer(Backward);
469 }
470
471 void BufferView::changeBuffer(Direction direction)
472 {
473     QModelIndex currentIndex = selectionModel()->currentIndex();
474     QModelIndex resultingIndex;
475
476     QModelIndex lastNetIndex = model()->index(model()->rowCount() - 1, 0, QModelIndex());
477
478     if (currentIndex.parent().isValid()) {
479         // If we are a child node just switch among siblings unless it's the first/last child
480         resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
481
482         if (!resultingIndex.isValid()) {
483             QModelIndex parent = currentIndex.parent();
484             if (direction == Backward)
485                 resultingIndex = parent;
486             else
487                 resultingIndex = parent.sibling(parent.row() + direction, 0);
488         }
489     }
490     else {
491         // If we have a toplevel node, try and get an adjacent child
492         if (direction == Backward) {
493             QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
494             if (currentIndex.row() == 0)
495                 newParent = lastNetIndex;
496             if (model()->hasChildren(newParent))
497                 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
498             else
499                 resultingIndex = newParent;
500         }
501         else {
502             if (model()->hasChildren(currentIndex))
503                 resultingIndex = currentIndex.child(0, 0);
504             else
505                 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
506         }
507     }
508
509     if (!resultingIndex.isValid()) {
510         if (direction == Forward)
511             resultingIndex = model()->index(0, 0, QModelIndex());
512         else
513             resultingIndex = lastNetIndex.child(model()->rowCount(lastNetIndex) - 1, 0);
514     }
515
516     selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
517     selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
518 }
519
520 void BufferView::selectFirstBuffer()
521 {
522     int networksCount = model()->rowCount(QModelIndex());
523     if (networksCount == 0) {
524         return;
525     }
526
527     QModelIndex bufferIndex;
528     for (int row = 0; row < networksCount; row++) {
529         QModelIndex networkIndex = model()->index(row, 0, QModelIndex());
530         int childCount = model()->rowCount(networkIndex);
531         if (childCount > 0) {
532             bufferIndex = model()->index(0, 0, networkIndex);
533             break;
534         }
535     }
536
537     if (!bufferIndex.isValid()) {
538         return;
539     }
540
541     selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
542     selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
543 }
544
545 void BufferView::wheelEvent(QWheelEvent* event)
546 {
547     if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
548         return TreeViewTouch::wheelEvent(event);
549
550     int rowDelta = (event->delta() > 0) ? -1 : 1;
551     changeBuffer((Direction)rowDelta);
552 }
553
554 void BufferView::hideCurrentBuffer()
555 {
556     QModelIndex index = selectionModel()->currentIndex();
557     if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
558         return;
559
560     BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
561
562     // The check above means we won't be looking at a network, which should always be the first row, so we can just go backwards.
563     changeBuffer(Backward);
564
565     config()->requestRemoveBuffer(bufferId);
566 }
567
568 void BufferView::filterTextChanged(const QString& filterString)
569 {
570     auto* filter = qobject_cast<BufferViewFilter*>(model());
571     if (!filter) {
572         return;
573     }
574     filter->setFilterString(filterString);
575     on_configChanged();  // make sure collapsation is correct
576 }
577
578 void BufferView::changeHighlight(BufferView::Direction direction)
579 {
580     // If for some weird reason we get a new delegate
581     auto delegate = qobject_cast<BufferViewDelegate*>(itemDelegate(_currentHighlight));
582     if (delegate) {
583         delegate->currentHighlight = QModelIndex();
584     }
585
586     QModelIndex newIndex = _currentHighlight;
587     if (!newIndex.isValid()) {
588         newIndex = model()->index(0, 0);
589     }
590
591     if (direction == Backward) {
592         newIndex = indexBelow(newIndex);
593     }
594     else {
595         newIndex = indexAbove(newIndex);
596     }
597
598     if (!newIndex.isValid()) {
599         return;
600     }
601
602     _currentHighlight = newIndex;
603
604     delegate = qobject_cast<BufferViewDelegate*>(itemDelegate(_currentHighlight));
605     if (delegate) {
606         delegate->currentHighlight = _currentHighlight;
607     }
608     viewport()->update();
609 }
610
611 void BufferView::selectHighlighted()
612 {
613     if (_currentHighlight.isValid()) {
614         selectionModel()->setCurrentIndex(_currentHighlight, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
615         selectionModel()->select(_currentHighlight, QItemSelectionModel::ClearAndSelect);
616     }
617     else {
618         selectFirstBuffer();
619     }
620
621     clearHighlight();
622 }
623
624 void BufferView::clearHighlight()
625 {
626     // If for some weird reason we get a new delegate
627     auto delegate = qobject_cast<BufferViewDelegate*>(itemDelegate(_currentHighlight));
628     if (delegate) {
629         delegate->currentHighlight = QModelIndex();
630     }
631     _currentHighlight = QModelIndex();
632     viewport()->update();
633 }
634
635 // ****************************************
636 //  BufferViewDelegate
637 // ****************************************
638 class ColorsChangedEvent : public QEvent
639 {
640 public:
641     ColorsChangedEvent()
642         : QEvent(QEvent::User){};
643 };
644
645 BufferViewDelegate::BufferViewDelegate(QObject* parent)
646     : QStyledItemDelegate(parent)
647 {}
648
649 void BufferViewDelegate::customEvent(QEvent* event)
650 {
651     if (event->type() != QEvent::User)
652         return;
653
654     event->accept();
655 }
656
657 bool BufferViewDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
658 {
659     if (event->type() != QEvent::MouseButtonRelease)
660         return QStyledItemDelegate::editorEvent(event, model, option, index);
661
662     if (!(model->flags(index) & Qt::ItemIsUserCheckable))
663         return QStyledItemDelegate::editorEvent(event, model, option, index);
664
665     QVariant value = index.data(Qt::CheckStateRole);
666     if (!value.isValid())
667         return QStyledItemDelegate::editorEvent(event, model, option, index);
668
669     QStyleOptionViewItem viewOpt(option);
670     initStyleOption(&viewOpt, index);
671
672     QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
673     auto* me = static_cast<QMouseEvent*>(event);
674
675     if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
676         return QStyledItemDelegate::editorEvent(event, model, option, index);
677
678     auto state = static_cast<Qt::CheckState>(value.toInt());
679     if (state == Qt::Unchecked)
680         state = Qt::PartiallyChecked;
681     else if (state == Qt::PartiallyChecked)
682         state = Qt::Checked;
683     else
684         state = Qt::Unchecked;
685     model->setData(index, state, Qt::CheckStateRole);
686     return true;
687 }
688
689 // ==============================
690 //  BufferView Dock
691 // ==============================
692 BufferViewDock::BufferViewDock(BufferViewConfig* config, QWidget* parent)
693     : QDockWidget(parent)
694     , _childWidget(nullptr)
695     , _widget(new QWidget(parent))
696     , _filterEdit(new QLineEdit(parent))
697     , _active(false)
698     , _title(config->bufferViewName())
699 {
700     setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
701     toggleViewAction()->setData(config->bufferViewId());
702     setAllowedAreas(Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea);
703     connect(config, &BufferViewConfig::bufferViewNameSet, this, &BufferViewDock::bufferViewRenamed);
704     connect(config, &BufferViewConfig::configChanged, this, &BufferViewDock::configChanged);
705     updateTitle();
706
707     _widget->setLayout(new QVBoxLayout);
708     _widget->layout()->setSpacing(0);
709     _widget->layout()->setContentsMargins(0, 0, 0, 0);
710
711     // We need to potentially hide it early, so it doesn't flicker
712     _filterEdit->setVisible(config->showSearch());
713     _filterEdit->setFocusPolicy(Qt::ClickFocus);
714     _filterEdit->installEventFilter(this);
715     _filterEdit->setPlaceholderText(tr("Search..."));
716     connect(_filterEdit, &QLineEdit::returnPressed, this, &BufferViewDock::onFilterReturnPressed);
717
718     _widget->layout()->addWidget(_filterEdit);
719     QDockWidget::setWidget(_widget);
720 }
721
722 void BufferViewDock::setLocked(bool locked)
723 {
724     if (locked) {
725         setFeatures(nullptr);
726     }
727     else {
728         setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
729     }
730 }
731
732 void BufferViewDock::updateTitle()
733 {
734     QString title = _title;
735     if (isActive())
736         title.prepend(QString::fromUtf8("• "));
737     setWindowTitle(title);
738 }
739
740 void BufferViewDock::configChanged()
741 {
742     if (_filterEdit->isVisible() != config()->showSearch()) {
743         _filterEdit->setVisible(config()->showSearch());
744         _filterEdit->clear();
745     }
746 }
747
748 void BufferViewDock::onFilterReturnPressed()
749 {
750     if (_oldFocusItem) {
751         _oldFocusItem->setFocus();
752         _oldFocusItem = nullptr;
753     }
754
755     if (!config()->showSearch()) {
756         _filterEdit->setVisible(false);
757     }
758
759     BufferView* view = bufferView();
760     if (!view) {
761         return;
762     }
763
764     if (!_filterEdit->text().isEmpty()) {
765         view->selectHighlighted();
766         _filterEdit->clear();
767     }
768     else {
769         view->clearHighlight();
770     }
771 }
772
773 void BufferViewDock::setActive(bool active)
774 {
775     if (active != isActive()) {
776         _active = active;
777         updateTitle();
778         if (active) {
779             raise();  // for tabbed docks
780         }
781     }
782 }
783
784 bool BufferViewDock::eventFilter(QObject* object, QEvent* event)
785 {
786     if (object != _filterEdit) {
787         return false;
788     }
789
790    if (event->type() == QEvent::FocusOut) {
791        if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
792            _filterEdit->setVisible(false);
793            return true;
794        }
795    }
796    else if (event->type() == QEvent::KeyRelease) {
797        auto keyEvent = static_cast<QKeyEvent*>(event);
798
799        BufferView* view = bufferView();
800        if (!view) {
801            return false;
802        }
803
804        switch (keyEvent->key()) {
805        case Qt::Key_Escape: {
806            _filterEdit->clear();
807
808            if (!_oldFocusItem) {
809                return false;
810            }
811
812            _oldFocusItem->setFocus();
813            _oldFocusItem = nullptr;
814            return true;
815        }
816        case Qt::Key_Down:
817            view->changeHighlight(BufferView::Backward);
818            return true;
819        case Qt::Key_Up:
820            view->changeHighlight(BufferView::Forward);
821            return true;
822        default:
823            break;
824        }
825
826        return false;
827    }
828
829    return false;
830 }
831
832 void BufferViewDock::bufferViewRenamed(const QString& newName)
833 {
834     _title = newName;
835     updateTitle();
836     toggleViewAction()->setText(newName);
837 }
838
839 int BufferViewDock::bufferViewId() const
840 {
841     BufferView* view = bufferView();
842     if (!view)
843         return 0;
844
845     if (view->config())
846         return view->config()->bufferViewId();
847     else
848         return 0;
849 }
850
851 BufferViewConfig* BufferViewDock::config() const
852 {
853     BufferView* view = bufferView();
854     if (!view)
855         return nullptr;
856     else
857         return view->config();
858 }
859
860 void BufferViewDock::setWidget(QWidget* newWidget)
861 {
862     _widget->layout()->addWidget(newWidget);
863     _childWidget = newWidget;
864
865     connect(_filterEdit, &QLineEdit::textChanged, bufferView(), &BufferView::filterTextChanged);
866 }
867
868 void BufferViewDock::activateFilter()
869 {
870     if (!_filterEdit->isVisible()) {
871         _filterEdit->setVisible(true);
872     }
873
874     _oldFocusItem = qApp->focusWidget();
875
876     _filterEdit->setFocus();
877 }
878
879
880 void BufferViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
881 {
882     QStyleOptionViewItem newOption = option;
883     if (index == currentHighlight) {
884         newOption.state |= QStyle::State_HasFocus;
885     }
886     QStyledItemDelegate::paint(painter, newOption, index);
887 }