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 // 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)));
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)));
104 void BufferView::setModel(QAbstractItemModel *model)
106 delete selectionModel();
108 TreeViewTouch::setModel(model);
110 // remove old Actions
111 QList<QAction *> oldactions = header()->actions();
112 foreach(QAction *action, oldactions) {
113 header()->removeAction(action);
114 action->deleteLater();
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);
132 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
134 // Make sure collapsation is correct after setting a model
135 // This might not be needed here, only in BufferView::setFilteredModel(). If issues arise, just
136 // move down to setFilteredModel (which calls this function).
141 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
143 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
145 filter->setConfig(config);
151 disconnect(this, 0, model(), 0);
152 disconnect(model(), 0, this, 0);
159 BufferViewFilter *filter = new BufferViewFilter(model_, config);
161 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
167 void BufferView::setConfig(BufferViewConfig *config)
169 if (_config == config)
173 disconnect(_config, 0, this, 0);
178 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
179 setRootIndexForNetworkId(config->networkId());
183 setRootIndex(QModelIndex());
188 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
190 if (!networkId.isValid() || !model()) {
192 setRootIndex(QModelIndex());
196 int networkCount = model()->rowCount();
198 for (int i = 0; i < networkCount; i++) {
199 child = model()->index(i, 0);
200 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
207 void BufferView::joinChannel(const QModelIndex &index)
209 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
211 if (bufferType != BufferInfo::ChannelBuffer)
214 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
216 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
220 void BufferView::keyPressEvent(QKeyEvent *event)
222 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
224 removeSelectedBuffers();
226 TreeViewTouch::keyPressEvent(event);
230 void BufferView::dropEvent(QDropEvent *event)
232 QModelIndex index = indexAt(event->pos());
234 QRect indexRect = visualRect(index);
235 QPoint cursorPos = event->pos();
237 // check if we're really _on_ the item and not indicating a move to just above or below the item
238 // Magic margin number for this is from QAbstractItemViewPrivate::position()
239 const int margin = 2;
240 if (cursorPos.y() - indexRect.top() < margin
241 || indexRect.bottom() - cursorPos.y() < margin)
242 return TreeViewTouch::dropEvent(event);
244 // If more than one buffer was being dragged, treat this as a rearrangement instead of a merge request
245 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
246 if (bufferList.count() != 1)
247 return TreeViewTouch::dropEvent(event);
249 // Get the Buffer ID of the buffer that was being dragged
250 BufferId bufferId2 = bufferList[0].second;
252 // Get the Buffer ID of the target buffer
253 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
255 // If the source and target are the same buffer, this was an aborted rearrangement
256 if (bufferId1 == bufferId2)
257 return TreeViewTouch::dropEvent(event);
259 // Get index of buffer that was being dragged
260 QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
262 // If the buffer being dragged is a channel and we're still joined to it, treat this as a rearrangement
263 // This prevents us from being joined to a channel with no associated UI elements
264 if (index2.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && index2.data(NetworkModel::ItemActiveRole) == true)
265 return TreeViewTouch::dropEvent(event);
267 //If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
268 if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
269 return TreeViewTouch::dropEvent(event);
271 // If the target buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
272 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
273 return TreeViewTouch::dropEvent(event);
275 // Confirm that the user really wants to merge the buffers before doing so
276 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
277 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)),
278 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
279 if (res == QMessageBox::Yes) {
280 Client::mergeBuffersPermanently(bufferId1, bufferId2);
285 void BufferView::removeSelectedBuffers(bool permanently)
291 QSet<BufferId> removedRows;
292 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
293 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
296 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
297 if (removedRows.contains(bufferId))
300 removedRows << bufferId;
303 foreach(BufferId bufferId, removedRows) {
305 config()->requestRemoveBufferPermanently(bufferId);
307 config()->requestRemoveBuffer(bufferId);
312 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
314 TreeViewTouch::rowsInserted(parent, start, end);
316 // ensure that newly inserted network nodes are expanded per default
317 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
320 setExpandedState(parent);
324 void BufferView::on_layoutChanged()
326 int numNets = model()->rowCount(QModelIndex());
327 for (int row = 0; row < numNets; row++) {
328 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
329 setExpandedState(networkIdx);
334 void BufferView::on_configChanged()
338 // Expand/collapse as needed
342 // update selection to current one
343 Client::bufferModel()->synchronizeView(this);
348 void BufferView::setExpandedState()
350 // Expand all active networks, collapse inactive ones... unless manually changed
351 QModelIndex networkIdx;
353 for (int row = 0; row < model()->rowCount(); row++) {
354 networkIdx = model()->index(row, 0);
355 if (model()->rowCount(networkIdx) == 0)
358 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
359 if (!networkId.isValid())
362 setExpandedState(networkIdx);
367 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
369 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
372 if (isExpanded(networkIdx))
373 oldState |= WasExpanded;
374 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
375 oldState |= WasActive;
377 _expandedState[networkId] = oldState;
381 void BufferView::setExpandedState(const QModelIndex &networkIdx)
383 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
386 if (model()->rowCount(networkIdx) == 0)
389 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
391 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
392 bool expandNetwork = networkActive;
393 if (_expandedState.contains(networkId)) {
394 int oldState = _expandedState[networkId];
395 if ((bool)(oldState & WasActive) == networkActive)
396 expandNetwork = (bool)(oldState & WasExpanded);
399 if (expandNetwork != isExpanded(networkIdx)) {
401 setExpanded(networkIdx, expandNetwork);
403 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
406 #if QT_VERSION < 0x050000
407 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
409 TreeViewTouch::dataChanged(topLeft, bottomRight);
411 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
413 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
416 // determine how many items have been changed and if any of them is a networkitem
417 // which just swichted from active to inactive or vice versa
418 if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
421 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
422 QModelIndex networkIdx = topLeft.sibling(i, 0);
423 setExpandedState(networkIdx);
428 void BufferView::toggleHeader(bool checked)
430 QAction *action = qobject_cast<QAction *>(sender());
431 header()->setSectionHidden((action->property("column")).toInt(), !checked);
435 void BufferView::contextMenuEvent(QContextMenuEvent *event)
437 QModelIndex index = indexAt(event->pos());
438 if (!index.isValid())
441 QMenu contextMenu(this);
443 if (index.isValid()) {
444 addActionsToMenu(&contextMenu, index);
447 addFilterActions(&contextMenu, index);
449 if (!contextMenu.actions().isEmpty())
450 contextMenu.exec(QCursor::pos());
454 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
456 QModelIndexList indexList = selectedIndexes();
457 // make sure the item we clicked on is first
458 indexList.removeAll(index);
459 indexList.prepend(index);
461 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
465 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
467 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
469 QList<QAction *> filterActions = filter->actions(index);
470 if (!filterActions.isEmpty()) {
471 contextMenu->addSeparator();
472 foreach(QAction *action, filterActions) {
473 contextMenu->addAction(action);
480 void BufferView::menuActionTriggered(QAction *result)
482 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
484 case ContextMenuActionProvider::HideBufferTemporarily:
485 removeSelectedBuffers();
487 case ContextMenuActionProvider::HideBufferPermanently:
488 removeSelectedBuffers(true);
496 void BufferView::nextBuffer()
498 changeBuffer(Forward);
502 void BufferView::previousBuffer()
504 changeBuffer(Backward);
508 void BufferView::changeBuffer(Direction direction)
510 QModelIndex currentIndex = selectionModel()->currentIndex();
511 QModelIndex resultingIndex;
513 if (currentIndex.parent().isValid()) {
514 //If we are a child node just switch among siblings unless it's the first/last child
515 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
517 if (!resultingIndex.isValid()) {
518 QModelIndex parent = currentIndex.parent();
519 if (direction == Backward)
520 resultingIndex = parent;
522 resultingIndex = parent.sibling(parent.row() + direction, 0);
526 //If we have a toplevel node, try and get an adjacent child
527 if (direction == Backward) {
528 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
529 if (model()->hasChildren(newParent))
530 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
532 resultingIndex = newParent;
535 if (model()->hasChildren(currentIndex))
536 resultingIndex = currentIndex.child(0, 0);
538 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
542 if (!resultingIndex.isValid())
545 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
546 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
549 void BufferView::selectFirstBuffer()
551 int networksCount = model()->rowCount(QModelIndex());
552 if (networksCount == 0) {
556 QModelIndex bufferIndex;
557 for (int row = 0; row < networksCount; row++) {
558 QModelIndex networkIndex = model()->index(row, 0, QModelIndex());
559 int childCount = model()->rowCount(networkIndex);
560 if (childCount > 0) {
561 bufferIndex = model()->index(0, 0, networkIndex);
566 if (!bufferIndex.isValid()) {
570 selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
571 selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
574 void BufferView::wheelEvent(QWheelEvent *event)
576 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
577 return TreeViewTouch::wheelEvent(event);
579 int rowDelta = (event->delta() > 0) ? -1 : 1;
580 changeBuffer((Direction)rowDelta);
584 void BufferView::hideCurrentBuffer()
586 QModelIndex index = selectionModel()->currentIndex();
587 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
590 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
592 //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.
593 changeBuffer(Backward);
595 /*if(removedRows.contains(bufferId))
598 removedRows << bufferId;*/
600 config()->requestRemoveBufferPermanently(bufferId);
602 config()->requestRemoveBuffer(bufferId);
605 void BufferView::filterTextChanged(QString filterString)
607 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
611 filter->setFilterString(filterString);
612 on_configChanged(); // make sure collapsation is correct
616 QSize BufferView::sizeHint() const
618 return TreeViewTouch::sizeHint();
621 return TreeViewTouch::sizeHint();
623 if (model()->rowCount() == 0)
624 return QSize(120, 50);
627 for (int i = 0; i < model()->columnCount(); i++) {
628 if (!isColumnHidden(i))
629 columnSize += sizeHintForColumn(i);
631 return QSize(columnSize, 50);
635 // ****************************************
637 // ****************************************
638 class ColorsChangedEvent : public QEvent
641 ColorsChangedEvent() : QEvent(QEvent::User) {};
645 BufferViewDelegate::BufferViewDelegate(QObject *parent)
646 : QStyledItemDelegate(parent)
651 void BufferViewDelegate::customEvent(QEvent *event)
653 if (event->type() != QEvent::User)
660 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
662 if (event->type() != QEvent::MouseButtonRelease)
663 return QStyledItemDelegate::editorEvent(event, model, option, index);
665 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
666 return QStyledItemDelegate::editorEvent(event, model, option, index);
668 QVariant value = index.data(Qt::CheckStateRole);
669 if (!value.isValid())
670 return QStyledItemDelegate::editorEvent(event, model, option, index);
672 #if QT_VERSION < 0x050000
673 QStyleOptionViewItemV4 viewOpt(option);
675 QStyleOptionViewItem viewOpt(option);
677 initStyleOption(&viewOpt, index);
679 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
680 QMouseEvent *me = static_cast<QMouseEvent *>(event);
682 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
683 return QStyledItemDelegate::editorEvent(event, model, option, index);
685 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
686 if (state == Qt::Unchecked)
687 state = Qt::PartiallyChecked;
688 else if (state == Qt::PartiallyChecked)
691 state = Qt::Unchecked;
692 model->setData(index, state, Qt::CheckStateRole);
697 // ==============================
699 // ==============================
700 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
701 : QDockWidget(parent),
703 _widget(new QWidget(parent)),
704 _filterEdit(new QLineEdit(parent)),
706 _title(config->bufferViewName())
708 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
709 toggleViewAction()->setData(config->bufferViewId());
710 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
711 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
712 connect(config, SIGNAL(configChanged()), SLOT(configChanged()));
715 _widget->setLayout(new QVBoxLayout);
716 _widget->layout()->setSpacing(0);
717 _widget->layout()->setContentsMargins(0, 0, 0, 0);
719 // We need to potentially hide it early, so it doesn't flicker
720 _filterEdit->setVisible(config->showSearch());
721 _filterEdit->setFocusPolicy(Qt::ClickFocus);
722 _filterEdit->installEventFilter(this);
723 _filterEdit->setPlaceholderText(tr("Search..."));
724 connect(_filterEdit, SIGNAL(returnPressed()), SLOT(onFilterReturnPressed()));
726 _widget->layout()->addWidget(_filterEdit);
727 QDockWidget::setWidget(_widget);
731 void BufferViewDock::updateTitle()
733 QString title = _title;
735 title.prepend(QString::fromUtf8("• "));
736 setWindowTitle(title);
739 void BufferViewDock::configChanged()
741 if (_filterEdit->isVisible() != config()->showSearch()) {
742 _filterEdit->setVisible(config()->showSearch());
743 _filterEdit->clear();
747 void BufferViewDock::onFilterReturnPressed()
750 _oldFocusItem->setFocus();
754 if (!config()->showSearch()) {
755 _filterEdit->setVisible(false);
758 BufferView *view = bufferView();
759 if (!view || _filterEdit->text().isEmpty()) {
763 view->selectFirstBuffer();
764 _filterEdit->clear();
767 void BufferViewDock::setActive(bool active)
769 if (active != isActive()) {
773 raise(); // for tabbed docks
778 bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
780 if (object != _filterEdit) {
784 if (event->type() == QEvent::FocusOut) {
785 if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
786 _filterEdit->setVisible(false);
789 } else if (event->type() == QEvent::KeyRelease) {
790 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
791 if (keyEvent->key() != Qt::Key_Escape) {
795 _filterEdit->clear();
798 _oldFocusItem->setFocus();
808 void BufferViewDock::bufferViewRenamed(const QString &newName)
812 toggleViewAction()->setText(newName);
816 int BufferViewDock::bufferViewId() const
818 BufferView *view = bufferView();
823 return view->config()->bufferViewId();
829 BufferViewConfig *BufferViewDock::config() const
831 BufferView *view = bufferView();
835 return view->config();
838 void BufferViewDock::setWidget(QWidget *newWidget)
840 _widget->layout()->addWidget(newWidget);
841 _childWidget = newWidget;
843 connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));
846 void BufferViewDock::activateFilter()
848 if (!_filterEdit->isVisible()) {
849 _filterEdit->setVisible(true);
852 _oldFocusItem = qApp->focusWidget();
854 _filterEdit->setFocus();