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