uisupport: Join channels on doubleclick on all but Windows and OSX
[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 #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 #if QT_VERSION < 0x050000
396 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
397 {
398     TreeViewTouch::dataChanged(topLeft, bottomRight);
399 #else
400 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
401 {
402     TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
403 #endif
404
405     // determine how many items have been changed and if any of them is a networkitem
406     // which just swichted from active to inactive or vice versa
407     if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
408         return;
409
410     for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
411         QModelIndex networkIdx = topLeft.sibling(i, 0);
412         setExpandedState(networkIdx);
413     }
414 }
415
416
417 void BufferView::toggleHeader(bool checked)
418 {
419     QAction *action = qobject_cast<QAction *>(sender());
420     header()->setSectionHidden((action->property("column")).toInt(), !checked);
421 }
422
423
424 void BufferView::contextMenuEvent(QContextMenuEvent *event)
425 {
426     QModelIndex index = indexAt(event->pos());
427     if (!index.isValid())
428         index = rootIndex();
429
430     QMenu contextMenu(this);
431
432     if (index.isValid()) {
433         addActionsToMenu(&contextMenu, index);
434     }
435
436     addFilterActions(&contextMenu, index);
437
438     if (!contextMenu.actions().isEmpty())
439         contextMenu.exec(QCursor::pos());
440 }
441
442
443 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
444 {
445     QModelIndexList indexList = selectedIndexes();
446     // make sure the item we clicked on is first
447     indexList.removeAll(index);
448     indexList.prepend(index);
449
450     GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
451 }
452
453
454 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
455 {
456     BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
457     if (filter) {
458         QList<QAction *> filterActions = filter->actions(index);
459         if (!filterActions.isEmpty()) {
460             contextMenu->addSeparator();
461             foreach(QAction *action, filterActions) {
462                 contextMenu->addAction(action);
463             }
464         }
465     }
466 }
467
468
469 void BufferView::menuActionTriggered(QAction *result)
470 {
471     ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
472     switch (type) {
473     case ContextMenuActionProvider::HideBufferTemporarily:
474         removeSelectedBuffers();
475         break;
476     case ContextMenuActionProvider::HideBufferPermanently:
477         removeSelectedBuffers(true);
478         break;
479     default:
480         return;
481     }
482 }
483
484
485 void BufferView::nextBuffer()
486 {
487     changeBuffer(Forward);
488 }
489
490
491 void BufferView::previousBuffer()
492 {
493     changeBuffer(Backward);
494 }
495
496
497 void BufferView::changeBuffer(Direction direction)
498 {
499     QModelIndex currentIndex = selectionModel()->currentIndex();
500     QModelIndex resultingIndex;
501
502     if (currentIndex.parent().isValid()) {
503         //If we are a child node just switch among siblings unless it's the first/last child
504         resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
505
506         if (!resultingIndex.isValid()) {
507             QModelIndex parent = currentIndex.parent();
508             if (direction == Backward)
509                 resultingIndex = parent;
510             else
511                 resultingIndex = parent.sibling(parent.row() + direction, 0);
512         }
513     }
514     else {
515         //If we have a toplevel node, try and get an adjacent child
516         if (direction == Backward) {
517             QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
518             if (model()->hasChildren(newParent))
519                 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
520             else
521                 resultingIndex = newParent;
522         }
523         else {
524             if (model()->hasChildren(currentIndex))
525                 resultingIndex = currentIndex.child(0, 0);
526             else
527                 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
528         }
529     }
530
531     if (!resultingIndex.isValid())
532         return;
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(QString filterString)
588 {
589     BufferViewFilter *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 QSize(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 QSize(columnSize, 50);
614 }
615
616
617 // ****************************************
618 //  BufferViewDelgate
619 // ****************************************
620 class ColorsChangedEvent : public QEvent
621 {
622 public:
623     ColorsChangedEvent() : QEvent(QEvent::User) {};
624 };
625
626
627 BufferViewDelegate::BufferViewDelegate(QObject *parent)
628     : QStyledItemDelegate(parent)
629 {
630 }
631
632
633 void BufferViewDelegate::customEvent(QEvent *event)
634 {
635     if (event->type() != QEvent::User)
636         return;
637
638     event->accept();
639 }
640
641
642 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
643 {
644     if (event->type() != QEvent::MouseButtonRelease)
645         return QStyledItemDelegate::editorEvent(event, model, option, index);
646
647     if (!(model->flags(index) & Qt::ItemIsUserCheckable))
648         return QStyledItemDelegate::editorEvent(event, model, option, index);
649
650     QVariant value = index.data(Qt::CheckStateRole);
651     if (!value.isValid())
652         return QStyledItemDelegate::editorEvent(event, model, option, index);
653
654 #if QT_VERSION < 0x050000
655     QStyleOptionViewItemV4 viewOpt(option);
656 #else
657     QStyleOptionViewItem viewOpt(option);
658 #endif
659     initStyleOption(&viewOpt, index);
660
661     QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
662     QMouseEvent *me = static_cast<QMouseEvent *>(event);
663
664     if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
665         return QStyledItemDelegate::editorEvent(event, model, option, index);
666
667     Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
668     if (state == Qt::Unchecked)
669         state = Qt::PartiallyChecked;
670     else if (state == Qt::PartiallyChecked)
671         state = Qt::Checked;
672     else
673         state = Qt::Unchecked;
674     model->setData(index, state, Qt::CheckStateRole);
675     return true;
676 }
677
678
679 // ==============================
680 //  BufferView Dock
681 // ==============================
682 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
683     : QDockWidget(parent),
684     _childWidget(0),
685     _widget(new QWidget(parent)),
686     _filterEdit(new QLineEdit(parent)),
687     _active(false),
688     _title(config->bufferViewName())
689 {
690     setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
691     toggleViewAction()->setData(config->bufferViewId());
692     setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
693     connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
694     connect(config, SIGNAL(configChanged()), SLOT(configChanged()));
695     updateTitle();
696
697     _widget->setLayout(new QVBoxLayout);
698     _widget->layout()->setSpacing(0);
699     _widget->layout()->setContentsMargins(0, 0, 0, 0);
700
701     // We need to potentially hide it early, so it doesn't flicker
702     _filterEdit->setVisible(config->showSearch());
703     _filterEdit->setFocusPolicy(Qt::ClickFocus);
704     _filterEdit->installEventFilter(this);
705     _filterEdit->setPlaceholderText(tr("Search..."));
706     connect(_filterEdit, SIGNAL(returnPressed()), SLOT(onFilterReturnPressed()));
707
708     _widget->layout()->addWidget(_filterEdit);
709     QDockWidget::setWidget(_widget);
710 }
711
712
713 void BufferViewDock::updateTitle()
714 {
715     QString title = _title;
716     if (isActive())
717         title.prepend(QString::fromUtf8("• "));
718     setWindowTitle(title);
719 }
720
721 void BufferViewDock::configChanged()
722 {
723     if (_filterEdit->isVisible() != config()->showSearch()) {
724         _filterEdit->setVisible(config()->showSearch());
725         _filterEdit->clear();
726     }
727 }
728
729 void BufferViewDock::onFilterReturnPressed()
730 {
731     if (_oldFocusItem) {
732         _oldFocusItem->setFocus();
733         _oldFocusItem = 0;
734     }
735
736     if (!config()->showSearch()) {
737         _filterEdit->setVisible(false);
738     }
739
740     BufferView *view = bufferView();
741     if (!view || _filterEdit->text().isEmpty()) {
742         return;
743     }
744
745     view->selectFirstBuffer();
746     _filterEdit->clear();
747 }
748
749 void BufferViewDock::setActive(bool active)
750 {
751     if (active != isActive()) {
752         _active = active;
753         updateTitle();
754         if (active) {
755             raise();  // for tabbed docks
756         }
757     }
758 }
759
760 bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
761 {
762    if (object != _filterEdit)  {
763        return false;
764    }
765
766    if (event->type() == QEvent::FocusOut) {
767        if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
768            _filterEdit->setVisible(false);
769            return true;
770        }
771    } else if (event->type() == QEvent::KeyRelease) {
772        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
773        if (keyEvent->key() != Qt::Key_Escape) {
774            return false;
775        }
776
777        _filterEdit->clear();
778
779        if (_oldFocusItem) {
780            _oldFocusItem->setFocus();
781            _oldFocusItem = 0;
782        }
783
784        return true;
785    }
786
787    return false;
788 }
789
790 void BufferViewDock::bufferViewRenamed(const QString &newName)
791 {
792     _title = newName;
793     updateTitle();
794     toggleViewAction()->setText(newName);
795 }
796
797
798 int BufferViewDock::bufferViewId() const
799 {
800     BufferView *view = bufferView();
801     if (!view)
802         return 0;
803
804     if (view->config())
805         return view->config()->bufferViewId();
806     else
807         return 0;
808 }
809
810
811 BufferViewConfig *BufferViewDock::config() const
812 {
813     BufferView *view = bufferView();
814     if (!view)
815         return 0;
816     else
817         return view->config();
818 }
819
820 void BufferViewDock::setWidget(QWidget *newWidget)
821 {
822     _widget->layout()->addWidget(newWidget);
823     _childWidget = newWidget;
824
825     connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));
826 }
827
828 void BufferViewDock::activateFilter()
829 {
830     if (!_filterEdit->isVisible()) {
831         _filterEdit->setVisible(true);
832     }
833
834     _oldFocusItem = qApp->focusWidget();
835
836     _filterEdit->setFocus();
837 }