1 /***************************************************************************
2 * Copyright (C) 2005-09 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"
40 #include "networkmodel.h"
41 #include "networkmodelactionprovider.h"
42 #include "quasselui.h"
43 #include "uisettings.h"
45 bool TristateDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
46 if(event->type() != QEvent::MouseButtonRelease)
47 return QStyledItemDelegate::editorEvent(event, model, option, index);
49 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
50 return QStyledItemDelegate::editorEvent(event, model, option, index);
52 QVariant value = index.data(Qt::CheckStateRole);
54 return QStyledItemDelegate::editorEvent(event, model, option, index);
56 QStyleOptionViewItemV4 viewOpt(option);
57 initStyleOption(&viewOpt, index);
59 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
60 QMouseEvent *me = static_cast<QMouseEvent*>(event);
62 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
63 return QStyledItemDelegate::editorEvent(event, model, option, index);
65 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
66 if(state == Qt::Unchecked)
67 state = Qt::PartiallyChecked;
68 else if(state == Qt::PartiallyChecked)
71 state = Qt::Unchecked;
72 model->setData(index, state, Qt::CheckStateRole);
79 /*****************************************
80 * The TreeView showing the Buffers
81 *****************************************/
82 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
83 // to be on the safe side: call QTreeView's method aswell
84 BufferView::BufferView(QWidget *parent)
87 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
88 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
90 setSelectionMode(QAbstractItemView::ExtendedSelection);
92 QAbstractItemDelegate *oldDelegate = itemDelegate();
93 TristateDelegate *tristateDelegate = new TristateDelegate(this);
94 setItemDelegate(tristateDelegate);
98 void BufferView::init() {
99 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
107 #ifndef QT_NO_DRAGANDDROP
108 setDragEnabled(true);
109 setAcceptDrops(true);
110 setDropIndicatorShown(true);
113 setSortingEnabled(true);
114 sortByColumn(0, Qt::AscendingOrder);
116 // activated() fails on X11 and Qtopia at least
117 #if defined Q_WS_QWS || defined Q_WS_X11
118 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
120 // afaik this is better on Mac and Windows
121 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
125 void BufferView::setModel(QAbstractItemModel *model) {
126 delete selectionModel();
128 QTreeView::setModel(model);
130 // remove old Actions
131 QList<QAction *> oldactions = header()->actions();
132 foreach(QAction *action, oldactions) {
133 header()->removeAction(action);
134 action->deleteLater();
141 QAction *showSection;
142 for(int i = 1; i < model->columnCount(); i++) {
143 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
144 showSection = new QAction(sectionName, header());
145 showSection->setCheckable(true);
146 showSection->setChecked(!isColumnHidden(i));
147 showSection->setProperty("column", i);
148 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
149 header()->addAction(showSection);
154 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
155 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
157 filter->setConfig(config);
163 disconnect(this, 0, model(), 0);
164 disconnect(model(), 0, this, 0);
170 BufferViewFilter *filter = new BufferViewFilter(model_, config);
172 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
177 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
178 if(QTreeView::selectionModel())
179 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
180 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
182 QTreeView::setSelectionModel(selectionModel);
183 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
185 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
186 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
190 void BufferView::setConfig(BufferViewConfig *config) {
191 if(_config == config)
195 disconnect(_config, 0, this, 0);
200 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
201 setRootIndexForNetworkId(config->networkId());
204 setRootIndex(QModelIndex());
208 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
209 if(!networkId.isValid() || !model()) {
211 setRootIndex(QModelIndex());
214 int networkCount = model()->rowCount();
216 for(int i = 0; i < networkCount; i++) {
217 child = model()->index(i, 0);
218 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
224 void BufferView::joinChannel(const QModelIndex &index) {
225 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
227 if(bufferType != BufferInfo::ChannelBuffer)
230 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
232 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
235 void BufferView::keyPressEvent(QKeyEvent *event) {
236 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
238 removeSelectedBuffers();
240 QTreeView::keyPressEvent(event);
243 void BufferView::dropEvent(QDropEvent *event) {
244 QModelIndex index = indexAt(event->pos());
246 QRect indexRect = visualRect(index);
247 QPoint cursorPos = event->pos();
249 // check if we're really _on_ the item and not indicating a move to just above or below the item
250 const int margin = 2;
251 if(cursorPos.y() - indexRect.top() < margin
252 || indexRect.bottom() - cursorPos.y() < margin)
253 return QTreeView::dropEvent(event);
255 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
256 if(bufferList.count() != 1)
257 return QTreeView::dropEvent(event);
259 NetworkId networkId = bufferList[0].first;
260 BufferId bufferId2 = bufferList[0].second;
262 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
263 return QTreeView::dropEvent(event);
265 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
266 return QTreeView::dropEvent(event);
268 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
269 return QTreeView::dropEvent(event);
271 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
272 if(bufferId1 == bufferId2)
273 return QTreeView::dropEvent(event);
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);
283 void BufferView::removeSelectedBuffers(bool permanently) {
288 QSet<BufferId> removedRows;
289 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
290 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
293 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
294 if(removedRows.contains(bufferId))
297 removedRows << bufferId;
300 config()->requestRemoveBufferPermanently(bufferId);
302 config()->requestRemoveBuffer(bufferId);
306 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
307 QTreeView::rowsInserted(parent, start, end);
309 // ensure that newly inserted network nodes are expanded per default
310 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
313 if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
314 // without updating the parent the expand will have no effect... Qt Bug?
320 void BufferView::on_configChanged() {
323 // expand all active networks... collapse inactive ones... unless manually changed
324 QModelIndex networkIdx;
326 for(int row = 0; row < model()->rowCount(); row++) {
327 networkIdx = model()->index(row, 0);
328 if(model()->rowCount(networkIdx) == 0)
331 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
332 if(!networkId.isValid())
336 setExpandedState(networkIdx);
340 // update selection to current one
341 Client::bufferModel()->synchronizeView(this);
347 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
348 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
351 if(isExpanded(networkIdx))
352 oldState |= WasExpanded;
353 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
354 oldState |= WasActive;
356 _expandedState[networkId] = oldState;
359 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
360 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
363 if(model()->rowCount(networkIdx) == 0)
366 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
368 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
369 bool expandNetwork = networkActive;
370 if(_expandedState.contains(networkId)) {
371 int oldState = _expandedState[networkId];
372 if((bool)(oldState & WasActive) == networkActive)
373 expandNetwork = (bool)(oldState & WasExpanded);
376 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
377 if(expandNetwork != isExpanded(networkIdx))
378 setExpanded(networkIdx, expandNetwork);
381 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
382 QTreeView::dataChanged(topLeft, bottomRight);
384 // determine how many items have been changed and if any of them is a networkitem
385 // which just swichted from active to inactive or vice versa
386 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
389 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
390 QModelIndex networkIdx = topLeft.sibling(i, 0);
391 setExpandedState(networkIdx);
395 void BufferView::toggleHeader(bool checked) {
396 QAction *action = qobject_cast<QAction *>(sender());
397 header()->setSectionHidden((action->property("column")).toInt(), !checked);
400 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
401 QModelIndex index = indexAt(event->pos());
405 QMenu contextMenu(this);
407 if(index.isValid()) {
408 addActionsToMenu(&contextMenu, index);
411 addFilterActions(&contextMenu, index);
413 if(!contextMenu.actions().isEmpty())
414 contextMenu.exec(QCursor::pos());
417 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
418 QModelIndexList indexList = selectedIndexes();
419 // make sure the item we clicked on is first
420 indexList.removeAll(index);
421 indexList.prepend(index);
423 Client::mainUi()->actionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
426 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
427 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
429 QList<QAction *> filterActions = filter->actions(index);
430 if(!filterActions.isEmpty()) {
431 contextMenu->addSeparator();
432 foreach(QAction *action, filterActions) {
433 contextMenu->addAction(action);
439 void BufferView::menuActionTriggered(QAction *result) {
440 NetworkModelActionProvider::ActionType type = (NetworkModelActionProvider::ActionType)result->data().toInt();
442 case NetworkModelActionProvider::HideBufferTemporarily:
443 removeSelectedBuffers();
445 case NetworkModelActionProvider::HideBufferPermanently:
446 removeSelectedBuffers(true);
453 void BufferView::wheelEvent(QWheelEvent* event) {
454 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
455 return QTreeView::wheelEvent(event);
457 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
458 QModelIndex currentIndex = selectionModel()->currentIndex();
459 QModelIndex resultingIndex;
460 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
462 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
464 else //if we scroll into a the parent node...
466 QModelIndex parent = currentIndex.parent();
467 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
469 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
471 resultingIndex = aunt.child( 0, 0 );
472 if( !resultingIndex.isValid() )
475 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
476 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
480 QSize BufferView::sizeHint() const {
481 return QTreeView::sizeHint();
484 return QTreeView::sizeHint();
486 if(model()->rowCount() == 0)
487 return QSize(120, 50);
490 for(int i = 0; i < model()->columnCount(); i++) {
491 if(!isColumnHidden(i))
492 columnSize += sizeHintForColumn(i);
494 return QSize(columnSize, 50);
497 // ==============================
499 // ==============================
500 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
501 : QDockWidget(config->bufferViewName(), parent)
503 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
504 toggleViewAction()->setData(config->bufferViewId());
505 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
506 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
509 void BufferViewDock::bufferViewRenamed(const QString &newName) {
510 setWindowTitle(newName);
511 toggleViewAction()->setText(newName);