1 /***************************************************************************
2 * Copyright (C) 2005-2010 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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);
63 void BufferView::init() {
64 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
71 header()->hide(); // nobody seems to use this anyway
74 if(QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
77 // FIXME This is to workaround bug #663
78 setUniformRowHeights(true);
80 #ifndef QT_NO_DRAGANDDROP
83 setDropIndicatorShown(true);
86 setSortingEnabled(true);
87 sortByColumn(0, Qt::AscendingOrder);
89 // activated() fails on X11 and Qtopia at least
90 #if defined Q_WS_QWS || defined Q_WS_X11
91 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
92 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
94 // afaik this is better on Mac and Windows
95 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
96 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
100 void BufferView::setModel(QAbstractItemModel *model) {
101 delete selectionModel();
103 QTreeView::setModel(model);
105 // remove old Actions
106 QList<QAction *> oldactions = header()->actions();
107 foreach(QAction *action, oldactions) {
108 header()->removeAction(action);
109 action->deleteLater();
116 QAction *showSection;
117 for(int i = 1; i < model->columnCount(); i++) {
118 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
119 showSection = new QAction(sectionName, header());
120 showSection->setCheckable(true);
121 showSection->setChecked(!isColumnHidden(i));
122 showSection->setProperty("column", i);
123 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
124 header()->addAction(showSection);
127 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
130 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
131 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
133 filter->setConfig(config);
139 disconnect(this, 0, model(), 0);
140 disconnect(model(), 0, this, 0);
146 BufferViewFilter *filter = new BufferViewFilter(model_, config);
148 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
153 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
154 if(QTreeView::selectionModel())
155 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
156 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
158 QTreeView::setSelectionModel(selectionModel);
159 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
161 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
162 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
166 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());
180 setRootIndex(QModelIndex());
184 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
185 if(!networkId.isValid() || !model()) {
187 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>())
200 void BufferView::joinChannel(const QModelIndex &index) {
201 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
203 if(bufferType != BufferInfo::ChannelBuffer)
206 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
208 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
211 void BufferView::keyPressEvent(QKeyEvent *event) {
212 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
214 removeSelectedBuffers();
216 QTreeView::keyPressEvent(event);
219 void BufferView::dropEvent(QDropEvent *event) {
220 QModelIndex index = indexAt(event->pos());
222 QRect indexRect = visualRect(index);
223 QPoint cursorPos = event->pos();
225 // check if we're really _on_ the item and not indicating a move to just above or below the item
226 const int margin = 2;
227 if(cursorPos.y() - indexRect.top() < margin
228 || indexRect.bottom() - cursorPos.y() < margin)
229 return QTreeView::dropEvent(event);
231 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
232 if(bufferList.count() != 1)
233 return QTreeView::dropEvent(event);
235 NetworkId networkId = bufferList[0].first;
236 BufferId bufferId2 = bufferList[0].second;
238 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
239 return QTreeView::dropEvent(event);
241 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
242 return QTreeView::dropEvent(event);
244 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
245 return QTreeView::dropEvent(event);
247 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
248 if(bufferId1 == bufferId2)
249 return QTreeView::dropEvent(event);
251 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
252 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)),
253 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
254 if(res == QMessageBox::Yes) {
255 Client::mergeBuffersPermanently(bufferId1, bufferId2);
259 void BufferView::removeSelectedBuffers(bool permanently) {
264 QSet<BufferId> removedRows;
265 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
266 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
269 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
270 if(removedRows.contains(bufferId))
273 removedRows << bufferId;
276 foreach(BufferId bufferId, removedRows) {
278 config()->requestRemoveBufferPermanently(bufferId);
280 config()->requestRemoveBuffer(bufferId);
284 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
285 QTreeView::rowsInserted(parent, start, end);
287 // ensure that newly inserted network nodes are expanded per default
288 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
291 setExpandedState(parent);
294 void BufferView::on_layoutChanged() {
295 int numNets = model()->rowCount(QModelIndex());
296 for(int row = 0; row < numNets; row++) {
297 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
298 setExpandedState(networkIdx);
302 void BufferView::on_configChanged() {
305 // expand all active networks... collapse inactive ones... unless manually changed
306 QModelIndex networkIdx;
308 for(int row = 0; row < model()->rowCount(); row++) {
309 networkIdx = model()->index(row, 0);
310 if(model()->rowCount(networkIdx) == 0)
313 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
314 if(!networkId.isValid())
317 setExpandedState(networkIdx);
321 // update selection to current one
322 Client::bufferModel()->synchronizeView(this);
326 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
327 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
330 if(isExpanded(networkIdx))
331 oldState |= WasExpanded;
332 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
333 oldState |= WasActive;
335 _expandedState[networkId] = oldState;
338 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
339 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
342 if(model()->rowCount(networkIdx) == 0)
345 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
347 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
348 bool expandNetwork = networkActive;
349 if(_expandedState.contains(networkId)) {
350 int oldState = _expandedState[networkId];
351 if((bool)(oldState & WasActive) == networkActive)
352 expandNetwork = (bool)(oldState & WasExpanded);
355 if(expandNetwork != isExpanded(networkIdx)) {
357 setExpanded(networkIdx, expandNetwork);
359 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
362 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
363 QTreeView::dataChanged(topLeft, bottomRight);
365 // determine how many items have been changed and if any of them is a networkitem
366 // which just swichted from active to inactive or vice versa
367 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
370 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
371 QModelIndex networkIdx = topLeft.sibling(i, 0);
372 setExpandedState(networkIdx);
376 void BufferView::toggleHeader(bool checked) {
377 QAction *action = qobject_cast<QAction *>(sender());
378 header()->setSectionHidden((action->property("column")).toInt(), !checked);
381 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
382 QModelIndex index = indexAt(event->pos());
386 QMenu contextMenu(this);
388 if(index.isValid()) {
389 addActionsToMenu(&contextMenu, index);
392 addFilterActions(&contextMenu, index);
394 if(!contextMenu.actions().isEmpty())
395 contextMenu.exec(QCursor::pos());
398 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
399 QModelIndexList indexList = selectedIndexes();
400 // make sure the item we clicked on is first
401 indexList.removeAll(index);
402 indexList.prepend(index);
404 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
407 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
408 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
410 QList<QAction *> filterActions = filter->actions(index);
411 if(!filterActions.isEmpty()) {
412 contextMenu->addSeparator();
413 foreach(QAction *action, filterActions) {
414 contextMenu->addAction(action);
420 void BufferView::menuActionTriggered(QAction *result) {
421 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
423 case ContextMenuActionProvider::HideBufferTemporarily:
424 removeSelectedBuffers();
426 case ContextMenuActionProvider::HideBufferPermanently:
427 removeSelectedBuffers(true);
434 void BufferView::nextBuffer() {
435 changeBuffer(Forward);
438 void BufferView::previousBuffer() {
439 changeBuffer(Backward);
442 void BufferView::changeBuffer(Direction direction) {
443 QModelIndex currentIndex = selectionModel()->currentIndex();
444 QModelIndex resultingIndex;
446 if(currentIndex.parent().isValid()) {
447 //If we are a child node just switch among siblings unless it's the first/last child
448 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
450 if(!resultingIndex.isValid()) {
451 QModelIndex parent = currentIndex.parent();
452 if(direction == Backward)
453 resultingIndex = parent;
455 resultingIndex = parent.sibling(parent.row() + direction, 0);
458 //If we have a toplevel node, try and get an adjacent child
459 if(direction == Backward) {
460 QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
461 if(model()->hasChildren(newParent))
462 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
464 resultingIndex = newParent;
466 if(model()->hasChildren(currentIndex))
467 resultingIndex = currentIndex.child(0, 0);
469 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
473 if(!resultingIndex.isValid())
476 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
477 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
480 void BufferView::wheelEvent(QWheelEvent* event) {
481 if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
482 return QTreeView::wheelEvent(event);
484 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
485 changeBuffer((Direction)rowDelta);
488 void BufferView::hideCurrentBuffer() {
489 QModelIndex index = selectionModel()->currentIndex();
490 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
493 BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
495 //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.
496 changeBuffer(Backward);
498 /*if(removedRows.contains(bufferId))
501 removedRows << bufferId;*/
503 config()->requestRemoveBufferPermanently(bufferId);
505 config()->requestRemoveBuffer(bufferId);
508 QSize BufferView::sizeHint() const {
509 return QTreeView::sizeHint();
512 return QTreeView::sizeHint();
514 if(model()->rowCount() == 0)
515 return QSize(120, 50);
518 for(int i = 0; i < model()->columnCount(); i++) {
519 if(!isColumnHidden(i))
520 columnSize += sizeHintForColumn(i);
522 return QSize(columnSize, 50);
526 // ****************************************
528 // ****************************************
529 class ColorsChangedEvent : public QEvent {
531 ColorsChangedEvent() : QEvent(QEvent::User) {};
534 BufferViewDelegate::BufferViewDelegate(QObject *parent)
535 : QStyledItemDelegate(parent)
539 void BufferViewDelegate::customEvent(QEvent *event) {
540 if(event->type() != QEvent::User)
546 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
547 if(event->type() != QEvent::MouseButtonRelease)
548 return QStyledItemDelegate::editorEvent(event, model, option, index);
550 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
551 return QStyledItemDelegate::editorEvent(event, model, option, index);
553 QVariant value = index.data(Qt::CheckStateRole);
555 return QStyledItemDelegate::editorEvent(event, model, option, index);
557 QStyleOptionViewItemV4 viewOpt(option);
558 initStyleOption(&viewOpt, index);
560 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
561 QMouseEvent *me = static_cast<QMouseEvent*>(event);
563 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
564 return QStyledItemDelegate::editorEvent(event, model, option, index);
566 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
567 if(state == Qt::Unchecked)
568 state = Qt::PartiallyChecked;
569 else if(state == Qt::PartiallyChecked)
572 state = Qt::Unchecked;
573 model->setData(index, state, Qt::CheckStateRole);
577 // ==============================
579 // ==============================
580 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
581 : QDockWidget(parent),
583 _title(config->bufferViewName())
585 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
586 toggleViewAction()->setData(config->bufferViewId());
587 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
588 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
592 void BufferViewDock::updateTitle() {
593 QString title = _title;
595 title.prepend(QString::fromUtf8("• "));
596 setWindowTitle(title);
599 void BufferViewDock::setActive(bool active) {
600 if(active != isActive()) {
604 raise(); // for tabbed docks
608 void BufferViewDock::bufferViewRenamed(const QString &newName) {
611 toggleViewAction()->setText(newName);
614 int BufferViewDock::bufferViewId() const {
615 BufferView *view = bufferView();
620 return view->config()->bufferViewId();
625 BufferViewConfig *BufferViewDock::config() const {
626 BufferView *view = bufferView();
630 return view->config();