1 /***************************************************************************
2 * Copyright (C) 2005-2016 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "bufferview.h"
23 #include <QApplication>
26 #include <QHeaderView>
29 #include <QMessageBox>
31 #include <QVBoxLayout>
34 #include "buffermodel.h"
35 #include "bufferviewfilter.h"
36 #include "buffersettings.h"
37 #include "buffersyncer.h"
39 #include "contextmenuactionprovider.h"
40 #include "graphicalui.h"
42 #include "networkmodel.h"
43 #include "contextmenuactionprovider.h"
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)
53 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
54 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
56 setSelectionMode(QAbstractItemView::ExtendedSelection);
58 QAbstractItemDelegate *oldDelegate = itemDelegate();
59 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
60 setItemDelegate(tristateDelegate);
65 void BufferView::init()
67 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
72 // New entries will be expanded automatically when added; no need to call expandAll()
74 header()->hide(); // nobody seems to use this anyway
77 if (QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
80 // FIXME This is to workaround bug #663
81 setUniformRowHeights(true);
83 #ifndef QT_NO_DRAGANDDROP
86 setDropIndicatorShown(true);
89 setSortingEnabled(true);
90 sortByColumn(0, Qt::AscendingOrder);
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)));
97 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
98 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
103 void BufferView::setModel(QAbstractItemModel *model)
105 delete selectionModel();
107 TreeViewTouch::setModel(model);
109 // remove old Actions
110 QList<QAction *> oldactions = header()->actions();
111 foreach(QAction *action, oldactions) {
112 header()->removeAction(action);
113 action->deleteLater();
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);
131 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
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).
140 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
142 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
144 filter->setConfig(config);
150 disconnect(this, 0, model(), 0);
151 disconnect(model(), 0, this, 0);
158 BufferViewFilter *filter = new BufferViewFilter(model_, config);
160 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
166 void BufferView::setConfig(BufferViewConfig *config)
168 if (_config == config)
172 disconnect(_config, 0, this, 0);
177 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
178 setRootIndexForNetworkId(config->networkId());
182 setRootIndex(QModelIndex());
187 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
189 if (!networkId.isValid() || !model()) {
191 setRootIndex(QModelIndex());
195 int networkCount = model()->rowCount();
197 for (int i = 0; i < networkCount; i++) {
198 child = model()->index(i, 0);
199 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
206 void BufferView::joinChannel(const QModelIndex &index)
208 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
210 if (bufferType != BufferInfo::ChannelBuffer)
213 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
215 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
219 void BufferView::dropEvent(QDropEvent *event)
221 QModelIndex index = indexAt(event->pos());
223 QRect indexRect = visualRect(index);
224 QPoint cursorPos = event->pos();
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);
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);
238 // Get the Buffer ID of the buffer that was being dragged
239 BufferId bufferId2 = bufferList[0].second;
241 // Get the Buffer ID of the target buffer
242 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
244 // If the source and target are the same buffer, this was an aborted rearrangement
245 if (bufferId1 == bufferId2)
246 return TreeViewTouch::dropEvent(event);
248 // Get index of buffer that was being dragged
249 QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
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);
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);
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);
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);
274 void BufferView::removeSelectedBuffers(bool permanently)
280 QSet<BufferId> removedRows;
281 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
282 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
285 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
286 if (removedRows.contains(bufferId))
289 removedRows << bufferId;
292 foreach(BufferId bufferId, removedRows) {
294 config()->requestRemoveBufferPermanently(bufferId);
296 config()->requestRemoveBuffer(bufferId);
301 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
303 TreeViewTouch::rowsInserted(parent, start, end);
305 // ensure that newly inserted network nodes are expanded per default
306 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
309 setExpandedState(parent);
313 void BufferView::on_layoutChanged()
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);
323 void BufferView::on_configChanged()
327 // Expand/collapse as needed
331 // update selection to current one
332 Client::bufferModel()->synchronizeView(this);
337 void BufferView::setExpandedState()
339 // Expand all active networks, collapse inactive ones... unless manually changed
340 QModelIndex networkIdx;
342 for (int row = 0; row < model()->rowCount(); row++) {
343 networkIdx = model()->index(row, 0);
344 if (model()->rowCount(networkIdx) == 0)
347 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
348 if (!networkId.isValid())
351 setExpandedState(networkIdx);
356 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
358 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
361 if (isExpanded(networkIdx))
362 oldState |= WasExpanded;
363 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
364 oldState |= WasActive;
366 _expandedState[networkId] = oldState;
370 void BufferView::setExpandedState(const QModelIndex &networkIdx)
372 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
375 if (model()->rowCount(networkIdx) == 0)
378 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
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);
388 if (expandNetwork != isExpanded(networkIdx)) {
390 setExpanded(networkIdx, expandNetwork);
392 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
395 #if QT_VERSION < 0x050000
396 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
398 TreeViewTouch::dataChanged(topLeft, bottomRight);
400 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
402 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
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)
410 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
411 QModelIndex networkIdx = topLeft.sibling(i, 0);
412 setExpandedState(networkIdx);
417 void BufferView::toggleHeader(bool checked)
419 QAction *action = qobject_cast<QAction *>(sender());
420 header()->setSectionHidden((action->property("column")).toInt(), !checked);
424 void BufferView::contextMenuEvent(QContextMenuEvent *event)
426 QModelIndex index = indexAt(event->pos());
427 if (!index.isValid())
430 QMenu contextMenu(this);
432 if (index.isValid()) {
433 addActionsToMenu(&contextMenu, index);
436 addFilterActions(&contextMenu, index);
438 if (!contextMenu.actions().isEmpty())
439 contextMenu.exec(QCursor::pos());
443 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
445 QModelIndexList indexList = selectedIndexes();
446 // make sure the item we clicked on is first
447 indexList.removeAll(index);
448 indexList.prepend(index);
450 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
454 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
456 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
458 QList<QAction *> filterActions = filter->actions(index);
459 if (!filterActions.isEmpty()) {
460 contextMenu->addSeparator();
461 foreach(QAction *action, filterActions) {
462 contextMenu->addAction(action);
469 void BufferView::menuActionTriggered(QAction *result)
471 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
473 case ContextMenuActionProvider::HideBufferTemporarily:
474 removeSelectedBuffers();
476 case ContextMenuActionProvider::HideBufferPermanently:
477 removeSelectedBuffers(true);
485 void BufferView::nextBuffer()
487 changeBuffer(Forward);
491 void BufferView::previousBuffer()
493 changeBuffer(Backward);
497 void BufferView::changeBuffer(Direction direction)
499 QModelIndex currentIndex = selectionModel()->currentIndex();
500 QModelIndex resultingIndex;
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);
506 if (!resultingIndex.isValid()) {
507 QModelIndex parent = currentIndex.parent();
508 if (direction == Backward)
509 resultingIndex = parent;
511 resultingIndex = parent.sibling(parent.row() + direction, 0);
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);
521 resultingIndex = newParent;
524 if (model()->hasChildren(currentIndex))
525 resultingIndex = currentIndex.child(0, 0);
527 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
531 if (!resultingIndex.isValid())
534 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
535 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
538 void BufferView::selectFirstBuffer()
540 int networksCount = model()->rowCount(QModelIndex());
541 if (networksCount == 0) {
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);
555 if (!bufferIndex.isValid()) {
559 selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
560 selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
563 void BufferView::wheelEvent(QWheelEvent *event)
565 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
566 return TreeViewTouch::wheelEvent(event);
568 int rowDelta = (event->delta() > 0) ? -1 : 1;
569 changeBuffer((Direction)rowDelta);
573 void BufferView::hideCurrentBuffer()
575 QModelIndex index = selectionModel()->currentIndex();
576 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
579 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
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);
584 config()->requestRemoveBuffer(bufferId);
587 void BufferView::filterTextChanged(QString filterString)
589 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
593 filter->setFilterString(filterString);
594 on_configChanged(); // make sure collapsation is correct
598 QSize BufferView::sizeHint() const
600 return TreeViewTouch::sizeHint();
603 return TreeViewTouch::sizeHint();
605 if (model()->rowCount() == 0)
606 return QSize(120, 50);
609 for (int i = 0; i < model()->columnCount(); i++) {
610 if (!isColumnHidden(i))
611 columnSize += sizeHintForColumn(i);
613 return QSize(columnSize, 50);
617 // ****************************************
619 // ****************************************
620 class ColorsChangedEvent : public QEvent
623 ColorsChangedEvent() : QEvent(QEvent::User) {};
627 BufferViewDelegate::BufferViewDelegate(QObject *parent)
628 : QStyledItemDelegate(parent)
633 void BufferViewDelegate::customEvent(QEvent *event)
635 if (event->type() != QEvent::User)
642 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
644 if (event->type() != QEvent::MouseButtonRelease)
645 return QStyledItemDelegate::editorEvent(event, model, option, index);
647 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
648 return QStyledItemDelegate::editorEvent(event, model, option, index);
650 QVariant value = index.data(Qt::CheckStateRole);
651 if (!value.isValid())
652 return QStyledItemDelegate::editorEvent(event, model, option, index);
654 #if QT_VERSION < 0x050000
655 QStyleOptionViewItemV4 viewOpt(option);
657 QStyleOptionViewItem viewOpt(option);
659 initStyleOption(&viewOpt, index);
661 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
662 QMouseEvent *me = static_cast<QMouseEvent *>(event);
664 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
665 return QStyledItemDelegate::editorEvent(event, model, option, index);
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)
673 state = Qt::Unchecked;
674 model->setData(index, state, Qt::CheckStateRole);
679 // ==============================
681 // ==============================
682 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
683 : QDockWidget(parent),
685 _widget(new QWidget(parent)),
686 _filterEdit(new QLineEdit(parent)),
688 _title(config->bufferViewName())
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()));
697 _widget->setLayout(new QVBoxLayout);
698 _widget->layout()->setSpacing(0);
699 _widget->layout()->setContentsMargins(0, 0, 0, 0);
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()));
708 _widget->layout()->addWidget(_filterEdit);
709 QDockWidget::setWidget(_widget);
713 void BufferViewDock::updateTitle()
715 QString title = _title;
717 title.prepend(QString::fromUtf8("• "));
718 setWindowTitle(title);
721 void BufferViewDock::configChanged()
723 if (_filterEdit->isVisible() != config()->showSearch()) {
724 _filterEdit->setVisible(config()->showSearch());
725 _filterEdit->clear();
729 void BufferViewDock::onFilterReturnPressed()
732 _oldFocusItem->setFocus();
736 if (!config()->showSearch()) {
737 _filterEdit->setVisible(false);
740 BufferView *view = bufferView();
741 if (!view || _filterEdit->text().isEmpty()) {
745 view->selectFirstBuffer();
746 _filterEdit->clear();
749 void BufferViewDock::setActive(bool active)
751 if (active != isActive()) {
755 raise(); // for tabbed docks
760 bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
762 if (object != _filterEdit) {
766 if (event->type() == QEvent::FocusOut) {
767 if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
768 _filterEdit->setVisible(false);
771 } else if (event->type() == QEvent::KeyRelease) {
772 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
773 if (keyEvent->key() != Qt::Key_Escape) {
777 _filterEdit->clear();
780 _oldFocusItem->setFocus();
790 void BufferViewDock::bufferViewRenamed(const QString &newName)
794 toggleViewAction()->setText(newName);
798 int BufferViewDock::bufferViewId() const
800 BufferView *view = bufferView();
805 return view->config()->bufferViewId();
811 BufferViewConfig *BufferViewDock::config() const
813 BufferView *view = bufferView();
817 return view->config();
820 void BufferViewDock::setWidget(QWidget *newWidget)
822 _widget->layout()->addWidget(newWidget);
823 _childWidget = newWidget;
825 connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));
828 void BufferViewDock::activateFilter()
830 if (!_filterEdit->isVisible()) {
831 _filterEdit->setVisible(true);
834 _oldFocusItem = qApp->focusWidget();
836 _filterEdit->setFocus();