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()));
136 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
138 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
140 filter->setConfig(config);
146 disconnect(this, 0, model(), 0);
147 disconnect(model(), 0, this, 0);
154 BufferViewFilter *filter = new BufferViewFilter(model_, config);
156 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
162 void BufferView::setConfig(BufferViewConfig *config)
164 if (_config == config)
168 disconnect(_config, 0, this, 0);
173 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
174 setRootIndexForNetworkId(config->networkId());
178 setRootIndex(QModelIndex());
183 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
185 if (!networkId.isValid() || !model()) {
187 setRootIndex(QModelIndex());
191 int networkCount = model()->rowCount();
193 for (int i = 0; i < networkCount; i++) {
194 child = model()->index(i, 0);
195 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
202 void BufferView::joinChannel(const QModelIndex &index)
204 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
206 if (bufferType != BufferInfo::ChannelBuffer)
209 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
211 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
215 void BufferView::keyPressEvent(QKeyEvent *event)
217 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
219 removeSelectedBuffers();
221 TreeViewTouch::keyPressEvent(event);
225 void BufferView::dropEvent(QDropEvent *event)
227 QModelIndex index = indexAt(event->pos());
229 QRect indexRect = visualRect(index);
230 QPoint cursorPos = event->pos();
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);
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);
244 // Get the Buffer ID of the buffer that was being dragged
245 BufferId bufferId2 = bufferList[0].second;
247 // Get the Buffer ID of the target buffer
248 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
250 // If the source and target are the same buffer, this was an aborted rearrangement
251 if (bufferId1 == bufferId2)
252 return TreeViewTouch::dropEvent(event);
254 // Get index of buffer that was being dragged
255 QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
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);
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);
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);
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);
280 void BufferView::removeSelectedBuffers(bool permanently)
286 QSet<BufferId> removedRows;
287 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
288 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
291 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
292 if (removedRows.contains(bufferId))
295 removedRows << bufferId;
298 foreach(BufferId bufferId, removedRows) {
300 config()->requestRemoveBufferPermanently(bufferId);
302 config()->requestRemoveBuffer(bufferId);
307 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
309 TreeViewTouch::rowsInserted(parent, start, end);
311 // ensure that newly inserted network nodes are expanded per default
312 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
315 setExpandedState(parent);
319 void BufferView::on_layoutChanged()
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);
329 void BufferView::on_configChanged()
333 // expand all active networks... collapse inactive ones... unless manually changed
334 QModelIndex networkIdx;
336 for (int row = 0; row < model()->rowCount(); row++) {
337 networkIdx = model()->index(row, 0);
338 if (model()->rowCount(networkIdx) == 0)
341 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
342 if (!networkId.isValid())
345 setExpandedState(networkIdx);
349 // update selection to current one
350 Client::bufferModel()->synchronizeView(this);
355 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
357 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
360 if (isExpanded(networkIdx))
361 oldState |= WasExpanded;
362 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
363 oldState |= WasActive;
365 _expandedState[networkId] = oldState;
369 void BufferView::setExpandedState(const QModelIndex &networkIdx)
371 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
374 if (model()->rowCount(networkIdx) == 0)
377 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
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);
387 if (expandNetwork != isExpanded(networkIdx)) {
389 setExpanded(networkIdx, expandNetwork);
391 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
394 #if QT_VERSION < 0x050000
395 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
397 TreeViewTouch::dataChanged(topLeft, bottomRight);
399 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
401 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
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)
409 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
410 QModelIndex networkIdx = topLeft.sibling(i, 0);
411 setExpandedState(networkIdx);
416 void BufferView::toggleHeader(bool checked)
418 QAction *action = qobject_cast<QAction *>(sender());
419 header()->setSectionHidden((action->property("column")).toInt(), !checked);
423 void BufferView::contextMenuEvent(QContextMenuEvent *event)
425 QModelIndex index = indexAt(event->pos());
426 if (!index.isValid())
429 QMenu contextMenu(this);
431 if (index.isValid()) {
432 addActionsToMenu(&contextMenu, index);
435 addFilterActions(&contextMenu, index);
437 if (!contextMenu.actions().isEmpty())
438 contextMenu.exec(QCursor::pos());
442 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
444 QModelIndexList indexList = selectedIndexes();
445 // make sure the item we clicked on is first
446 indexList.removeAll(index);
447 indexList.prepend(index);
449 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
453 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
455 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
457 QList<QAction *> filterActions = filter->actions(index);
458 if (!filterActions.isEmpty()) {
459 contextMenu->addSeparator();
460 foreach(QAction *action, filterActions) {
461 contextMenu->addAction(action);
468 void BufferView::menuActionTriggered(QAction *result)
470 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
472 case ContextMenuActionProvider::HideBufferTemporarily:
473 removeSelectedBuffers();
475 case ContextMenuActionProvider::HideBufferPermanently:
476 removeSelectedBuffers(true);
484 void BufferView::nextBuffer()
486 changeBuffer(Forward);
490 void BufferView::previousBuffer()
492 changeBuffer(Backward);
496 void BufferView::changeBuffer(Direction direction)
498 QModelIndex currentIndex = selectionModel()->currentIndex();
499 QModelIndex resultingIndex;
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);
505 if (!resultingIndex.isValid()) {
506 QModelIndex parent = currentIndex.parent();
507 if (direction == Backward)
508 resultingIndex = parent;
510 resultingIndex = parent.sibling(parent.row() + direction, 0);
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);
520 resultingIndex = newParent;
523 if (model()->hasChildren(currentIndex))
524 resultingIndex = currentIndex.child(0, 0);
526 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
530 if (!resultingIndex.isValid())
533 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
534 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
537 void BufferView::selectFirstBuffer()
539 int networksCount = model()->rowCount(QModelIndex());
540 if (networksCount == 0) {
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);
554 if (!bufferIndex.isValid()) {
558 selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
559 selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
562 void BufferView::wheelEvent(QWheelEvent *event)
564 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
565 return TreeViewTouch::wheelEvent(event);
567 int rowDelta = (event->delta() > 0) ? -1 : 1;
568 changeBuffer((Direction)rowDelta);
572 void BufferView::hideCurrentBuffer()
574 QModelIndex index = selectionModel()->currentIndex();
575 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
578 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
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);
583 /*if(removedRows.contains(bufferId))
586 removedRows << bufferId;*/
588 config()->requestRemoveBufferPermanently(bufferId);
590 config()->requestRemoveBuffer(bufferId);
593 void BufferView::filterTextChanged(QString filterString)
595 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
599 filter->setFilterString(filterString);
600 on_configChanged(); // make sure collapsation is correct
604 QSize BufferView::sizeHint() const
606 return TreeViewTouch::sizeHint();
609 return TreeViewTouch::sizeHint();
611 if (model()->rowCount() == 0)
612 return QSize(120, 50);
615 for (int i = 0; i < model()->columnCount(); i++) {
616 if (!isColumnHidden(i))
617 columnSize += sizeHintForColumn(i);
619 return QSize(columnSize, 50);
623 // ****************************************
625 // ****************************************
626 class ColorsChangedEvent : public QEvent
629 ColorsChangedEvent() : QEvent(QEvent::User) {};
633 BufferViewDelegate::BufferViewDelegate(QObject *parent)
634 : QStyledItemDelegate(parent)
639 void BufferViewDelegate::customEvent(QEvent *event)
641 if (event->type() != QEvent::User)
648 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
650 if (event->type() != QEvent::MouseButtonRelease)
651 return QStyledItemDelegate::editorEvent(event, model, option, index);
653 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
654 return QStyledItemDelegate::editorEvent(event, model, option, index);
656 QVariant value = index.data(Qt::CheckStateRole);
657 if (!value.isValid())
658 return QStyledItemDelegate::editorEvent(event, model, option, index);
660 #if QT_VERSION < 0x050000
661 QStyleOptionViewItemV4 viewOpt(option);
663 QStyleOptionViewItem viewOpt(option);
665 initStyleOption(&viewOpt, index);
667 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
668 QMouseEvent *me = static_cast<QMouseEvent *>(event);
670 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
671 return QStyledItemDelegate::editorEvent(event, model, option, index);
673 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
674 if (state == Qt::Unchecked)
675 state = Qt::PartiallyChecked;
676 else if (state == Qt::PartiallyChecked)
679 state = Qt::Unchecked;
680 model->setData(index, state, Qt::CheckStateRole);
685 // ==============================
687 // ==============================
688 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
689 : QDockWidget(parent),
691 _widget(new QWidget(parent)),
692 _filterEdit(new QLineEdit(parent)),
694 _title(config->bufferViewName())
696 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
697 toggleViewAction()->setData(config->bufferViewId());
698 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
699 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
700 connect(config, SIGNAL(configChanged()), SLOT(configChanged()));
703 _widget->setLayout(new QVBoxLayout);
704 _widget->layout()->setSpacing(0);
705 _widget->layout()->setContentsMargins(0, 0, 0, 0);
707 // We need to potentially hide it early, so it doesn't flicker
708 _filterEdit->setVisible(config->showSearch());
709 _filterEdit->setFocusPolicy(Qt::ClickFocus);
710 _filterEdit->installEventFilter(this);
711 _filterEdit->setPlaceholderText(tr("Search..."));
712 connect(_filterEdit, SIGNAL(returnPressed()), SLOT(onFilterReturnPressed()));
714 _widget->layout()->addWidget(_filterEdit);
715 QDockWidget::setWidget(_widget);
719 void BufferViewDock::updateTitle()
721 QString title = _title;
723 title.prepend(QString::fromUtf8("• "));
724 setWindowTitle(title);
727 void BufferViewDock::configChanged()
729 if (_filterEdit->isVisible() != config()->showSearch()) {
730 _filterEdit->setVisible(config()->showSearch());
731 _filterEdit->clear();
735 void BufferViewDock::onFilterReturnPressed()
738 _oldFocusItem->setFocus();
742 if (!config()->showSearch()) {
743 _filterEdit->setVisible(false);
746 BufferView *view = bufferView();
747 if (!view || _filterEdit->text().isEmpty()) {
751 view->selectFirstBuffer();
752 _filterEdit->clear();
755 void BufferViewDock::setActive(bool active)
757 if (active != isActive()) {
761 raise(); // for tabbed docks
766 bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
768 if (object != _filterEdit) {
772 if (event->type() == QEvent::FocusOut) {
773 if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
774 _filterEdit->setVisible(false);
777 } else if (event->type() == QEvent::KeyRelease) {
778 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
779 if (keyEvent->key() != Qt::Key_Escape) {
783 _filterEdit->clear();
786 _oldFocusItem->setFocus();
796 void BufferViewDock::bufferViewRenamed(const QString &newName)
800 toggleViewAction()->setText(newName);
804 int BufferViewDock::bufferViewId() const
806 BufferView *view = bufferView();
811 return view->config()->bufferViewId();
817 BufferViewConfig *BufferViewDock::config() const
819 BufferView *view = bufferView();
823 return view->config();
826 void BufferViewDock::setWidget(QWidget *newWidget)
828 _widget->layout()->addWidget(newWidget);
829 _childWidget = newWidget;
831 connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));
834 void BufferViewDock::activateFilter()
836 if (!_filterEdit->isVisible()) {
837 _filterEdit->setVisible(true);
840 _oldFocusItem = qApp->focusWidget();
842 _filterEdit->setFocus();