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 "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);
72 #ifndef QT_NO_DRAGANDDROP
75 setDropIndicatorShown(true);
78 setSortingEnabled(true);
79 sortByColumn(0, Qt::AscendingOrder);
81 // activated() fails on X11 and Qtopia at least
82 #if defined Q_WS_QWS || defined Q_WS_X11
83 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
84 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
86 // afaik this is better on Mac and Windows
87 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
88 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
92 void BufferView::setModel(QAbstractItemModel *model) {
93 delete selectionModel();
95 QTreeView::setModel(model);
98 QList<QAction *> oldactions = header()->actions();
99 foreach(QAction *action, oldactions) {
100 header()->removeAction(action);
101 action->deleteLater();
108 QAction *showSection;
109 for(int i = 1; i < model->columnCount(); i++) {
110 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
111 showSection = new QAction(sectionName, header());
112 showSection->setCheckable(true);
113 showSection->setChecked(!isColumnHidden(i));
114 showSection->setProperty("column", i);
115 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
116 header()->addAction(showSection);
119 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
122 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
123 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
125 filter->setConfig(config);
131 disconnect(this, 0, model(), 0);
132 disconnect(model(), 0, this, 0);
138 BufferViewFilter *filter = new BufferViewFilter(model_, config);
140 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
145 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
146 if(QTreeView::selectionModel())
147 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
148 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
150 QTreeView::setSelectionModel(selectionModel);
151 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
153 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
154 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
158 void BufferView::setConfig(BufferViewConfig *config) {
159 if(_config == config)
163 disconnect(_config, 0, this, 0);
168 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
169 setRootIndexForNetworkId(config->networkId());
172 setRootIndex(QModelIndex());
176 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
177 if(!networkId.isValid() || !model()) {
179 setRootIndex(QModelIndex());
182 int networkCount = model()->rowCount();
184 for(int i = 0; i < networkCount; i++) {
185 child = model()->index(i, 0);
186 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
192 void BufferView::joinChannel(const QModelIndex &index) {
193 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
195 if(bufferType != BufferInfo::ChannelBuffer)
198 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
200 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
203 void BufferView::keyPressEvent(QKeyEvent *event) {
204 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
206 removeSelectedBuffers();
208 QTreeView::keyPressEvent(event);
211 void BufferView::dropEvent(QDropEvent *event) {
212 QModelIndex index = indexAt(event->pos());
214 QRect indexRect = visualRect(index);
215 QPoint cursorPos = event->pos();
217 // check if we're really _on_ the item and not indicating a move to just above or below the item
218 const int margin = 2;
219 if(cursorPos.y() - indexRect.top() < margin
220 || indexRect.bottom() - cursorPos.y() < margin)
221 return QTreeView::dropEvent(event);
223 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
224 if(bufferList.count() != 1)
225 return QTreeView::dropEvent(event);
227 NetworkId networkId = bufferList[0].first;
228 BufferId bufferId2 = bufferList[0].second;
230 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
231 return QTreeView::dropEvent(event);
233 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
234 return QTreeView::dropEvent(event);
236 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
237 return QTreeView::dropEvent(event);
239 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
240 if(bufferId1 == bufferId2)
241 return QTreeView::dropEvent(event);
243 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
244 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)),
245 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
246 if(res == QMessageBox::Yes) {
247 Client::mergeBuffersPermanently(bufferId1, bufferId2);
251 void BufferView::removeSelectedBuffers(bool permanently) {
256 QSet<BufferId> removedRows;
257 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
258 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
261 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
262 if(removedRows.contains(bufferId))
265 removedRows << bufferId;
268 foreach(BufferId bufferId, removedRows) {
270 config()->requestRemoveBufferPermanently(bufferId);
272 config()->requestRemoveBuffer(bufferId);
276 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
277 QTreeView::rowsInserted(parent, start, end);
279 // ensure that newly inserted network nodes are expanded per default
280 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
283 setExpandedState(parent);
286 void BufferView::on_layoutChanged() {
287 int numNets = model()->rowCount(QModelIndex());
288 for(int row = 0; row < numNets; row++) {
289 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
290 setExpandedState(networkIdx);
294 void BufferView::on_configChanged() {
297 // expand all active networks... collapse inactive ones... unless manually changed
298 QModelIndex networkIdx;
300 for(int row = 0; row < model()->rowCount(); row++) {
301 networkIdx = model()->index(row, 0);
302 if(model()->rowCount(networkIdx) == 0)
305 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
306 if(!networkId.isValid())
309 setExpandedState(networkIdx);
313 // update selection to current one
314 Client::bufferModel()->synchronizeView(this);
318 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
319 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
322 if(isExpanded(networkIdx))
323 oldState |= WasExpanded;
324 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
325 oldState |= WasActive;
327 _expandedState[networkId] = oldState;
330 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
331 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
334 if(model()->rowCount(networkIdx) == 0)
337 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
339 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
340 bool expandNetwork = networkActive;
341 if(_expandedState.contains(networkId)) {
342 int oldState = _expandedState[networkId];
343 if((bool)(oldState & WasActive) == networkActive)
344 expandNetwork = (bool)(oldState & WasExpanded);
347 if(expandNetwork != isExpanded(networkIdx)) {
349 setExpanded(networkIdx, expandNetwork);
351 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
354 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
355 QTreeView::dataChanged(topLeft, bottomRight);
357 // determine how many items have been changed and if any of them is a networkitem
358 // which just swichted from active to inactive or vice versa
359 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
362 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
363 QModelIndex networkIdx = topLeft.sibling(i, 0);
364 setExpandedState(networkIdx);
368 void BufferView::toggleHeader(bool checked) {
369 QAction *action = qobject_cast<QAction *>(sender());
370 header()->setSectionHidden((action->property("column")).toInt(), !checked);
373 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
374 QModelIndex index = indexAt(event->pos());
378 QMenu contextMenu(this);
380 if(index.isValid()) {
381 addActionsToMenu(&contextMenu, index);
384 addFilterActions(&contextMenu, index);
386 if(!contextMenu.actions().isEmpty())
387 contextMenu.exec(QCursor::pos());
390 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
391 QModelIndexList indexList = selectedIndexes();
392 // make sure the item we clicked on is first
393 indexList.removeAll(index);
394 indexList.prepend(index);
396 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
399 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
400 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
402 QList<QAction *> filterActions = filter->actions(index);
403 if(!filterActions.isEmpty()) {
404 contextMenu->addSeparator();
405 foreach(QAction *action, filterActions) {
406 contextMenu->addAction(action);
412 void BufferView::menuActionTriggered(QAction *result) {
413 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
415 case ContextMenuActionProvider::HideBufferTemporarily:
416 removeSelectedBuffers();
418 case ContextMenuActionProvider::HideBufferPermanently:
419 removeSelectedBuffers(true);
426 void BufferView::wheelEvent(QWheelEvent* event) {
427 if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
428 return QTreeView::wheelEvent(event);
430 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
431 QModelIndex currentIndex = selectionModel()->currentIndex();
432 QModelIndex resultingIndex;
433 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
435 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
437 else //if we scroll into a the parent node...
439 QModelIndex parent = currentIndex.parent();
440 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
442 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
444 resultingIndex = aunt.child( 0, 0 );
445 if( !resultingIndex.isValid() )
448 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
449 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
453 QSize BufferView::sizeHint() const {
454 return QTreeView::sizeHint();
457 return QTreeView::sizeHint();
459 if(model()->rowCount() == 0)
460 return QSize(120, 50);
463 for(int i = 0; i < model()->columnCount(); i++) {
464 if(!isColumnHidden(i))
465 columnSize += sizeHintForColumn(i);
467 return QSize(columnSize, 50);
471 // ****************************************
473 // ****************************************
474 class ColorsChangedEvent : public QEvent {
476 ColorsChangedEvent() : QEvent(QEvent::User) {};
479 BufferViewDelegate::BufferViewDelegate(QObject *parent)
480 : QStyledItemDelegate(parent)
484 void BufferViewDelegate::customEvent(QEvent *event) {
485 if(event->type() != QEvent::User)
491 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
492 if(event->type() != QEvent::MouseButtonRelease)
493 return QStyledItemDelegate::editorEvent(event, model, option, index);
495 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
496 return QStyledItemDelegate::editorEvent(event, model, option, index);
498 QVariant value = index.data(Qt::CheckStateRole);
500 return QStyledItemDelegate::editorEvent(event, model, option, index);
502 QStyleOptionViewItemV4 viewOpt(option);
503 initStyleOption(&viewOpt, index);
505 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
506 QMouseEvent *me = static_cast<QMouseEvent*>(event);
508 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
509 return QStyledItemDelegate::editorEvent(event, model, option, index);
511 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
512 if(state == Qt::Unchecked)
513 state = Qt::PartiallyChecked;
514 else if(state == Qt::PartiallyChecked)
517 state = Qt::Unchecked;
518 model->setData(index, state, Qt::CheckStateRole);
522 // ==============================
524 // ==============================
525 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
526 : QDockWidget(config->bufferViewName(), parent)
528 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
529 toggleViewAction()->setData(config->bufferViewId());
530 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
531 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
534 void BufferViewDock::bufferViewRenamed(const QString &newName) {
535 setWindowTitle(newName);
536 toggleViewAction()->setText(newName);
539 int BufferViewDock::bufferViewId() const {
540 BufferView *view = bufferView();
545 return view->config()->bufferViewId();
550 BufferViewConfig *BufferViewDock::config() const {
551 BufferView *view = bufferView();
555 return view->config();