1 /***************************************************************************
2 * Copyright (C) 2005-2015 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>
33 #include "buffermodel.h"
34 #include "bufferviewfilter.h"
35 #include "buffersettings.h"
36 #include "buffersyncer.h"
38 #include "contextmenuactionprovider.h"
39 #include "graphicalui.h"
41 #include "networkmodel.h"
42 #include "contextmenuactionprovider.h"
44 /*****************************************
45 * The TreeView showing the Buffers
46 *****************************************/
47 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
48 // to be on the safe side: call QTreeView's method aswell (or TreeViewTouch's)
49 BufferView::BufferView(QWidget *parent)
50 : TreeViewTouch(parent)
52 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
53 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
55 setSelectionMode(QAbstractItemView::ExtendedSelection);
57 QAbstractItemDelegate *oldDelegate = itemDelegate();
58 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
59 setItemDelegate(tristateDelegate);
64 void BufferView::init()
66 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
71 // New entries will be expanded automatically when added; no need to call expandAll()
73 header()->hide(); // nobody seems to use this anyway
76 if (QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
79 // FIXME This is to workaround bug #663
80 setUniformRowHeights(true);
82 #ifndef QT_NO_DRAGANDDROP
85 setDropIndicatorShown(true);
88 setSortingEnabled(true);
89 sortByColumn(0, Qt::AscendingOrder);
91 // activated() fails on X11 and Qtopia at least
92 #if defined Q_WS_QWS || defined Q_WS_X11
93 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
94 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
96 // afaik this is better on Mac and Windows
97 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
98 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
103 void BufferView::setModel(QAbstractItemModel *model)
105 delete selectionModel();
107 TreeViewTouch::setModel(model);
109 // remove old Actions
110 QList<QAction *> oldactions = header()->actions();
111 foreach(QAction *action, oldactions) {
112 header()->removeAction(action);
113 action->deleteLater();
120 QAction *showSection;
121 for (int i = 1; i < model->columnCount(); i++) {
122 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
123 showSection = new QAction(sectionName, header());
124 showSection->setCheckable(true);
125 showSection->setChecked(!isColumnHidden(i));
126 showSection->setProperty("column", i);
127 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
128 header()->addAction(showSection);
131 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
135 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
137 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
139 filter->setConfig(config);
145 disconnect(this, 0, model(), 0);
146 disconnect(model(), 0, this, 0);
153 BufferViewFilter *filter = new BufferViewFilter(model_, config);
155 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
161 void BufferView::setConfig(BufferViewConfig *config)
163 if (_config == config)
167 disconnect(_config, 0, this, 0);
172 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
173 setRootIndexForNetworkId(config->networkId());
177 setRootIndex(QModelIndex());
182 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
184 if (!networkId.isValid() || !model()) {
186 setRootIndex(QModelIndex());
190 int networkCount = model()->rowCount();
192 for (int i = 0; i < networkCount; i++) {
193 child = model()->index(i, 0);
194 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
201 void BufferView::joinChannel(const QModelIndex &index)
203 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
205 if (bufferType != BufferInfo::ChannelBuffer)
208 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
210 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
214 void BufferView::keyPressEvent(QKeyEvent *event)
216 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
218 removeSelectedBuffers();
220 TreeViewTouch::keyPressEvent(event);
224 void BufferView::dropEvent(QDropEvent *event)
226 QModelIndex index = indexAt(event->pos());
228 QRect indexRect = visualRect(index);
229 QPoint cursorPos = event->pos();
231 // check if we're really _on_ the item and not indicating a move to just above or below the item
232 // Magic margin number for this is from QAbstractItemViewPrivate::position()
233 const int margin = 2;
234 if (cursorPos.y() - indexRect.top() < margin
235 || indexRect.bottom() - cursorPos.y() < margin)
236 return TreeViewTouch::dropEvent(event);
238 // If more than one buffer was being dragged, treat this as a rearrangement instead of a merge request
239 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
240 if (bufferList.count() != 1)
241 return TreeViewTouch::dropEvent(event);
243 // Get the Buffer ID of the buffer that was being dragged
244 BufferId bufferId2 = bufferList[0].second;
246 // Get the Buffer ID of the target buffer
247 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
249 // If the source and target are the same buffer, this was an aborted rearrangement
250 if (bufferId1 == bufferId2)
251 return TreeViewTouch::dropEvent(event);
253 // Get index of buffer that was being dragged
254 QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
256 // If the buffer being dragged is a channel and we're still joined to it, treat this as a rearrangement
257 // This prevents us from being joined to a channel with no associated UI elements
258 if (index2.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && index2.data(NetworkModel::ItemActiveRole) == true)
259 return TreeViewTouch::dropEvent(event);
261 //If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
262 if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
263 return TreeViewTouch::dropEvent(event);
265 // If the target buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
266 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
267 return TreeViewTouch::dropEvent(event);
269 // Confirm that the user really wants to merge the buffers before doing so
270 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
271 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)),
272 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
273 if (res == QMessageBox::Yes) {
274 Client::mergeBuffersPermanently(bufferId1, bufferId2);
279 void BufferView::removeSelectedBuffers(bool permanently)
285 QSet<BufferId> removedRows;
286 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
287 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
290 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
291 if (removedRows.contains(bufferId))
294 removedRows << bufferId;
297 foreach(BufferId bufferId, removedRows) {
299 config()->requestRemoveBufferPermanently(bufferId);
301 config()->requestRemoveBuffer(bufferId);
306 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
308 TreeViewTouch::rowsInserted(parent, start, end);
310 // ensure that newly inserted network nodes are expanded per default
311 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
314 setExpandedState(parent);
318 void BufferView::on_layoutChanged()
320 int numNets = model()->rowCount(QModelIndex());
321 for (int row = 0; row < numNets; row++) {
322 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
323 setExpandedState(networkIdx);
328 void BufferView::on_configChanged()
332 // expand all active networks... collapse inactive ones... unless manually changed
333 QModelIndex networkIdx;
335 for (int row = 0; row < model()->rowCount(); row++) {
336 networkIdx = model()->index(row, 0);
337 if (model()->rowCount(networkIdx) == 0)
340 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
341 if (!networkId.isValid())
344 setExpandedState(networkIdx);
348 // update selection to current one
349 Client::bufferModel()->synchronizeView(this);
354 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
356 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
359 if (isExpanded(networkIdx))
360 oldState |= WasExpanded;
361 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
362 oldState |= WasActive;
364 _expandedState[networkId] = oldState;
368 void BufferView::setExpandedState(const QModelIndex &networkIdx)
370 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
373 if (model()->rowCount(networkIdx) == 0)
376 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
378 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
379 bool expandNetwork = networkActive;
380 if (_expandedState.contains(networkId)) {
381 int oldState = _expandedState[networkId];
382 if ((bool)(oldState & WasActive) == networkActive)
383 expandNetwork = (bool)(oldState & WasExpanded);
386 if (expandNetwork != isExpanded(networkIdx)) {
388 setExpanded(networkIdx, expandNetwork);
390 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
393 #if QT_VERSION < 0x050000
394 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
396 TreeViewTouch::dataChanged(topLeft, bottomRight);
398 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
400 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
403 // determine how many items have been changed and if any of them is a networkitem
404 // which just swichted from active to inactive or vice versa
405 if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
408 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
409 QModelIndex networkIdx = topLeft.sibling(i, 0);
410 setExpandedState(networkIdx);
415 void BufferView::toggleHeader(bool checked)
417 QAction *action = qobject_cast<QAction *>(sender());
418 header()->setSectionHidden((action->property("column")).toInt(), !checked);
422 void BufferView::contextMenuEvent(QContextMenuEvent *event)
424 QModelIndex index = indexAt(event->pos());
425 if (!index.isValid())
428 QMenu contextMenu(this);
430 if (index.isValid()) {
431 addActionsToMenu(&contextMenu, index);
434 addFilterActions(&contextMenu, index);
436 if (!contextMenu.actions().isEmpty())
437 contextMenu.exec(QCursor::pos());
441 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
443 QModelIndexList indexList = selectedIndexes();
444 // make sure the item we clicked on is first
445 indexList.removeAll(index);
446 indexList.prepend(index);
448 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
452 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
454 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
456 QList<QAction *> filterActions = filter->actions(index);
457 if (!filterActions.isEmpty()) {
458 contextMenu->addSeparator();
459 foreach(QAction *action, filterActions) {
460 contextMenu->addAction(action);
467 void BufferView::menuActionTriggered(QAction *result)
469 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
471 case ContextMenuActionProvider::HideBufferTemporarily:
472 removeSelectedBuffers();
474 case ContextMenuActionProvider::HideBufferPermanently:
475 removeSelectedBuffers(true);
483 void BufferView::nextBuffer()
485 changeBuffer(Forward);
489 void BufferView::previousBuffer()
491 changeBuffer(Backward);
495 void BufferView::changeBuffer(Direction direction)
497 QModelIndex currentIndex = selectionModel()->currentIndex();
498 QModelIndex resultingIndex;
500 if (currentIndex.parent().isValid()) {
501 //If we are a child node just switch among siblings unless it's the first/last child
502 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
504 if (!resultingIndex.isValid()) {
505 QModelIndex parent = currentIndex.parent();
506 if (direction == Backward)
507 resultingIndex = parent;
509 resultingIndex = parent.sibling(parent.row() + direction, 0);
513 //If we have a toplevel node, try and get an adjacent child
514 if (direction == Backward) {
515 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
516 if (model()->hasChildren(newParent))
517 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
519 resultingIndex = newParent;
522 if (model()->hasChildren(currentIndex))
523 resultingIndex = currentIndex.child(0, 0);
525 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
529 if (!resultingIndex.isValid())
532 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
533 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
537 void BufferView::wheelEvent(QWheelEvent *event)
539 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
540 return TreeViewTouch::wheelEvent(event);
542 int rowDelta = (event->delta() > 0) ? -1 : 1;
543 changeBuffer((Direction)rowDelta);
547 void BufferView::hideCurrentBuffer()
549 QModelIndex index = selectionModel()->currentIndex();
550 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
553 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
555 //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.
556 changeBuffer(Backward);
558 /*if(removedRows.contains(bufferId))
561 removedRows << bufferId;*/
563 config()->requestRemoveBufferPermanently(bufferId);
565 config()->requestRemoveBuffer(bufferId);
569 QSize BufferView::sizeHint() const
571 return TreeViewTouch::sizeHint();
574 return TreeViewTouch::sizeHint();
576 if (model()->rowCount() == 0)
577 return QSize(120, 50);
580 for (int i = 0; i < model()->columnCount(); i++) {
581 if (!isColumnHidden(i))
582 columnSize += sizeHintForColumn(i);
584 return QSize(columnSize, 50);
588 // ****************************************
590 // ****************************************
591 class ColorsChangedEvent : public QEvent
594 ColorsChangedEvent() : QEvent(QEvent::User) {};
598 BufferViewDelegate::BufferViewDelegate(QObject *parent)
599 : QStyledItemDelegate(parent)
604 void BufferViewDelegate::customEvent(QEvent *event)
606 if (event->type() != QEvent::User)
613 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
615 if (event->type() != QEvent::MouseButtonRelease)
616 return QStyledItemDelegate::editorEvent(event, model, option, index);
618 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
619 return QStyledItemDelegate::editorEvent(event, model, option, index);
621 QVariant value = index.data(Qt::CheckStateRole);
622 if (!value.isValid())
623 return QStyledItemDelegate::editorEvent(event, model, option, index);
625 #if QT_VERSION < 0x050000
626 QStyleOptionViewItemV4 viewOpt(option);
628 QStyleOptionViewItem viewOpt(option);
630 initStyleOption(&viewOpt, index);
632 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
633 QMouseEvent *me = static_cast<QMouseEvent *>(event);
635 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
636 return QStyledItemDelegate::editorEvent(event, model, option, index);
638 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
639 if (state == Qt::Unchecked)
640 state = Qt::PartiallyChecked;
641 else if (state == Qt::PartiallyChecked)
644 state = Qt::Unchecked;
645 model->setData(index, state, Qt::CheckStateRole);
650 // ==============================
652 // ==============================
653 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
654 : QDockWidget(parent),
656 _title(config->bufferViewName())
658 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
659 toggleViewAction()->setData(config->bufferViewId());
660 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
661 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
666 void BufferViewDock::updateTitle()
668 QString title = _title;
670 title.prepend(QString::fromUtf8("• "));
671 setWindowTitle(title);
675 void BufferViewDock::setActive(bool active)
677 if (active != isActive()) {
681 raise(); // for tabbed docks
686 void BufferViewDock::bufferViewRenamed(const QString &newName)
690 toggleViewAction()->setText(newName);
694 int BufferViewDock::bufferViewId() const
696 BufferView *view = bufferView();
701 return view->config()->bufferViewId();
707 BufferViewConfig *BufferViewDock::config() const
709 BufferView *view = bufferView();
713 return view->config();