qa: Resolve Qt deprecation warnings - default-construct QFlags
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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                 // Treat an invalid QAbstractItemModel as an invalid QModelIndex
498                 resultingIndex = (newParent.model() ? newParent.model()->index(model()->rowCount(newParent) - 1, 0, newParent) : QModelIndex());
499             }
500             else
501                 resultingIndex = newParent;
502         }
503         else {
504             if (model()->hasChildren(currentIndex)) {
505                 // Treat an invalid QAbstractItemModel as an invalid QModelIndex
506                 resultingIndex = (currentIndex.model() ? currentIndex.model()->index(0, 0, currentIndex) : QModelIndex());
507             }
508             else
509                 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
510         }
511     }
512
513     if (!resultingIndex.isValid()) {
514         if (direction == Forward)
515             resultingIndex = model()->index(0, 0, QModelIndex());
516         else {
517             // Assume model is valid
518             resultingIndex = lastNetIndex.model()->index(model()->rowCount(lastNetIndex) - 1, 0, lastNetIndex);
519         }
520     }
521
522     selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
523     selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
524 }
525
526 void BufferView::selectFirstBuffer()
527 {
528     int networksCount = model()->rowCount(QModelIndex());
529     if (networksCount == 0) {
530         return;
531     }
532
533     QModelIndex bufferIndex;
534     for (int row = 0; row < networksCount; row++) {
535         QModelIndex networkIndex = model()->index(row, 0, QModelIndex());
536         int childCount = model()->rowCount(networkIndex);
537         if (childCount > 0) {
538             bufferIndex = model()->index(0, 0, networkIndex);
539             break;
540         }
541     }
542
543     if (!bufferIndex.isValid()) {
544         return;
545     }
546
547     selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
548     selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
549 }
550
551 void BufferView::wheelEvent(QWheelEvent* event)
552 {
553     if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
554         return TreeViewTouch::wheelEvent(event);
555
556     int rowDelta = (event->delta() > 0) ? -1 : 1;
557     changeBuffer((Direction)rowDelta);
558 }
559
560 void BufferView::hideCurrentBuffer()
561 {
562     QModelIndex index = selectionModel()->currentIndex();
563     if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
564         return;
565
566     BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
567
568     // 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.
569     changeBuffer(Backward);
570
571     config()->requestRemoveBuffer(bufferId);
572 }
573
574 void BufferView::filterTextChanged(const QString& filterString)
575 {
576     auto* filter = qobject_cast<BufferViewFilter*>(model());
577     if (!filter) {
578         return;
579     }
580     filter->setFilterString(filterString);
581     on_configChanged();  // make sure collapsation is correct
582 }
583
584 void BufferView::changeHighlight(BufferView::Direction direction)
585 {
586     // If for some weird reason we get a new delegate
587     auto delegate = qobject_cast<BufferViewDelegate*>(itemDelegate(_currentHighlight));
588     if (delegate) {
589         delegate->currentHighlight = QModelIndex();
590     }
591
592     QModelIndex newIndex = _currentHighlight;
593     if (!newIndex.isValid()) {
594         newIndex = model()->index(0, 0);
595     }
596
597     if (direction == Backward) {
598         newIndex = indexBelow(newIndex);
599     }
600     else {
601         newIndex = indexAbove(newIndex);
602     }
603
604     if (!newIndex.isValid()) {
605         return;
606     }
607
608     _currentHighlight = newIndex;
609
610     delegate = qobject_cast<BufferViewDelegate*>(itemDelegate(_currentHighlight));
611     if (delegate) {
612         delegate->currentHighlight = _currentHighlight;
613     }
614     viewport()->update();
615 }
616
617 void BufferView::selectHighlighted()
618 {
619     if (_currentHighlight.isValid()) {
620         selectionModel()->setCurrentIndex(_currentHighlight, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
621         selectionModel()->select(_currentHighlight, QItemSelectionModel::ClearAndSelect);
622     }
623     else {
624         selectFirstBuffer();
625     }
626
627     clearHighlight();
628 }
629
630 void BufferView::clearHighlight()
631 {
632     // If for some weird reason we get a new delegate
633     auto delegate = qobject_cast<BufferViewDelegate*>(itemDelegate(_currentHighlight));
634     if (delegate) {
635         delegate->currentHighlight = QModelIndex();
636     }
637     _currentHighlight = QModelIndex();
638     viewport()->update();
639 }
640
641 // ****************************************
642 //  BufferViewDelegate
643 // ****************************************
644 class ColorsChangedEvent : public QEvent
645 {
646 public:
647     ColorsChangedEvent()
648         : QEvent(QEvent::User){};
649 };
650
651 BufferViewDelegate::BufferViewDelegate(QObject* parent)
652     : QStyledItemDelegate(parent)
653 {}
654
655 void BufferViewDelegate::customEvent(QEvent* event)
656 {
657     if (event->type() != QEvent::User)
658         return;
659
660     event->accept();
661 }
662
663 bool BufferViewDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
664 {
665     if (event->type() != QEvent::MouseButtonRelease)
666         return QStyledItemDelegate::editorEvent(event, model, option, index);
667
668     if (!(model->flags(index) & Qt::ItemIsUserCheckable))
669         return QStyledItemDelegate::editorEvent(event, model, option, index);
670
671     QVariant value = index.data(Qt::CheckStateRole);
672     if (!value.isValid())
673         return QStyledItemDelegate::editorEvent(event, model, option, index);
674
675     QStyleOptionViewItem viewOpt(option);
676     initStyleOption(&viewOpt, index);
677
678     QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
679     auto* me = static_cast<QMouseEvent*>(event);
680
681     if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
682         return QStyledItemDelegate::editorEvent(event, model, option, index);
683
684     auto state = static_cast<Qt::CheckState>(value.toInt());
685     if (state == Qt::Unchecked)
686         state = Qt::PartiallyChecked;
687     else if (state == Qt::PartiallyChecked)
688         state = Qt::Checked;
689     else
690         state = Qt::Unchecked;
691     model->setData(index, state, Qt::CheckStateRole);
692     return true;
693 }
694
695 // ==============================
696 //  BufferView Dock
697 // ==============================
698 BufferViewDock::BufferViewDock(BufferViewConfig* config, QWidget* parent)
699     : QDockWidget(parent)
700     , _childWidget(nullptr)
701     , _widget(new QWidget(parent))
702     , _filterEdit(new QLineEdit(parent))
703     , _active(false)
704     , _title(config->bufferViewName())
705 {
706     setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
707     toggleViewAction()->setData(config->bufferViewId());
708     setAllowedAreas(Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea);
709     connect(config, &BufferViewConfig::bufferViewNameSet, this, &BufferViewDock::bufferViewRenamed);
710     connect(config, &BufferViewConfig::configChanged, this, &BufferViewDock::configChanged);
711     updateTitle();
712
713     _widget->setLayout(new QVBoxLayout);
714     _widget->layout()->setSpacing(0);
715     _widget->layout()->setContentsMargins(0, 0, 0, 0);
716
717     // We need to potentially hide it early, so it doesn't flicker
718     _filterEdit->setVisible(config->showSearch());
719     _filterEdit->setFocusPolicy(Qt::ClickFocus);
720     _filterEdit->installEventFilter(this);
721     _filterEdit->setPlaceholderText(tr("Search..."));
722     connect(_filterEdit, &QLineEdit::returnPressed, this, &BufferViewDock::onFilterReturnPressed);
723
724     _widget->layout()->addWidget(_filterEdit);
725     QDockWidget::setWidget(_widget);
726 }
727
728 void BufferViewDock::setLocked(bool locked)
729 {
730     if (locked) {
731         setFeatures({});
732     }
733     else {
734         setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
735     }
736 }
737
738 void BufferViewDock::updateTitle()
739 {
740     QString title = _title;
741     if (isActive())
742         title.prepend(QString::fromUtf8("• "));
743     setWindowTitle(title);
744 }
745
746 void BufferViewDock::configChanged()
747 {
748     if (_filterEdit->isVisible() != config()->showSearch()) {
749         _filterEdit->setVisible(config()->showSearch());
750         _filterEdit->clear();
751     }
752 }
753
754 void BufferViewDock::onFilterReturnPressed()
755 {
756     if (_oldFocusItem) {
757         _oldFocusItem->setFocus();
758         _oldFocusItem = nullptr;
759     }
760
761     if (!config()->showSearch()) {
762         _filterEdit->setVisible(false);
763     }
764
765     BufferView* view = bufferView();
766     if (!view) {
767         return;
768     }
769
770     if (!_filterEdit->text().isEmpty()) {
771         view->selectHighlighted();
772         _filterEdit->clear();
773     }
774     else {
775         view->clearHighlight();
776     }
777 }
778
779 void BufferViewDock::setActive(bool active)
780 {
781     if (active != isActive()) {
782         _active = active;
783         updateTitle();
784         if (active) {
785             raise();  // for tabbed docks
786         }
787     }
788 }
789
790 bool BufferViewDock::eventFilter(QObject* object, QEvent* event)
791 {
792     if (object != _filterEdit) {
793         return false;
794     }
795
796    if (event->type() == QEvent::FocusOut) {
797        if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
798            _filterEdit->setVisible(false);
799            return true;
800        }
801    }
802    else if (event->type() == QEvent::KeyRelease) {
803        auto keyEvent = static_cast<QKeyEvent*>(event);
804
805        BufferView* view = bufferView();
806        if (!view) {
807            return false;
808        }
809
810        switch (keyEvent->key()) {
811        case Qt::Key_Escape: {
812            _filterEdit->clear();
813
814            if (!_oldFocusItem) {
815                return false;
816            }
817
818            _oldFocusItem->setFocus();
819            _oldFocusItem = nullptr;
820            return true;
821        }
822        case Qt::Key_Down:
823            view->changeHighlight(BufferView::Backward);
824            return true;
825        case Qt::Key_Up:
826            view->changeHighlight(BufferView::Forward);
827            return true;
828        default:
829            break;
830        }
831
832        return false;
833    }
834
835    return false;
836 }
837
838 void BufferViewDock::bufferViewRenamed(const QString& newName)
839 {
840     _title = newName;
841     updateTitle();
842     toggleViewAction()->setText(newName);
843 }
844
845 int BufferViewDock::bufferViewId() const
846 {
847     BufferView* view = bufferView();
848     if (!view)
849         return 0;
850
851     if (view->config())
852         return view->config()->bufferViewId();
853     else
854         return 0;
855 }
856
857 BufferViewConfig* BufferViewDock::config() const
858 {
859     BufferView* view = bufferView();
860     if (!view)
861         return nullptr;
862     else
863         return view->config();
864 }
865
866 void BufferViewDock::setWidget(QWidget* newWidget)
867 {
868     _widget->layout()->addWidget(newWidget);
869     _childWidget = newWidget;
870
871     connect(_filterEdit, &QLineEdit::textChanged, bufferView(), &BufferView::filterTextChanged);
872 }
873
874 void BufferViewDock::activateFilter()
875 {
876     if (!_filterEdit->isVisible()) {
877         _filterEdit->setVisible(true);
878     }
879
880     _oldFocusItem = qApp->focusWidget();
881
882     _filterEdit->setFocus();
883 }
884
885
886 void BufferViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
887 {
888     QStyleOptionViewItem newOption = option;
889     if (index == currentHighlight) {
890         newOption.state |= QStyle::State_HasFocus;
891     }
892     QStyledItemDelegate::paint(painter, newOption, index);
893 }