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
49 BufferView::BufferView(QWidget *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);
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 QTreeView::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::setSelectionModel(QItemSelectionModel *selectionModel)
163 if (QTreeView::selectionModel())
164 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
165 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
167 QTreeView::setSelectionModel(selectionModel);
168 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
170 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
171 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
176 void BufferView::setConfig(BufferViewConfig *config)
178 if (_config == config)
182 disconnect(_config, 0, this, 0);
187 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
188 setRootIndexForNetworkId(config->networkId());
192 setRootIndex(QModelIndex());
197 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
199 if (!networkId.isValid() || !model()) {
201 setRootIndex(QModelIndex());
205 int networkCount = model()->rowCount();
207 for (int i = 0; i < networkCount; i++) {
208 child = model()->index(i, 0);
209 if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
216 void BufferView::joinChannel(const QModelIndex &index)
218 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
220 if (bufferType != BufferInfo::ChannelBuffer)
223 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
225 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
229 void BufferView::keyPressEvent(QKeyEvent *event)
231 if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
233 removeSelectedBuffers();
235 QTreeView::keyPressEvent(event);
239 void BufferView::dropEvent(QDropEvent *event)
241 QModelIndex index = indexAt(event->pos());
243 QRect indexRect = visualRect(index);
244 QPoint cursorPos = event->pos();
246 // check if we're really _on_ the item and not indicating a move to just above or below the item
247 const int margin = 2;
248 if (cursorPos.y() - indexRect.top() < margin
249 || indexRect.bottom() - cursorPos.y() < margin)
250 return QTreeView::dropEvent(event);
252 QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
253 if (bufferList.count() != 1)
254 return QTreeView::dropEvent(event);
256 NetworkId networkId = bufferList[0].first;
257 BufferId bufferId2 = bufferList[0].second;
259 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
260 return QTreeView::dropEvent(event);
262 if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
263 return QTreeView::dropEvent(event);
265 if (index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
266 return QTreeView::dropEvent(event);
268 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
269 if (bufferId1 == bufferId2)
270 return QTreeView::dropEvent(event);
272 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
273 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)),
274 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
275 if (res == QMessageBox::Yes) {
276 Client::mergeBuffersPermanently(bufferId1, bufferId2);
281 void BufferView::removeSelectedBuffers(bool permanently)
287 QSet<BufferId> removedRows;
288 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
289 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
292 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
293 if (removedRows.contains(bufferId))
296 removedRows << bufferId;
299 foreach(BufferId bufferId, removedRows) {
301 config()->requestRemoveBufferPermanently(bufferId);
303 config()->requestRemoveBuffer(bufferId);
308 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
310 QTreeView::rowsInserted(parent, start, end);
312 // ensure that newly inserted network nodes are expanded per default
313 if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
316 setExpandedState(parent);
320 void BufferView::on_layoutChanged()
322 int numNets = model()->rowCount(QModelIndex());
323 for (int row = 0; row < numNets; row++) {
324 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
325 setExpandedState(networkIdx);
330 void BufferView::on_configChanged()
334 // expand all active networks... collapse inactive ones... unless manually changed
335 QModelIndex networkIdx;
337 for (int row = 0; row < model()->rowCount(); row++) {
338 networkIdx = model()->index(row, 0);
339 if (model()->rowCount(networkIdx) == 0)
342 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
343 if (!networkId.isValid())
346 setExpandedState(networkIdx);
350 // update selection to current one
351 Client::bufferModel()->synchronizeView(this);
356 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
358 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
361 if (isExpanded(networkIdx))
362 oldState |= WasExpanded;
363 if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
364 oldState |= WasActive;
366 _expandedState[networkId] = oldState;
370 void BufferView::setExpandedState(const QModelIndex &networkIdx)
372 if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
375 if (model()->rowCount(networkIdx) == 0)
378 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
380 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
381 bool expandNetwork = networkActive;
382 if (_expandedState.contains(networkId)) {
383 int oldState = _expandedState[networkId];
384 if ((bool)(oldState & WasActive) == networkActive)
385 expandNetwork = (bool)(oldState & WasExpanded);
388 if (expandNetwork != isExpanded(networkIdx)) {
390 setExpanded(networkIdx, expandNetwork);
392 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
395 #if QT_VERSION < 0x050000
396 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
398 QTreeView::dataChanged(topLeft, bottomRight);
400 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
402 QTreeView::dataChanged(topLeft, bottomRight, roles);
405 // determine how many items have been changed and if any of them is a networkitem
406 // which just swichted from active to inactive or vice versa
407 if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
410 for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
411 QModelIndex networkIdx = topLeft.sibling(i, 0);
412 setExpandedState(networkIdx);
417 void BufferView::toggleHeader(bool checked)
419 QAction *action = qobject_cast<QAction *>(sender());
420 header()->setSectionHidden((action->property("column")).toInt(), !checked);
424 void BufferView::contextMenuEvent(QContextMenuEvent *event)
426 QModelIndex index = indexAt(event->pos());
427 if (!index.isValid())
430 QMenu contextMenu(this);
432 if (index.isValid()) {
433 addActionsToMenu(&contextMenu, index);
436 addFilterActions(&contextMenu, index);
438 if (!contextMenu.actions().isEmpty())
439 contextMenu.exec(QCursor::pos());
443 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
445 QModelIndexList indexList = selectedIndexes();
446 // make sure the item we clicked on is first
447 indexList.removeAll(index);
448 indexList.prepend(index);
450 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
454 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
456 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
458 QList<QAction *> filterActions = filter->actions(index);
459 if (!filterActions.isEmpty()) {
460 contextMenu->addSeparator();
461 foreach(QAction *action, filterActions) {
462 contextMenu->addAction(action);
469 void BufferView::menuActionTriggered(QAction *result)
471 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
473 case ContextMenuActionProvider::HideBufferTemporarily:
474 removeSelectedBuffers();
476 case ContextMenuActionProvider::HideBufferPermanently:
477 removeSelectedBuffers(true);
485 void BufferView::nextBuffer()
487 changeBuffer(Forward);
491 void BufferView::previousBuffer()
493 changeBuffer(Backward);
497 void BufferView::changeBuffer(Direction direction)
499 QModelIndex currentIndex = selectionModel()->currentIndex();
500 QModelIndex resultingIndex;
502 if (currentIndex.parent().isValid()) {
503 //If we are a child node just switch among siblings unless it's the first/last child
504 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
506 if (!resultingIndex.isValid()) {
507 QModelIndex parent = currentIndex.parent();
508 if (direction == Backward)
509 resultingIndex = parent;
511 resultingIndex = parent.sibling(parent.row() + direction, 0);
515 //If we have a toplevel node, try and get an adjacent child
516 if (direction == Backward) {
517 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
518 if (model()->hasChildren(newParent))
519 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
521 resultingIndex = newParent;
524 if (model()->hasChildren(currentIndex))
525 resultingIndex = currentIndex.child(0, 0);
527 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
531 if (!resultingIndex.isValid())
534 selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
535 selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
539 void BufferView::wheelEvent(QWheelEvent *event)
541 if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
542 return QTreeView::wheelEvent(event);
544 int rowDelta = (event->delta() > 0) ? -1 : 1;
545 changeBuffer((Direction)rowDelta);
549 void BufferView::hideCurrentBuffer()
551 QModelIndex index = selectionModel()->currentIndex();
552 if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
555 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
557 //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.
558 changeBuffer(Backward);
560 /*if(removedRows.contains(bufferId))
563 removedRows << bufferId;*/
565 config()->requestRemoveBufferPermanently(bufferId);
567 config()->requestRemoveBuffer(bufferId);
571 QSize BufferView::sizeHint() const
573 return QTreeView::sizeHint();
576 return QTreeView::sizeHint();
578 if (model()->rowCount() == 0)
579 return QSize(120, 50);
582 for (int i = 0; i < model()->columnCount(); i++) {
583 if (!isColumnHidden(i))
584 columnSize += sizeHintForColumn(i);
586 return QSize(columnSize, 50);
590 // ****************************************
592 // ****************************************
593 class ColorsChangedEvent : public QEvent
596 ColorsChangedEvent() : QEvent(QEvent::User) {};
600 BufferViewDelegate::BufferViewDelegate(QObject *parent)
601 : QStyledItemDelegate(parent)
606 void BufferViewDelegate::customEvent(QEvent *event)
608 if (event->type() != QEvent::User)
615 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
617 if (event->type() != QEvent::MouseButtonRelease)
618 return QStyledItemDelegate::editorEvent(event, model, option, index);
620 if (!(model->flags(index) & Qt::ItemIsUserCheckable))
621 return QStyledItemDelegate::editorEvent(event, model, option, index);
623 QVariant value = index.data(Qt::CheckStateRole);
624 if (!value.isValid())
625 return QStyledItemDelegate::editorEvent(event, model, option, index);
627 QStyleOptionViewItemV4 viewOpt(option);
628 initStyleOption(&viewOpt, index);
630 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
631 QMouseEvent *me = static_cast<QMouseEvent *>(event);
633 if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
634 return QStyledItemDelegate::editorEvent(event, model, option, index);
636 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
637 if (state == Qt::Unchecked)
638 state = Qt::PartiallyChecked;
639 else if (state == Qt::PartiallyChecked)
642 state = Qt::Unchecked;
643 model->setData(index, state, Qt::CheckStateRole);
648 // ==============================
650 // ==============================
651 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
652 : QDockWidget(parent),
654 _title(config->bufferViewName())
656 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
657 toggleViewAction()->setData(config->bufferViewId());
658 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
659 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
664 void BufferViewDock::updateTitle()
666 QString title = _title;
668 title.prepend(QString::fromUtf8("• "));
669 setWindowTitle(title);
673 void BufferViewDock::setActive(bool active)
675 if (active != isActive()) {
679 raise(); // for tabbed docks
684 void BufferViewDock::bufferViewRenamed(const QString &newName)
688 toggleViewAction()->setText(newName);
692 int BufferViewDock::bufferViewId() const
694 BufferView *view = bufferView();
699 return view->config()->bufferViewId();
705 BufferViewConfig *BufferViewDock::config() const
707 BufferView *view = bufferView();
711 return view->config();