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 #if defined Q_OS_MACOS || defined Q_OS_WIN
92 // afaik this is better on Mac and Windows
93 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
94 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
96 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
97 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
102 void BufferView::setModel(QAbstractItemModel *model)
104 delete selectionModel();
106 TreeViewTouch::setModel(model);
108 // remove old Actions
109 QList<QAction *> oldactions = header()->actions();
110 foreach(QAction *action, oldactions) {
111 header()->removeAction(action);
112 action->deleteLater();
119 QAction *showSection;
120 for (int i = 1; i < model->columnCount(); i++) {
121 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
122 showSection = new QAction(sectionName, header());
123 showSection->setCheckable(true);
124 showSection->setChecked(!isColumnHidden(i));
125 showSection->setProperty("column", i);
126 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
127 header()->addAction(showSection);
130 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
132 // Make sure collapsation is correct after setting a model
133 // This might not be needed here, only in BufferView::setFilteredModel(). If issues arise, just
134 // move down to setFilteredModel (which calls this function).
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()));
218 void BufferView::keyPressEvent(QKeyEvent *event)
220 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
222 removeSelectedBuffers();
224 TreeViewTouch::keyPressEvent(event);
228 void BufferView::dropEvent(QDropEvent *event)
230 QModelIndex index = indexAt(event->pos());
232 QRect indexRect = visualRect(index);
233 QPoint cursorPos = event->pos();
235 // check if we're really _on_ the item and not indicating a move to just above or below the item
236 // Magic margin number for this is from QAbstractItemViewPrivate::position()
237 const int margin = 2;
238 if (cursorPos.y() - indexRect.top() < margin
239 || indexRect.bottom() - cursorPos.y() < margin)
240 return TreeViewTouch::dropEvent(event);
242 // If more than one buffer was being dragged, treat this as a rearrangement instead of a merge request
243 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
244 if (bufferList.count() != 1)
245 return TreeViewTouch::dropEvent(event);
247 // Get the Buffer ID of the buffer that was being dragged
248 BufferId bufferId2 = bufferList[0].second;
250 // Get the Buffer ID of the target buffer
251 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
253 // If the source and target are the same buffer, this was an aborted rearrangement
254 if (bufferId1 == bufferId2)
255 return TreeViewTouch::dropEvent(event);
257 // Get index of buffer that was being dragged
258 QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
260 // If the buffer being dragged is a channel and we're still joined to it, treat this as a rearrangement
261 // This prevents us from being joined to a channel with no associated UI elements
262 if (index2.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && index2.data(NetworkModel::ItemActiveRole) == true)
263 return TreeViewTouch::dropEvent(event);
265 //If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
266 if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
267 return TreeViewTouch::dropEvent(event);
269 // If the target buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
270 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
271 return TreeViewTouch::dropEvent(event);
273 // Confirm that the user really wants to merge the buffers before doing so
274 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
275 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)),
276 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
277 if (res == QMessageBox::Yes) {
278 Client::mergeBuffersPermanently(bufferId1, bufferId2);
283 void BufferView::removeSelectedBuffers(bool permanently)
289 QSet<BufferId> removedRows;
290 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
291 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
294 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
295 if (removedRows.contains(bufferId))
298 removedRows << bufferId;
301 foreach(BufferId bufferId, removedRows) {
303 config()->requestRemoveBufferPermanently(bufferId);
305 config()->requestRemoveBuffer(bufferId);
310 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
312 TreeViewTouch::rowsInserted(parent, start, end);
314 // ensure that newly inserted network nodes are expanded per default
315 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
318 setExpandedState(parent);
322 void BufferView::on_layoutChanged()
324 int numNets = model()->rowCount(QModelIndex());
325 for (int row = 0; row < numNets; row++) {
326 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
327 setExpandedState(networkIdx);
332 void BufferView::on_configChanged()
336 // Expand/collapse as needed
340 // update selection to current one
341 Client::bufferModel()->synchronizeView(this);
346 void BufferView::setExpandedState()
348 // Expand all active networks, collapse inactive ones... unless manually changed
349 QModelIndex networkIdx;
351 for (int row = 0; row < model()->rowCount(); row++) {
352 networkIdx = model()->index(row, 0);
353 if (model()->rowCount(networkIdx) == 0)
356 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
357 if (!networkId.isValid())
360 setExpandedState(networkIdx);
365 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
367 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
370 if (isExpanded(networkIdx))
371 oldState |= WasExpanded;
372 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
373 oldState |= WasActive;
375 _expandedState[networkId] = oldState;
379 void BufferView::setExpandedState(const QModelIndex &networkIdx)
381 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
384 if (model()->rowCount(networkIdx) == 0)
387 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
389 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
390 bool expandNetwork = networkActive;
391 if (_expandedState.contains(networkId)) {
392 int oldState = _expandedState[networkId];
393 if ((bool)(oldState & WasActive) == networkActive)
394 expandNetwork = (bool)(oldState & WasExpanded);
397 if (expandNetwork != isExpanded(networkIdx)) {
399 setExpanded(networkIdx, expandNetwork);
401 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
404 #if QT_VERSION < 0x050000
405 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
407 TreeViewTouch::dataChanged(topLeft, bottomRight);
409 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
411 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
414 // determine how many items have been changed and if any of them is a networkitem
415 // which just swichted from active to inactive or vice versa
416 if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
419 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
420 QModelIndex networkIdx = topLeft.sibling(i, 0);
421 setExpandedState(networkIdx);
426 void BufferView::toggleHeader(bool checked)
428 QAction *action = qobject_cast<QAction *>(sender());
429 header()->setSectionHidden((action->property("column")).toInt(), !checked);
433 void BufferView::contextMenuEvent(QContextMenuEvent *event)
435 QModelIndex index = indexAt(event->pos());
436 if (!index.isValid())
439 QMenu contextMenu(this);
441 if (index.isValid()) {
442 addActionsToMenu(&contextMenu, index);
445 addFilterActions(&contextMenu, index);
447 if (!contextMenu.actions().isEmpty())
448 contextMenu.exec(QCursor::pos());
452 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
454 QModelIndexList indexList = selectedIndexes();
455 // make sure the item we clicked on is first
456 indexList.removeAll(index);
457 indexList.prepend(index);
459 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
463 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
465 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
467 QList<QAction *> filterActions = filter->actions(index);
468 if (!filterActions.isEmpty()) {
469 contextMenu->addSeparator();
470 foreach(QAction *action, filterActions) {
471 contextMenu->addAction(action);
478 void BufferView::menuActionTriggered(QAction *result)
480 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
482 case ContextMenuActionProvider::HideBufferTemporarily:
483 removeSelectedBuffers();
485 case ContextMenuActionProvider::HideBufferPermanently:
486 removeSelectedBuffers(true);
494 void BufferView::nextBuffer()
496 changeBuffer(Forward);
500 void BufferView::previousBuffer()
502 changeBuffer(Backward);
506 void BufferView::changeBuffer(Direction direction)
508 QModelIndex currentIndex = selectionModel()->currentIndex();
509 QModelIndex resultingIndex;
511 if (currentIndex.parent().isValid()) {
512 //If we are a child node just switch among siblings unless it's the first/last child
513 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
515 if (!resultingIndex.isValid()) {
516 QModelIndex parent = currentIndex.parent();
517 if (direction == Backward)
518 resultingIndex = parent;
520 resultingIndex = parent.sibling(parent.row() + direction, 0);
524 //If we have a toplevel node, try and get an adjacent child
525 if (direction == Backward) {
526 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
527 if (model()->hasChildren(newParent))
528 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
530 resultingIndex = newParent;
533 if (model()->hasChildren(currentIndex))
534 resultingIndex = currentIndex.child(0, 0);
536 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
540 if (!resultingIndex.isValid())
543 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
544 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
548 void BufferView::wheelEvent(QWheelEvent *event)
550 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
551 return TreeViewTouch::wheelEvent(event);
553 int rowDelta = (event->delta() > 0) ? -1 : 1;
554 changeBuffer((Direction)rowDelta);
558 void BufferView::hideCurrentBuffer()
560 QModelIndex index = selectionModel()->currentIndex();
561 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
564 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
566 //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.
567 changeBuffer(Backward);
569 /*if(removedRows.contains(bufferId))
572 removedRows << bufferId;*/
574 config()->requestRemoveBufferPermanently(bufferId);
576 config()->requestRemoveBuffer(bufferId);
580 QSize BufferView::sizeHint() const
582 return TreeViewTouch::sizeHint();
585 return TreeViewTouch::sizeHint();
587 if (model()->rowCount() == 0)
588 return QSize(120, 50);
591 for (int i = 0; i < model()->columnCount(); i++) {
592 if (!isColumnHidden(i))
593 columnSize += sizeHintForColumn(i);
595 return QSize(columnSize, 50);
599 // ****************************************
601 // ****************************************
602 class ColorsChangedEvent : public QEvent
605 ColorsChangedEvent() : QEvent(QEvent::User) {};
609 BufferViewDelegate::BufferViewDelegate(QObject *parent)
610 : QStyledItemDelegate(parent)
615 void BufferViewDelegate::customEvent(QEvent *event)
617 if (event->type() != QEvent::User)
624 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
626 if (event->type() != QEvent::MouseButtonRelease)
627 return QStyledItemDelegate::editorEvent(event, model, option, index);
629 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
630 return QStyledItemDelegate::editorEvent(event, model, option, index);
632 QVariant value = index.data(Qt::CheckStateRole);
633 if (!value.isValid())
634 return QStyledItemDelegate::editorEvent(event, model, option, index);
636 #if QT_VERSION < 0x050000
637 QStyleOptionViewItemV4 viewOpt(option);
639 QStyleOptionViewItem viewOpt(option);
641 initStyleOption(&viewOpt, index);
643 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
644 QMouseEvent *me = static_cast<QMouseEvent *>(event);
646 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
647 return QStyledItemDelegate::editorEvent(event, model, option, index);
649 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
650 if (state == Qt::Unchecked)
651 state = Qt::PartiallyChecked;
652 else if (state == Qt::PartiallyChecked)
655 state = Qt::Unchecked;
656 model->setData(index, state, Qt::CheckStateRole);
661 // ==============================
663 // ==============================
664 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
665 : QDockWidget(parent),
667 _title(config->bufferViewName())
669 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
670 toggleViewAction()->setData(config->bufferViewId());
671 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
672 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
677 void BufferViewDock::updateTitle()
679 QString title = _title;
681 title.prepend(QString::fromUtf8("• "));
682 setWindowTitle(title);
686 void BufferViewDock::setActive(bool active)
688 if (active != isActive()) {
692 raise(); // for tabbed docks
697 void BufferViewDock::bufferViewRenamed(const QString &newName)
701 toggleViewAction()->setText(newName);
705 int BufferViewDock::bufferViewId() const
707 BufferView *view = bufferView();
712 return view->config()->bufferViewId();
718 BufferViewConfig *BufferViewDock::config() const
720 BufferView *view = bufferView();
724 return view->config();