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