1 /***************************************************************************
2 * Copyright (C) 2005-08 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 "iconloader.h"
39 #include "mappedselectionmodel.h"
41 #include "networkmodel.h"
42 #include "networkmodelactionprovider.h"
43 #include "quasselui.h"
44 #include "uisettings.h"
46 bool TristateDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
47 if(event->type() != QEvent::MouseButtonRelease)
48 return QStyledItemDelegate::editorEvent(event, model, option, index);
50 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
51 return QStyledItemDelegate::editorEvent(event, model, option, index);
53 QVariant value = index.data(Qt::CheckStateRole);
55 return QStyledItemDelegate::editorEvent(event, model, option, index);
57 QStyleOptionViewItemV4 viewOpt(option);
58 initStyleOption(&viewOpt, index);
60 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
61 QMouseEvent *me = static_cast<QMouseEvent*>(event);
63 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
64 return QStyledItemDelegate::editorEvent(event, model, option, index);
66 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
67 if(state == Qt::Unchecked)
68 state = Qt::PartiallyChecked;
69 else if(state == Qt::PartiallyChecked)
72 state = Qt::Unchecked;
73 model->setData(index, state, Qt::CheckStateRole);
80 /*****************************************
81 * The TreeView showing the Buffers
82 *****************************************/
83 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
84 // to be on the safe side: call QTreeView's method aswell
85 BufferView::BufferView(QWidget *parent)
88 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(on_collapse(const QModelIndex &)));
89 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(on_expand(const QModelIndex &)));
91 setSelectionMode(QAbstractItemView::ExtendedSelection);
93 QAbstractItemDelegate *oldDelegate = itemDelegate();
94 TristateDelegate *tristateDelegate = new TristateDelegate(this);
95 setItemDelegate(tristateDelegate);
99 void BufferView::init() {
100 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
108 #ifndef QT_NO_DRAGANDDROP
109 setDragEnabled(true);
110 setAcceptDrops(true);
111 setDropIndicatorShown(true);
114 setSortingEnabled(true);
115 sortByColumn(0, Qt::AscendingOrder);
117 // activated() fails on X11 and Qtopia at least
118 #if defined Q_WS_QWS || defined Q_WS_X11
119 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
121 // afaik this is better on Mac and Windows
122 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
126 void BufferView::setModel(QAbstractItemModel *model) {
127 delete selectionModel();
129 QTreeView::setModel(model);
131 // remove old Actions
132 QList<QAction *> oldactions = header()->actions();
133 foreach(QAction *action, oldactions) {
134 header()->removeAction(action);
135 action->deleteLater();
142 QAction *showSection;
143 for(int i = 1; i < model->columnCount(); i++) {
144 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
145 showSection = new QAction(sectionName, header());
146 showSection->setCheckable(true);
147 showSection->setChecked(!isColumnHidden(i));
148 showSection->setProperty("column", i);
149 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
150 header()->addAction(showSection);
155 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
156 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
158 filter->setConfig(config);
164 disconnect(this, 0, model(), 0);
165 disconnect(model(), 0, this, 0);
171 BufferViewFilter *filter = new BufferViewFilter(model_, config);
173 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
178 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
179 if(QTreeView::selectionModel())
180 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
181 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
183 QTreeView::setSelectionModel(selectionModel);
184 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
186 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
187 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
191 void BufferView::setConfig(BufferViewConfig *config) {
192 if(_config == config)
196 disconnect(_config, 0, this, 0);
201 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
202 setRootIndexForNetworkId(config->networkId());
205 setRootIndex(QModelIndex());
209 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
210 if(!networkId.isValid() || !model()) {
212 setRootIndex(QModelIndex());
215 int networkCount = model()->rowCount();
217 for(int i = 0; i < networkCount; i++) {
218 child = model()->index(i, 0);
219 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
225 void BufferView::joinChannel(const QModelIndex &index) {
226 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
228 if(bufferType != BufferInfo::ChannelBuffer)
231 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
233 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
236 void BufferView::keyPressEvent(QKeyEvent *event) {
237 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
239 removeSelectedBuffers();
241 QTreeView::keyPressEvent(event);
244 void BufferView::dropEvent(QDropEvent *event) {
245 QModelIndex index = indexAt(event->pos());
247 QRect indexRect = visualRect(index);
248 QPoint cursorPos = event->pos();
250 // check if we're really _on_ the item and not indicating a move to just above or below the item
251 const int margin = 2;
252 if(cursorPos.y() - indexRect.top() < margin
253 || indexRect.bottom() - cursorPos.y() < margin)
254 return QTreeView::dropEvent(event);
256 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
257 if(bufferList.count() != 1)
258 return QTreeView::dropEvent(event);
260 NetworkId networkId = bufferList[0].first;
261 BufferId bufferId2 = bufferList[0].second;
263 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
264 return QTreeView::dropEvent(event);
266 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
267 return QTreeView::dropEvent(event);
269 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
270 return QTreeView::dropEvent(event);
272 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
273 if(bufferId1 == bufferId2)
274 return QTreeView::dropEvent(event);
276 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
277 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)),
278 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
279 if(res == QMessageBox::Yes) {
280 Client::mergeBuffersPermanently(bufferId1, bufferId2);
284 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 config()->requestRemoveBufferPermanently(bufferId);
303 config()->requestRemoveBuffer(bufferId);
307 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
308 QTreeView::rowsInserted(parent, start, end);
310 // ensure that newly inserted network nodes are expanded per default
311 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
314 if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
315 // without updating the parent the expand will have no effect... Qt Bug?
321 void BufferView::on_configChanged() {
324 // expand all active networks... collapse inactive ones... unless manually changed
325 QModelIndex networkIdx;
327 for(int row = 0; row < model()->rowCount(); row++) {
328 networkIdx = model()->index(row, 0);
329 if(model()->rowCount(networkIdx) == 0)
332 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
333 if(!networkId.isValid())
338 bool expandNetwork = false;
339 if(_expandedState.contains(networkId))
340 expandNetwork = _expandedState[networkId];
342 expandNetwork = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
347 collapse(networkIdx);
350 // update selection to current one
351 MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
352 if(!config() || !mappedSelectionModel)
355 mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
356 mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
359 void BufferView::on_collapse(const QModelIndex &index) {
360 storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), false);
363 void BufferView::on_expand(const QModelIndex &index) {
364 storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), true);
367 void BufferView::storeExpandedState(NetworkId networkId, bool expanded) {
368 _expandedState[networkId] = expanded;
371 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
372 QTreeView::dataChanged(topLeft, bottomRight);
374 // determine how many items have been changed and if any of them is a networkitem
375 // which just swichted from active to inactive or vice versa
376 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
379 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
380 QModelIndex networkIdx = topLeft.sibling(i, 0);
381 if(model()->rowCount(networkIdx) == 0)
384 bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
386 if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
388 if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
393 void BufferView::toggleHeader(bool checked) {
394 QAction *action = qobject_cast<QAction *>(sender());
395 header()->setSectionHidden((action->property("column")).toInt(), !checked);
398 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
399 QModelIndex index = indexAt(event->pos());
403 QMenu contextMenu(this);
405 if(index.isValid()) {
406 addActionsToMenu(&contextMenu, index);
409 addFilterActions(&contextMenu, index);
411 if(!contextMenu.actions().isEmpty())
412 contextMenu.exec(QCursor::pos());
415 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
416 Client::mainUi()->actionProvider()->addActions(contextMenu, index, this, "menuActionTriggered", (bool)config());
419 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
420 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
422 QList<QAction *> filterActions = filter->actions(index);
423 if(!filterActions.isEmpty()) {
424 contextMenu->addSeparator();
425 foreach(QAction *action, filterActions) {
426 contextMenu->addAction(action);
432 void BufferView::menuActionTriggered(QAction *result) {
433 NetworkModelActionProvider::ActionType type = (NetworkModelActionProvider::ActionType)result->data().toInt();
435 case NetworkModelActionProvider::HideBufferTemporarily:
436 removeSelectedBuffers();
438 case NetworkModelActionProvider::HideBufferPermanently:
439 removeSelectedBuffers(true);
446 void BufferView::wheelEvent(QWheelEvent* event) {
447 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
448 return QTreeView::wheelEvent(event);
450 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
451 QModelIndex currentIndex = selectionModel()->currentIndex();
452 QModelIndex resultingIndex;
453 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
455 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
457 else //if we scroll into a the parent node...
459 QModelIndex parent = currentIndex.parent();
460 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
462 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
464 resultingIndex = aunt.child( 0, 0 );
465 if( !resultingIndex.isValid() )
468 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
469 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
473 QSize BufferView::sizeHint() const {
474 return QTreeView::sizeHint();
477 return QTreeView::sizeHint();
479 if(model()->rowCount() == 0)
480 return QSize(120, 50);
483 for(int i = 0; i < model()->columnCount(); i++) {
484 if(!isColumnHidden(i))
485 columnSize += sizeHintForColumn(i);
487 return QSize(columnSize, 50);
490 // ==============================
492 // ==============================
493 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
494 : QDockWidget(config->bufferViewName(), parent)
496 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
497 toggleViewAction()->setData(config->bufferViewId());
498 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
499 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
502 BufferViewDock::BufferViewDock(QWidget *parent)
503 : QDockWidget(tr("All Buffers"), parent)
505 setObjectName("BufferViewDock--1");
506 toggleViewAction()->setData((int)-1);
507 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
510 void BufferViewDock::bufferViewRenamed(const QString &newName) {
511 setWindowTitle(newName);
512 toggleViewAction()->setText(newName);