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);
521 void BufferView::wheelEvent(QWheelEvent *event)
523 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
524 return TreeViewTouch::wheelEvent(event);
526 int rowDelta = (event->delta() > 0) ? -1 : 1;
527 changeBuffer((Direction)rowDelta);
531 void BufferView::hideCurrentBuffer()
533 QModelIndex index = selectionModel()->currentIndex();
534 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
537 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
539 //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.
540 changeBuffer(Backward);
542 /*if(removedRows.contains(bufferId))
545 removedRows << bufferId;*/
547 config()->requestRemoveBufferPermanently(bufferId);
549 config()->requestRemoveBuffer(bufferId);
552 void BufferView::filterTextChanged(QString filterString)
554 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
558 filter->setFilterString(filterString);
559 on_configChanged(); // make sure collapsation is correct
563 QSize BufferView::sizeHint() const
565 return TreeViewTouch::sizeHint();
568 return TreeViewTouch::sizeHint();
570 if (model()->rowCount() == 0)
571 return QSize(120, 50);
574 for (int i = 0; i < model()->columnCount(); i++) {
575 if (!isColumnHidden(i))
576 columnSize += sizeHintForColumn(i);
578 return QSize(columnSize, 50);
582 // ****************************************
584 // ****************************************
585 class ColorsChangedEvent : public QEvent
588 ColorsChangedEvent() : QEvent(QEvent::User) {};
592 BufferViewDelegate::BufferViewDelegate(QObject *parent)
593 : QStyledItemDelegate(parent)
598 void BufferViewDelegate::customEvent(QEvent *event)
600 if (event->type() != QEvent::User)
607 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
609 if (event->type() != QEvent::MouseButtonRelease)
610 return QStyledItemDelegate::editorEvent(event, model, option, index);
612 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
613 return QStyledItemDelegate::editorEvent(event, model, option, index);
615 QVariant value = index.data(Qt::CheckStateRole);
616 if (!value.isValid())
617 return QStyledItemDelegate::editorEvent(event, model, option, index);
619 QStyleOptionViewItemV4 viewOpt(option);
620 initStyleOption(&viewOpt, index);
622 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
623 QMouseEvent *me = static_cast<QMouseEvent *>(event);
625 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
626 return QStyledItemDelegate::editorEvent(event, model, option, index);
628 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
629 if (state == Qt::Unchecked)
630 state = Qt::PartiallyChecked;
631 else if (state == Qt::PartiallyChecked)
634 state = Qt::Unchecked;
635 model->setData(index, state, Qt::CheckStateRole);
640 // ==============================
642 // ==============================
643 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
644 : QDockWidget(parent),
646 _widget(new QWidget(parent)),
647 _filterEdit(new QLineEdit(parent)),
649 _title(config->bufferViewName())
651 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
652 toggleViewAction()->setData(config->bufferViewId());
653 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
654 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
657 _widget->setLayout(new QVBoxLayout);
658 _widget->layout()->setSpacing(0);
659 _widget->layout()->setContentsMargins(0, 0, 0, 0);
660 _filterEdit->setVisible(config->showSearch()); // hide it here, so we don't flicker or somesuch
661 _filterEdit->setPlaceholderText(tr("Search..."));
662 _widget->layout()->addWidget(_filterEdit);
663 QDockWidget::setWidget(_widget);
667 void BufferViewDock::updateTitle()
669 QString title = _title;
671 title.prepend(QString::fromUtf8("• "));
672 setWindowTitle(title);
675 void BufferViewDock::configChanged()
677 _filterEdit->setVisible(config()->showSearch());
679 if (!_filterEdit->isVisible()) {
680 _filterEdit->setText(QLatin1String(""));
684 void BufferViewDock::setActive(bool active)
686 if (active != isActive()) {
690 raise(); // for tabbed docks
695 void BufferViewDock::bufferViewRenamed(const QString &newName)
699 toggleViewAction()->setText(newName);
703 int BufferViewDock::bufferViewId() const
705 BufferView *view = bufferView();
710 return view->config()->bufferViewId();
716 BufferViewConfig *BufferViewDock::config() const
718 BufferView *view = bufferView();
722 return view->config();
725 void BufferViewDock::setWidget(QWidget *newWidget)
727 _widget->layout()->addWidget(newWidget);
728 _childWidget = newWidget;
730 connect(_filterEdit, SIGNAL(textChanged(QString)), bufferView(), SLOT(filterTextChanged(QString)));