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