Don't use the QPointer::clear() function that was introduced in Qt5
[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     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     const int margin = 2;
234     if (cursorPos.y() - indexRect.top() < margin
235         || indexRect.bottom() - cursorPos.y() < margin)
236         return TreeViewTouch::dropEvent(event);
237
238     QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
239     if (bufferList.count() != 1)
240         return TreeViewTouch::dropEvent(event);
241
242     BufferId bufferId2 = bufferList[0].second;
243
244     if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
245         return TreeViewTouch::dropEvent(event);
246
247     if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
248         return TreeViewTouch::dropEvent(event);
249
250     BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
251     if (bufferId1 == bufferId2)
252         return TreeViewTouch::dropEvent(event);
253
254     int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
255         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)),
256         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
257     if (res == QMessageBox::Yes) {
258         Client::mergeBuffersPermanently(bufferId1, bufferId2);
259     }
260 }
261
262
263 void BufferView::removeSelectedBuffers(bool permanently)
264 {
265     if (!config())
266         return;
267
268     BufferId bufferId;
269     QSet<BufferId> removedRows;
270     foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
271         if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
272             continue;
273
274         bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
275         if (removedRows.contains(bufferId))
276             continue;
277
278         removedRows << bufferId;
279     }
280
281     foreach(BufferId bufferId, removedRows) {
282         if (permanently)
283             config()->requestRemoveBufferPermanently(bufferId);
284         else
285             config()->requestRemoveBuffer(bufferId);
286     }
287 }
288
289
290 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
291 {
292     TreeViewTouch::rowsInserted(parent, start, end);
293
294     // ensure that newly inserted network nodes are expanded per default
295     if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
296         return;
297
298     setExpandedState(parent);
299 }
300
301
302 void BufferView::on_layoutChanged()
303 {
304     int numNets = model()->rowCount(QModelIndex());
305     for (int row = 0; row < numNets; row++) {
306         QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
307         setExpandedState(networkIdx);
308     }
309 }
310
311
312 void BufferView::on_configChanged()
313 {
314     Q_ASSERT(model());
315
316     // expand all active networks... collapse inactive ones... unless manually changed
317     QModelIndex networkIdx;
318     NetworkId networkId;
319     for (int row = 0; row < model()->rowCount(); row++) {
320         networkIdx = model()->index(row, 0);
321         if (model()->rowCount(networkIdx) ==  0)
322             continue;
323
324         networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
325         if (!networkId.isValid())
326             continue;
327
328         setExpandedState(networkIdx);
329     }
330
331     if (config()) {
332         // update selection to current one
333         Client::bufferModel()->synchronizeView(this);
334     }
335 }
336
337
338 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
339 {
340     NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
341
342     int oldState = 0;
343     if (isExpanded(networkIdx))
344         oldState |= WasExpanded;
345     if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
346         oldState |= WasActive;
347
348     _expandedState[networkId] = oldState;
349 }
350
351
352 void BufferView::setExpandedState(const QModelIndex &networkIdx)
353 {
354     if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
355         return;
356
357     if (model()->rowCount(networkIdx) == 0)
358         return;
359
360     NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
361
362     bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
363     bool expandNetwork = networkActive;
364     if (_expandedState.contains(networkId)) {
365         int oldState = _expandedState[networkId];
366         if ((bool)(oldState & WasActive) == networkActive)
367             expandNetwork = (bool)(oldState & WasExpanded);
368     }
369
370     if (expandNetwork != isExpanded(networkIdx)) {
371         update(networkIdx);
372         setExpanded(networkIdx, expandNetwork);
373     }
374     storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
375 }
376
377 #if QT_VERSION < 0x050000
378 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
379 {
380     TreeViewTouch::dataChanged(topLeft, bottomRight);
381 #else
382 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
383 {
384     TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
385 #endif
386
387     // determine how many items have been changed and if any of them is a networkitem
388     // which just swichted from active to inactive or vice versa
389     if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
390         return;
391
392     for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
393         QModelIndex networkIdx = topLeft.sibling(i, 0);
394         setExpandedState(networkIdx);
395     }
396 }
397
398
399 void BufferView::toggleHeader(bool checked)
400 {
401     QAction *action = qobject_cast<QAction *>(sender());
402     header()->setSectionHidden((action->property("column")).toInt(), !checked);
403 }
404
405
406 void BufferView::contextMenuEvent(QContextMenuEvent *event)
407 {
408     QModelIndex index = indexAt(event->pos());
409     if (!index.isValid())
410         index = rootIndex();
411
412     QMenu contextMenu(this);
413
414     if (index.isValid()) {
415         addActionsToMenu(&contextMenu, index);
416     }
417
418     addFilterActions(&contextMenu, index);
419
420     if (!contextMenu.actions().isEmpty())
421         contextMenu.exec(QCursor::pos());
422 }
423
424
425 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
426 {
427     QModelIndexList indexList = selectedIndexes();
428     // make sure the item we clicked on is first
429     indexList.removeAll(index);
430     indexList.prepend(index);
431
432     GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
433 }
434
435
436 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
437 {
438     BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
439     if (filter) {
440         QList<QAction *> filterActions = filter->actions(index);
441         if (!filterActions.isEmpty()) {
442             contextMenu->addSeparator();
443             foreach(QAction *action, filterActions) {
444                 contextMenu->addAction(action);
445             }
446         }
447     }
448 }
449
450
451 void BufferView::menuActionTriggered(QAction *result)
452 {
453     ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
454     switch (type) {
455     case ContextMenuActionProvider::HideBufferTemporarily:
456         removeSelectedBuffers();
457         break;
458     case ContextMenuActionProvider::HideBufferPermanently:
459         removeSelectedBuffers(true);
460         break;
461     default:
462         return;
463     }
464 }
465
466
467 void BufferView::nextBuffer()
468 {
469     changeBuffer(Forward);
470 }
471
472
473 void BufferView::previousBuffer()
474 {
475     changeBuffer(Backward);
476 }
477
478
479 void BufferView::changeBuffer(Direction direction)
480 {
481     QModelIndex currentIndex = selectionModel()->currentIndex();
482     QModelIndex resultingIndex;
483
484     if (currentIndex.parent().isValid()) {
485         //If we are a child node just switch among siblings unless it's the first/last child
486         resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
487
488         if (!resultingIndex.isValid()) {
489             QModelIndex parent = currentIndex.parent();
490             if (direction == Backward)
491                 resultingIndex = parent;
492             else
493                 resultingIndex = parent.sibling(parent.row() + direction, 0);
494         }
495     }
496     else {
497         //If we have a toplevel node, try and get an adjacent child
498         if (direction == Backward) {
499             QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
500             if (model()->hasChildren(newParent))
501                 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
502             else
503                 resultingIndex = newParent;
504         }
505         else {
506             if (model()->hasChildren(currentIndex))
507                 resultingIndex = currentIndex.child(0, 0);
508             else
509                 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
510         }
511     }
512
513     if (!resultingIndex.isValid())
514         return;
515
516     selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
517     selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
518 }
519
520 void BufferView::selectFirstBuffer()
521 {
522     int networksCount = model()->rowCount(QModelIndex());
523     if (networksCount == 0) {
524         return;
525     }
526
527     QModelIndex bufferIndex;
528     for (int row = 0; row < networksCount; row++) {
529         QModelIndex networkIndex = model()->index(row, 0, QModelIndex());
530         int childCount = model()->rowCount(networkIndex);
531         if (childCount > 0) {
532             bufferIndex = model()->index(0, 0, networkIndex);
533             break;
534         }
535     }
536
537     if (!bufferIndex.isValid()) {
538         return;
539     }
540
541     selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
542     selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
543 }
544
545 void BufferView::wheelEvent(QWheelEvent *event)
546 {
547     if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
548         return TreeViewTouch::wheelEvent(event);
549
550     int rowDelta = (event->delta() > 0) ? -1 : 1;
551     changeBuffer((Direction)rowDelta);
552 }
553
554
555 void BufferView::hideCurrentBuffer()
556 {
557     QModelIndex index = selectionModel()->currentIndex();
558     if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
559         return;
560
561     BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
562
563     //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.
564     changeBuffer(Backward);
565
566     /*if(removedRows.contains(bufferId))
567       continue;
568
569     removedRows << bufferId;*/
570     /*if(permanently)
571       config()->requestRemoveBufferPermanently(bufferId);
572     else*/
573     config()->requestRemoveBuffer(bufferId);
574 }
575
576 void BufferView::filterTextChanged(QString filterString)
577 {
578     BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
579     if (!filter) {
580         return;
581     }
582     filter->setFilterString(filterString);
583     on_configChanged(); // make sure collapsation is correct
584 }
585
586
587 QSize BufferView::sizeHint() const
588 {
589     return TreeViewTouch::sizeHint();
590
591     if (!model())
592         return TreeViewTouch::sizeHint();
593
594     if (model()->rowCount() == 0)
595         return QSize(120, 50);
596
597     int columnSize = 0;
598     for (int i = 0; i < model()->columnCount(); i++) {
599         if (!isColumnHidden(i))
600             columnSize += sizeHintForColumn(i);
601     }
602     return QSize(columnSize, 50);
603 }
604
605
606 // ****************************************
607 //  BufferViewDelgate
608 // ****************************************
609 class ColorsChangedEvent : public QEvent
610 {
611 public:
612     ColorsChangedEvent() : QEvent(QEvent::User) {};
613 };
614
615
616 BufferViewDelegate::BufferViewDelegate(QObject *parent)
617     : QStyledItemDelegate(parent)
618 {
619 }
620
621
622 void BufferViewDelegate::customEvent(QEvent *event)
623 {
624     if (event->type() != QEvent::User)
625         return;
626
627     event->accept();
628 }
629
630
631 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
632 {
633     if (event->type() != QEvent::MouseButtonRelease)
634         return QStyledItemDelegate::editorEvent(event, model, option, index);
635
636     if (!(model->flags(index) & Qt::ItemIsUserCheckable))
637         return QStyledItemDelegate::editorEvent(event, model, option, index);
638
639     QVariant value = index.data(Qt::CheckStateRole);
640     if (!value.isValid())
641         return QStyledItemDelegate::editorEvent(event, model, option, index);
642
643     QStyleOptionViewItemV4 viewOpt(option);
644     initStyleOption(&viewOpt, index);
645
646     QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
647     QMouseEvent *me = static_cast<QMouseEvent *>(event);
648
649     if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
650         return QStyledItemDelegate::editorEvent(event, model, option, index);
651
652     Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
653     if (state == Qt::Unchecked)
654         state = Qt::PartiallyChecked;
655     else if (state == Qt::PartiallyChecked)
656         state = Qt::Checked;
657     else
658         state = Qt::Unchecked;
659     model->setData(index, state, Qt::CheckStateRole);
660     return true;
661 }
662
663
664 // ==============================
665 //  BufferView Dock
666 // ==============================
667 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
668     : QDockWidget(parent),
669     _childWidget(0),
670     _widget(new QWidget(parent)),
671     _filterEdit(new QLineEdit(parent)),
672     _active(false),
673     _title(config->bufferViewName())
674 {
675     setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
676     toggleViewAction()->setData(config->bufferViewId());
677     setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
678     connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
679     connect(config, SIGNAL(configChanged()), SLOT(configChanged()));
680     updateTitle();
681
682     _widget->setLayout(new QVBoxLayout);
683     _widget->layout()->setSpacing(0);
684     _widget->layout()->setContentsMargins(0, 0, 0, 0);
685
686     // We need to potentially hide it early, so it doesn't flicker
687     _filterEdit->setVisible(config->showSearch());
688     _filterEdit->setFocusPolicy(Qt::ClickFocus);
689     _filterEdit->installEventFilter(this);
690     _filterEdit->setPlaceholderText(tr("Search..."));
691     connect(_filterEdit, SIGNAL(returnPressed()), SLOT(onFilterReturnPressed()));
692
693     _widget->layout()->addWidget(_filterEdit);
694     QDockWidget::setWidget(_widget);
695 }
696
697
698 void BufferViewDock::updateTitle()
699 {
700     QString title = _title;
701     if (isActive())
702         title.prepend(QString::fromUtf8("• "));
703     setWindowTitle(title);
704 }
705
706 void BufferViewDock::configChanged()
707 {
708     if (_filterEdit->isVisible() != config()->showSearch()) {
709         _filterEdit->setVisible(config()->showSearch());
710         _filterEdit->clear();
711     }
712 }
713
714 void BufferViewDock::onFilterReturnPressed()
715 {
716     if (_oldFocusItem) {
717         _oldFocusItem->setFocus();
718         _oldFocusItem = 0;
719     }
720
721     if (!config()->showSearch()) {
722         _filterEdit->setVisible(false);
723     }
724
725     BufferView *view = bufferView();
726     if (!view || _filterEdit->text().isEmpty()) {
727         return;
728     }
729
730     view->selectFirstBuffer();
731     _filterEdit->clear();
732 }
733
734 void BufferViewDock::setActive(bool active)
735 {
736     if (active != isActive()) {
737         _active = active;
738         updateTitle();
739         if (active) {
740             raise();  // for tabbed docks
741         }
742     }
743 }
744
745 bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
746 {
747    if (object != _filterEdit)  {
748        return false;
749    }
750
751    if (event->type() == QEvent::FocusOut) {
752        if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
753            _filterEdit->setVisible(false);
754            return true;
755        }
756    } else if (event->type() == QEvent::KeyRelease) {
757        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
758        if (keyEvent->key() != Qt::Key_Escape) {
759            return false;
760        }
761
762        _filterEdit->clear();
763
764        if (_oldFocusItem) {
765            _oldFocusItem->setFocus();
766            _oldFocusItem = 0;
767        }
768
769        return true;
770    }
771
772    return false;
773 }
774
775 void BufferViewDock::bufferViewRenamed(const QString &newName)
776 {
777     _title = newName;
778     updateTitle();
779     toggleViewAction()->setText(newName);
780 }
781
782
783 int BufferViewDock::bufferViewId() const
784 {
785     BufferView *view = bufferView();
786     if (!view)
787         return 0;
788
789     if (view->config())
790         return view->config()->bufferViewId();
791     else
792         return 0;
793 }
794
795
796 BufferViewConfig *BufferViewDock::config() const
797 {
798     BufferView *view = bufferView();
799     if (!view)
800         return 0;
801     else
802         return view->config();
803 }
804
805 void BufferViewDock::setWidget(QWidget *newWidget)
806 {
807     _widget->layout()->addWidget(newWidget);
808     _childWidget = newWidget;
809
810     connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));
811 }
812
813 void BufferViewDock::activateFilter()
814 {
815     if (!_filterEdit->isVisible()) {
816         _filterEdit->setVisible(true);
817     }
818
819     _oldFocusItem = qApp->focusWidget();
820
821     _filterEdit->setFocus();
822 }