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