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 <QTouchEvent>
36 #include "buffermodel.h"
37 #include "bufferviewfilter.h"
38 #include "buffersettings.h"
39 #include "buffersyncer.h"
41 #include "contextmenuactionprovider.h"
42 #include "graphicalui.h"
44 #include "networkmodel.h"
45 #include "contextmenuactionprovider.h"
47 /*****************************************
48 * The TreeView showing the Buffers
49 *****************************************/
50 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
51 // to be on the safe side: call QTreeView's method aswell
52 BufferView::BufferView(QWidget *parent)
55 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
56 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
58 setSelectionMode(QAbstractItemView::ExtendedSelection);
60 QAbstractItemDelegate *oldDelegate = itemDelegate();
61 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
62 setItemDelegate(tristateDelegate);
67 void BufferView::init()
69 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
76 header()->hide(); // nobody seems to use this anyway
79 if (QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
82 // FIXME This is to workaround bug #663
83 setUniformRowHeights(true);
85 #ifndef QT_NO_DRAGANDDROP
88 setDropIndicatorShown(true);
90 setAttribute(Qt::WA_AcceptTouchEvents);
92 setSortingEnabled(true);
93 sortByColumn(0, Qt::AscendingOrder);
95 // activated() fails on X11 and Qtopia at least
96 #if defined Q_WS_QWS || defined Q_WS_X11
97 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
98 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
100 // afaik this is better on Mac and Windows
101 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
102 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
107 void BufferView::setModel(QAbstractItemModel *model)
109 delete selectionModel();
111 QTreeView::setModel(model);
113 // remove old Actions
114 QList<QAction *> oldactions = header()->actions();
115 foreach(QAction *action, oldactions) {
116 header()->removeAction(action);
117 action->deleteLater();
124 QAction *showSection;
125 for (int i = 1; i < model->columnCount(); i++) {
126 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
127 showSection = new QAction(sectionName, header());
128 showSection->setCheckable(true);
129 showSection->setChecked(!isColumnHidden(i));
130 showSection->setProperty("column", i);
131 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
132 header()->addAction(showSection);
135 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
139 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
141 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
143 filter->setConfig(config);
149 disconnect(this, 0, model(), 0);
150 disconnect(model(), 0, this, 0);
157 BufferViewFilter *filter = new BufferViewFilter(model_, config);
159 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
165 void BufferView::setConfig(BufferViewConfig *config)
167 if (_config == config)
171 disconnect(_config, 0, this, 0);
176 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
177 setRootIndexForNetworkId(config->networkId());
181 setRootIndex(QModelIndex());
186 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
188 if (!networkId.isValid() || !model()) {
190 setRootIndex(QModelIndex());
194 int networkCount = model()->rowCount();
196 for (int i = 0; i < networkCount; i++) {
197 child = model()->index(i, 0);
198 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
205 void BufferView::joinChannel(const QModelIndex &index)
207 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
209 if (bufferType != BufferInfo::ChannelBuffer)
212 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
214 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
217 bool BufferView::event(QEvent *event) {
218 if (event->type() == QEvent::TouchBegin && _lastTouchStart < QDateTime::currentMSecsSinceEpoch() - 1000) { //(slow) double tab = normal behaviour = select multiple. 1000 ok?
219 _touchScrollInProgress = true;
220 _lastTouchStart = QDateTime::currentMSecsSinceEpoch();
221 setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
225 if (event->type() == QEvent::TouchUpdate && _touchScrollInProgress) {
226 QTouchEvent::TouchPoint p = ((QTouchEvent*)event)->touchPoints().at(0);
227 verticalScrollBar()->setValue(verticalScrollBar()->value() - (p.pos().y() - p.lastPos().y()));
230 #if QT_VERSION >= 0x050000
231 if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
233 if (event->type() == QEvent::TouchEnd) {
235 _touchScrollInProgress = false;
239 return QTreeView::event(event);
242 void BufferView::mousePressEvent(QMouseEvent * event) {
243 if (!_touchScrollInProgress)
244 QTreeView::mousePressEvent(event);
247 void BufferView::mouseMoveEvent(QMouseEvent * event) {
248 if (!_touchScrollInProgress)
249 QTreeView::mouseMoveEvent(event);
252 void BufferView::keyPressEvent(QKeyEvent *event)
254 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
256 removeSelectedBuffers();
258 QTreeView::keyPressEvent(event);
262 void BufferView::dropEvent(QDropEvent *event)
264 QModelIndex index = indexAt(event->pos());
266 QRect indexRect = visualRect(index);
267 QPoint cursorPos = event->pos();
269 // check if we're really _on_ the item and not indicating a move to just above or below the item
270 const int margin = 2;
271 if (cursorPos.y() - indexRect.top() < margin
272 || indexRect.bottom() - cursorPos.y() < margin)
273 return QTreeView::dropEvent(event);
275 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
276 if (bufferList.count() != 1)
277 return QTreeView::dropEvent(event);
279 BufferId bufferId2 = bufferList[0].second;
281 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
282 return QTreeView::dropEvent(event);
284 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
285 return QTreeView::dropEvent(event);
287 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
288 if (bufferId1 == bufferId2)
289 return QTreeView::dropEvent(event);
291 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
292 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)),
293 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
294 if (res == QMessageBox::Yes) {
295 Client::mergeBuffersPermanently(bufferId1, bufferId2);
300 void BufferView::removeSelectedBuffers(bool permanently)
306 QSet<BufferId> removedRows;
307 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
308 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
311 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
312 if (removedRows.contains(bufferId))
315 removedRows << bufferId;
318 foreach(BufferId bufferId, removedRows) {
320 config()->requestRemoveBufferPermanently(bufferId);
322 config()->requestRemoveBuffer(bufferId);
327 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
329 QTreeView::rowsInserted(parent, start, end);
331 // ensure that newly inserted network nodes are expanded per default
332 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
335 setExpandedState(parent);
339 void BufferView::on_layoutChanged()
341 int numNets = model()->rowCount(QModelIndex());
342 for (int row = 0; row < numNets; row++) {
343 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
344 setExpandedState(networkIdx);
349 void BufferView::on_configChanged()
353 // expand all active networks... collapse inactive ones... unless manually changed
354 QModelIndex networkIdx;
356 for (int row = 0; row < model()->rowCount(); row++) {
357 networkIdx = model()->index(row, 0);
358 if (model()->rowCount(networkIdx) == 0)
361 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
362 if (!networkId.isValid())
365 setExpandedState(networkIdx);
369 // update selection to current one
370 Client::bufferModel()->synchronizeView(this);
375 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
377 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
380 if (isExpanded(networkIdx))
381 oldState |= WasExpanded;
382 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
383 oldState |= WasActive;
385 _expandedState[networkId] = oldState;
389 void BufferView::setExpandedState(const QModelIndex &networkIdx)
391 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
394 if (model()->rowCount(networkIdx) == 0)
397 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
399 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
400 bool expandNetwork = networkActive;
401 if (_expandedState.contains(networkId)) {
402 int oldState = _expandedState[networkId];
403 if ((bool)(oldState & WasActive) == networkActive)
404 expandNetwork = (bool)(oldState & WasExpanded);
407 if (expandNetwork != isExpanded(networkIdx)) {
409 setExpanded(networkIdx, expandNetwork);
411 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
414 #if QT_VERSION < 0x050000
415 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
417 QTreeView::dataChanged(topLeft, bottomRight);
419 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
421 QTreeView::dataChanged(topLeft, bottomRight, roles);
424 // determine how many items have been changed and if any of them is a networkitem
425 // which just swichted from active to inactive or vice versa
426 if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
429 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
430 QModelIndex networkIdx = topLeft.sibling(i, 0);
431 setExpandedState(networkIdx);
436 void BufferView::toggleHeader(bool checked)
438 QAction *action = qobject_cast<QAction *>(sender());
439 header()->setSectionHidden((action->property("column")).toInt(), !checked);
443 void BufferView::contextMenuEvent(QContextMenuEvent *event)
445 QModelIndex index = indexAt(event->pos());
446 if (!index.isValid())
449 QMenu contextMenu(this);
451 if (index.isValid()) {
452 addActionsToMenu(&contextMenu, index);
455 addFilterActions(&contextMenu, index);
457 if (!contextMenu.actions().isEmpty())
458 contextMenu.exec(QCursor::pos());
462 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
464 QModelIndexList indexList = selectedIndexes();
465 // make sure the item we clicked on is first
466 indexList.removeAll(index);
467 indexList.prepend(index);
469 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
473 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
475 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
477 QList<QAction *> filterActions = filter->actions(index);
478 if (!filterActions.isEmpty()) {
479 contextMenu->addSeparator();
480 foreach(QAction *action, filterActions) {
481 contextMenu->addAction(action);
488 void BufferView::menuActionTriggered(QAction *result)
490 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
492 case ContextMenuActionProvider::HideBufferTemporarily:
493 removeSelectedBuffers();
495 case ContextMenuActionProvider::HideBufferPermanently:
496 removeSelectedBuffers(true);
504 void BufferView::nextBuffer()
506 changeBuffer(Forward);
510 void BufferView::previousBuffer()
512 changeBuffer(Backward);
516 void BufferView::changeBuffer(Direction direction)
518 QModelIndex currentIndex = selectionModel()->currentIndex();
519 QModelIndex resultingIndex;
521 if (currentIndex.parent().isValid()) {
522 //If we are a child node just switch among siblings unless it's the first/last child
523 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
525 if (!resultingIndex.isValid()) {
526 QModelIndex parent = currentIndex.parent();
527 if (direction == Backward)
528 resultingIndex = parent;
530 resultingIndex = parent.sibling(parent.row() + direction, 0);
534 //If we have a toplevel node, try and get an adjacent child
535 if (direction == Backward) {
536 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
537 if (model()->hasChildren(newParent))
538 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
540 resultingIndex = newParent;
543 if (model()->hasChildren(currentIndex))
544 resultingIndex = currentIndex.child(0, 0);
546 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
550 if (!resultingIndex.isValid())
553 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
554 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
558 void BufferView::wheelEvent(QWheelEvent *event)
560 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
561 return QTreeView::wheelEvent(event);
563 int rowDelta = (event->delta() > 0) ? -1 : 1;
564 changeBuffer((Direction)rowDelta);
568 void BufferView::hideCurrentBuffer()
570 QModelIndex index = selectionModel()->currentIndex();
571 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
574 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
576 //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.
577 changeBuffer(Backward);
579 /*if(removedRows.contains(bufferId))
582 removedRows << bufferId;*/
584 config()->requestRemoveBufferPermanently(bufferId);
586 config()->requestRemoveBuffer(bufferId);
590 QSize BufferView::sizeHint() const
592 return QTreeView::sizeHint();
595 return QTreeView::sizeHint();
597 if (model()->rowCount() == 0)
598 return QSize(120, 50);
601 for (int i = 0; i < model()->columnCount(); i++) {
602 if (!isColumnHidden(i))
603 columnSize += sizeHintForColumn(i);
605 return QSize(columnSize, 50);
609 // ****************************************
611 // ****************************************
612 class ColorsChangedEvent : public QEvent
615 ColorsChangedEvent() : QEvent(QEvent::User) {};
619 BufferViewDelegate::BufferViewDelegate(QObject *parent)
620 : QStyledItemDelegate(parent)
625 void BufferViewDelegate::customEvent(QEvent *event)
627 if (event->type() != QEvent::User)
634 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
636 if (event->type() != QEvent::MouseButtonRelease)
637 return QStyledItemDelegate::editorEvent(event, model, option, index);
639 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
640 return QStyledItemDelegate::editorEvent(event, model, option, index);
642 QVariant value = index.data(Qt::CheckStateRole);
643 if (!value.isValid())
644 return QStyledItemDelegate::editorEvent(event, model, option, index);
646 QStyleOptionViewItemV4 viewOpt(option);
647 initStyleOption(&viewOpt, index);
649 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
650 QMouseEvent *me = static_cast<QMouseEvent *>(event);
652 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
653 return QStyledItemDelegate::editorEvent(event, model, option, index);
655 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
656 if (state == Qt::Unchecked)
657 state = Qt::PartiallyChecked;
658 else if (state == Qt::PartiallyChecked)
661 state = Qt::Unchecked;
662 model->setData(index, state, Qt::CheckStateRole);
667 // ==============================
669 // ==============================
670 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
671 : QDockWidget(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 &)));
683 void BufferViewDock::updateTitle()
685 QString title = _title;
687 title.prepend(QString::fromUtf8("• "));
688 setWindowTitle(title);
692 void BufferViewDock::setActive(bool active)
694 if (active != isActive()) {
698 raise(); // for tabbed docks
703 void BufferViewDock::bufferViewRenamed(const QString &newName)
707 toggleViewAction()->setText(newName);
711 int BufferViewDock::bufferViewId() const
713 BufferView *view = bufferView();
718 return view->config()->bufferViewId();
724 BufferViewConfig *BufferViewDock::config() const
726 BufferView *view = bufferView();
730 return view->config();