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()));
133 // Make sure collapsation is correct after setting a model
134 // This might not be needed here, only in BufferView::setFilteredModel(). If issues arise, just
135 // move down to setFilteredModel (which calls this function).
140 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
142 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
144 filter->setConfig(config);
150 disconnect(this, 0, model(), 0);
151 disconnect(model(), 0, this, 0);
158 BufferViewFilter *filter = new BufferViewFilter(model_, config);
160 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
166 void BufferView::setConfig(BufferViewConfig *config)
168 if (_config == config)
172 disconnect(_config, 0, this, 0);
177 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
178 setRootIndexForNetworkId(config->networkId());
182 setRootIndex(QModelIndex());
187 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
189 if (!networkId.isValid() || !model()) {
191 setRootIndex(QModelIndex());
195 int networkCount = model()->rowCount();
197 for (int i = 0; i < networkCount; i++) {
198 child = model()->index(i, 0);
199 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
206 void BufferView::joinChannel(const QModelIndex &index)
208 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
210 if (bufferType != BufferInfo::ChannelBuffer)
213 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
215 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
219 void BufferView::keyPressEvent(QKeyEvent *event)
221 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
223 removeSelectedBuffers();
225 TreeViewTouch::keyPressEvent(event);
229 void BufferView::dropEvent(QDropEvent *event)
231 QModelIndex index = indexAt(event->pos());
233 QRect indexRect = visualRect(index);
234 QPoint cursorPos = event->pos();
236 // check if we're really _on_ the item and not indicating a move to just above or below the item
237 // Magic margin number for this is from QAbstractItemViewPrivate::position()
238 const int margin = 2;
239 if (cursorPos.y() - indexRect.top() < margin
240 || indexRect.bottom() - cursorPos.y() < margin)
241 return TreeViewTouch::dropEvent(event);
243 // If more than one buffer was being dragged, treat this as a rearrangement instead of a merge request
244 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
245 if (bufferList.count() != 1)
246 return TreeViewTouch::dropEvent(event);
248 // Get the Buffer ID of the buffer that was being dragged
249 BufferId bufferId2 = bufferList[0].second;
251 // Get the Buffer ID of the target buffer
252 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
254 // If the source and target are the same buffer, this was an aborted rearrangement
255 if (bufferId1 == bufferId2)
256 return TreeViewTouch::dropEvent(event);
258 // Get index of buffer that was being dragged
259 QModelIndex index2 = Client::networkModel()->bufferIndex(bufferId2);
261 // If the buffer being dragged is a channel and we're still joined to it, treat this as a rearrangement
262 // This prevents us from being joined to a channel with no associated UI elements
263 if (index2.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && index2.data(NetworkModel::ItemActiveRole) == true)
264 return TreeViewTouch::dropEvent(event);
266 //If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
267 if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
268 return TreeViewTouch::dropEvent(event);
270 // If the target buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
271 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
272 return TreeViewTouch::dropEvent(event);
274 // Confirm that the user really wants to merge the buffers before doing so
275 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
276 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)),
277 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
278 if (res == QMessageBox::Yes) {
279 Client::mergeBuffersPermanently(bufferId1, bufferId2);
284 void BufferView::removeSelectedBuffers(bool permanently)
290 QSet<BufferId> removedRows;
291 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
292 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
295 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
296 if (removedRows.contains(bufferId))
299 removedRows << bufferId;
302 foreach(BufferId bufferId, removedRows) {
304 config()->requestRemoveBufferPermanently(bufferId);
306 config()->requestRemoveBuffer(bufferId);
311 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
313 TreeViewTouch::rowsInserted(parent, start, end);
315 // ensure that newly inserted network nodes are expanded per default
316 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
319 setExpandedState(parent);
323 void BufferView::on_layoutChanged()
325 int numNets = model()->rowCount(QModelIndex());
326 for (int row = 0; row < numNets; row++) {
327 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
328 setExpandedState(networkIdx);
333 void BufferView::on_configChanged()
337 // Expand/collapse as needed
341 // update selection to current one
342 Client::bufferModel()->synchronizeView(this);
347 void BufferView::setExpandedState()
349 // Expand all active networks, collapse inactive ones... unless manually changed
350 QModelIndex networkIdx;
352 for (int row = 0; row < model()->rowCount(); row++) {
353 networkIdx = model()->index(row, 0);
354 if (model()->rowCount(networkIdx) == 0)
357 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
358 if (!networkId.isValid())
361 setExpandedState(networkIdx);
366 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
368 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
371 if (isExpanded(networkIdx))
372 oldState |= WasExpanded;
373 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
374 oldState |= WasActive;
376 _expandedState[networkId] = oldState;
380 void BufferView::setExpandedState(const QModelIndex &networkIdx)
382 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
385 if (model()->rowCount(networkIdx) == 0)
388 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
390 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
391 bool expandNetwork = networkActive;
392 if (_expandedState.contains(networkId)) {
393 int oldState = _expandedState[networkId];
394 if ((bool)(oldState & WasActive) == networkActive)
395 expandNetwork = (bool)(oldState & WasExpanded);
398 if (expandNetwork != isExpanded(networkIdx)) {
400 setExpanded(networkIdx, expandNetwork);
402 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
405 #if QT_VERSION < 0x050000
406 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
408 TreeViewTouch::dataChanged(topLeft, bottomRight);
410 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
412 TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
415 // determine how many items have been changed and if any of them is a networkitem
416 // which just swichted from active to inactive or vice versa
417 if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
420 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
421 QModelIndex networkIdx = topLeft.sibling(i, 0);
422 setExpandedState(networkIdx);
427 void BufferView::toggleHeader(bool checked)
429 QAction *action = qobject_cast<QAction *>(sender());
430 header()->setSectionHidden((action->property("column")).toInt(), !checked);
434 void BufferView::contextMenuEvent(QContextMenuEvent *event)
436 QModelIndex index = indexAt(event->pos());
437 if (!index.isValid())
440 QMenu contextMenu(this);
442 if (index.isValid()) {
443 addActionsToMenu(&contextMenu, index);
446 addFilterActions(&contextMenu, index);
448 if (!contextMenu.actions().isEmpty())
449 contextMenu.exec(QCursor::pos());
453 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
455 QModelIndexList indexList = selectedIndexes();
456 // make sure the item we clicked on is first
457 indexList.removeAll(index);
458 indexList.prepend(index);
460 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
464 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
466 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
468 QList<QAction *> filterActions = filter->actions(index);
469 if (!filterActions.isEmpty()) {
470 contextMenu->addSeparator();
471 foreach(QAction *action, filterActions) {
472 contextMenu->addAction(action);
479 void BufferView::menuActionTriggered(QAction *result)
481 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
483 case ContextMenuActionProvider::HideBufferTemporarily:
484 removeSelectedBuffers();
486 case ContextMenuActionProvider::HideBufferPermanently:
487 removeSelectedBuffers(true);
495 void BufferView::nextBuffer()
497 changeBuffer(Forward);
501 void BufferView::previousBuffer()
503 changeBuffer(Backward);
507 void BufferView::changeBuffer(Direction direction)
509 QModelIndex currentIndex = selectionModel()->currentIndex();
510 QModelIndex resultingIndex;
512 if (currentIndex.parent().isValid()) {
513 //If we are a child node just switch among siblings unless it's the first/last child
514 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
516 if (!resultingIndex.isValid()) {
517 QModelIndex parent = currentIndex.parent();
518 if (direction == Backward)
519 resultingIndex = parent;
521 resultingIndex = parent.sibling(parent.row() + direction, 0);
525 //If we have a toplevel node, try and get an adjacent child
526 if (direction == Backward) {
527 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
528 if (model()->hasChildren(newParent))
529 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
531 resultingIndex = newParent;
534 if (model()->hasChildren(currentIndex))
535 resultingIndex = currentIndex.child(0, 0);
537 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
541 if (!resultingIndex.isValid())
544 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
545 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
549 void BufferView::wheelEvent(QWheelEvent *event)
551 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
552 return TreeViewTouch::wheelEvent(event);
554 int rowDelta = (event->delta() > 0) ? -1 : 1;
555 changeBuffer((Direction)rowDelta);
559 void BufferView::hideCurrentBuffer()
561 QModelIndex index = selectionModel()->currentIndex();
562 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
565 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
567 //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.
568 changeBuffer(Backward);
570 /*if(removedRows.contains(bufferId))
573 removedRows << bufferId;*/
575 config()->requestRemoveBufferPermanently(bufferId);
577 config()->requestRemoveBuffer(bufferId);
581 QSize BufferView::sizeHint() const
583 return TreeViewTouch::sizeHint();
586 return TreeViewTouch::sizeHint();
588 if (model()->rowCount() == 0)
589 return QSize(120, 50);
592 for (int i = 0; i < model()->columnCount(); i++) {
593 if (!isColumnHidden(i))
594 columnSize += sizeHintForColumn(i);
596 return QSize(columnSize, 50);
600 // ****************************************
602 // ****************************************
603 class ColorsChangedEvent : public QEvent
606 ColorsChangedEvent() : QEvent(QEvent::User) {};
610 BufferViewDelegate::BufferViewDelegate(QObject *parent)
611 : QStyledItemDelegate(parent)
616 void BufferViewDelegate::customEvent(QEvent *event)
618 if (event->type() != QEvent::User)
625 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
627 if (event->type() != QEvent::MouseButtonRelease)
628 return QStyledItemDelegate::editorEvent(event, model, option, index);
630 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
631 return QStyledItemDelegate::editorEvent(event, model, option, index);
633 QVariant value = index.data(Qt::CheckStateRole);
634 if (!value.isValid())
635 return QStyledItemDelegate::editorEvent(event, model, option, index);
637 #if QT_VERSION < 0x050000
638 QStyleOptionViewItemV4 viewOpt(option);
640 QStyleOptionViewItem viewOpt(option);
642 initStyleOption(&viewOpt, index);
644 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
645 QMouseEvent *me = static_cast<QMouseEvent *>(event);
647 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
648 return QStyledItemDelegate::editorEvent(event, model, option, index);
650 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
651 if (state == Qt::Unchecked)
652 state = Qt::PartiallyChecked;
653 else if (state == Qt::PartiallyChecked)
656 state = Qt::Unchecked;
657 model->setData(index, state, Qt::CheckStateRole);
662 // ==============================
664 // ==============================
665 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
666 : QDockWidget(parent),
668 _title(config->bufferViewName())
670 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
671 toggleViewAction()->setData(config->bufferViewId());
672 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
673 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
678 void BufferViewDock::updateTitle()
680 QString title = _title;
682 title.prepend(QString::fromUtf8("• "));
683 setWindowTitle(title);
687 void BufferViewDock::setActive(bool active)
689 if (active != isActive()) {
693 raise(); // for tabbed docks
698 void BufferViewDock::bufferViewRenamed(const QString &newName)
702 toggleViewAction()->setText(newName);
706 int BufferViewDock::bufferViewId() const
708 BufferView *view = bufferView();
713 return view->config()->bufferViewId();
719 BufferViewConfig *BufferViewDock::config() const
721 BufferView *view = bufferView();
725 return view->config();