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