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);
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 const int margin = 2;
234 if (cursorPos.y() - indexRect.top() < margin
235 || indexRect.bottom() - cursorPos.y() < margin)
236 return TreeViewTouch::dropEvent(event);
238 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
239 if (bufferList.count() != 1)
240 return TreeViewTouch::dropEvent(event);
242 BufferId bufferId2 = bufferList[0].second;
244 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
245 return TreeViewTouch::dropEvent(event);
247 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
248 return TreeViewTouch::dropEvent(event);
250 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
251 if (bufferId1 == bufferId2)
252 return TreeViewTouch::dropEvent(event);
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);
263 void BufferView::removeSelectedBuffers(bool permanently)
269 QSet<BufferId> removedRows;
270 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
271 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
274 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
275 if (removedRows.contains(bufferId))
278 removedRows << bufferId;
281 foreach(BufferId bufferId, removedRows) {
283 config()->requestRemoveBufferPermanently(bufferId);
285 config()->requestRemoveBuffer(bufferId);
290 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
292 TreeViewTouch::rowsInserted(parent, start, end);
294 // ensure that newly inserted network nodes are expanded per default
295 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
298 setExpandedState(parent);
302 void BufferView::on_layoutChanged()
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);
312 void BufferView::on_configChanged()
316 // expand all active networks... collapse inactive ones... unless manually changed
317 QModelIndex networkIdx;
319 for (int row = 0; row < model()->rowCount(); row++) {
320 networkIdx = model()->index(row, 0);
321 if (model()->rowCount(networkIdx) == 0)
324 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
325 if (!networkId.isValid())
328 setExpandedState(networkIdx);
332 // update selection to current one
333 Client::bufferModel()->synchronizeView(this);
338 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
340 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
343 if (isExpanded(networkIdx))
344 oldState |= WasExpanded;
345 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
346 oldState |= WasActive;
348 _expandedState[networkId] = oldState;
352 void BufferView::setExpandedState(const QModelIndex &networkIdx)
354 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
357 if (model()->rowCount(networkIdx) == 0)
360 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
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);
370 if (expandNetwork != isExpanded(networkIdx)) {
372 setExpanded(networkIdx, expandNetwork);
374 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
377 #if QT_VERSION < 0x050000
378 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
380 TreeViewTouch::dataChanged(topLeft, bottomRight);
382 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
384 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
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)
392 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
393 QModelIndex networkIdx = topLeft.sibling(i, 0);
394 setExpandedState(networkIdx);
399 void BufferView::toggleHeader(bool checked)
401 QAction *action = qobject_cast<QAction *>(sender());
402 header()->setSectionHidden((action->property("column")).toInt(), !checked);
406 void BufferView::contextMenuEvent(QContextMenuEvent *event)
408 QModelIndex index = indexAt(event->pos());
409 if (!index.isValid())
412 QMenu contextMenu(this);
414 if (index.isValid()) {
415 addActionsToMenu(&contextMenu, index);
418 addFilterActions(&contextMenu, index);
420 if (!contextMenu.actions().isEmpty())
421 contextMenu.exec(QCursor::pos());
425 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
427 QModelIndexList indexList = selectedIndexes();
428 // make sure the item we clicked on is first
429 indexList.removeAll(index);
430 indexList.prepend(index);
432 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
436 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
438 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
440 QList<QAction *> filterActions = filter->actions(index);
441 if (!filterActions.isEmpty()) {
442 contextMenu->addSeparator();
443 foreach(QAction *action, filterActions) {
444 contextMenu->addAction(action);
451 void BufferView::menuActionTriggered(QAction *result)
453 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
455 case ContextMenuActionProvider::HideBufferTemporarily:
456 removeSelectedBuffers();
458 case ContextMenuActionProvider::HideBufferPermanently:
459 removeSelectedBuffers(true);
467 void BufferView::nextBuffer()
469 changeBuffer(Forward);
473 void BufferView::previousBuffer()
475 changeBuffer(Backward);
479 void BufferView::changeBuffer(Direction direction)
481 QModelIndex currentIndex = selectionModel()->currentIndex();
482 QModelIndex resultingIndex;
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);
488 if (!resultingIndex.isValid()) {
489 QModelIndex parent = currentIndex.parent();
490 if (direction == Backward)
491 resultingIndex = parent;
493 resultingIndex = parent.sibling(parent.row() + direction, 0);
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);
503 resultingIndex = newParent;
506 if (model()->hasChildren(currentIndex))
507 resultingIndex = currentIndex.child(0, 0);
509 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
513 if (!resultingIndex.isValid())
516 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
517 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
520 void BufferView::selectFirstBuffer()
522 int networksCount = model()->rowCount(QModelIndex());
523 if (networksCount == 0) {
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);
537 if (!bufferIndex.isValid()) {
541 selectionModel()->setCurrentIndex(bufferIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
542 selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
545 void BufferView::wheelEvent(QWheelEvent *event)
547 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
548 return TreeViewTouch::wheelEvent(event);
550 int rowDelta = (event->delta() > 0) ? -1 : 1;
551 changeBuffer((Direction)rowDelta);
555 void BufferView::hideCurrentBuffer()
557 QModelIndex index = selectionModel()->currentIndex();
558 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
561 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
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);
566 /*if(removedRows.contains(bufferId))
569 removedRows << bufferId;*/
571 config()->requestRemoveBufferPermanently(bufferId);
573 config()->requestRemoveBuffer(bufferId);
576 void BufferView::filterTextChanged(QString filterString)
578 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
582 filter->setFilterString(filterString);
583 on_configChanged(); // make sure collapsation is correct
587 QSize BufferView::sizeHint() const
589 return TreeViewTouch::sizeHint();
592 return TreeViewTouch::sizeHint();
594 if (model()->rowCount() == 0)
595 return QSize(120, 50);
598 for (int i = 0; i < model()->columnCount(); i++) {
599 if (!isColumnHidden(i))
600 columnSize += sizeHintForColumn(i);
602 return QSize(columnSize, 50);
606 // ****************************************
608 // ****************************************
609 class ColorsChangedEvent : public QEvent
612 ColorsChangedEvent() : QEvent(QEvent::User) {};
616 BufferViewDelegate::BufferViewDelegate(QObject *parent)
617 : QStyledItemDelegate(parent)
622 void BufferViewDelegate::customEvent(QEvent *event)
624 if (event->type() != QEvent::User)
631 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
633 if (event->type() != QEvent::MouseButtonRelease)
634 return QStyledItemDelegate::editorEvent(event, model, option, index);
636 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
637 return QStyledItemDelegate::editorEvent(event, model, option, index);
639 QVariant value = index.data(Qt::CheckStateRole);
640 if (!value.isValid())
641 return QStyledItemDelegate::editorEvent(event, model, option, index);
643 QStyleOptionViewItemV4 viewOpt(option);
644 initStyleOption(&viewOpt, index);
646 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
647 QMouseEvent *me = static_cast<QMouseEvent *>(event);
649 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
650 return QStyledItemDelegate::editorEvent(event, model, option, index);
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)
658 state = Qt::Unchecked;
659 model->setData(index, state, Qt::CheckStateRole);
664 // ==============================
666 // ==============================
667 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
668 : QDockWidget(parent),
670 _widget(new QWidget(parent)),
671 _filterEdit(new QLineEdit(parent)),
673 _title(config->bufferViewName())
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()));
682 _widget->setLayout(new QVBoxLayout);
683 _widget->layout()->setSpacing(0);
684 _widget->layout()->setContentsMargins(0, 0, 0, 0);
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()));
693 _widget->layout()->addWidget(_filterEdit);
694 QDockWidget::setWidget(_widget);
698 void BufferViewDock::updateTitle()
700 QString title = _title;
702 title.prepend(QString::fromUtf8("• "));
703 setWindowTitle(title);
706 void BufferViewDock::configChanged()
708 if (_filterEdit->isVisible() != config()->showSearch()) {
709 _filterEdit->setVisible(config()->showSearch());
710 _filterEdit->clear();
714 void BufferViewDock::onFilterReturnPressed()
717 _oldFocusItem->setFocus();
721 if (!config()->showSearch()) {
722 _filterEdit->setVisible(false);
725 BufferView *view = bufferView();
726 if (!view || _filterEdit->text().isEmpty()) {
730 view->selectFirstBuffer();
731 _filterEdit->clear();
734 void BufferViewDock::setActive(bool active)
736 if (active != isActive()) {
740 raise(); // for tabbed docks
745 bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
747 if (object != _filterEdit) {
751 if (event->type() == QEvent::FocusOut) {
752 if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
753 _filterEdit->setVisible(false);
756 } else if (event->type() == QEvent::KeyRelease) {
757 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
758 if (keyEvent->key() != Qt::Key_Escape) {
762 _filterEdit->clear();
765 _oldFocusItem->setFocus();
775 void BufferViewDock::bufferViewRenamed(const QString &newName)
779 toggleViewAction()->setText(newName);
783 int BufferViewDock::bufferViewId() const
785 BufferView *view = bufferView();
790 return view->config()->bufferViewId();
796 BufferViewConfig *BufferViewDock::config() const
798 BufferView *view = bufferView();
802 return view->config();
805 void BufferViewDock::setWidget(QWidget *newWidget)
807 _widget->layout()->addWidget(newWidget);
808 _childWidget = newWidget;
810 connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));
813 void BufferViewDock::activateFilter()
815 if (!_filterEdit->isVisible()) {
816 _filterEdit->setVisible(true);
819 _oldFocusItem = qApp->focusWidget();
821 _filterEdit->setFocus();