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);
70 header()->hide(); // nobody seems to use this anyway
74 #ifndef QT_NO_DRAGANDDROP
77 setDropIndicatorShown(true);
80 setSortingEnabled(true);
81 sortByColumn(0, Qt::AscendingOrder);
83 // activated() fails on X11 and Qtopia at least
84 #if defined Q_WS_QWS || defined Q_WS_X11
85 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
86 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
88 // afaik this is better on Mac and Windows
89 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
90 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
94 void BufferView::setModel(QAbstractItemModel *model) {
95 delete selectionModel();
97 QTreeView::setModel(model);
100 QList<QAction *> oldactions = header()->actions();
101 foreach(QAction *action, oldactions) {
102 header()->removeAction(action);
103 action->deleteLater();
110 QAction *showSection;
111 for(int i = 1; i < model->columnCount(); i++) {
112 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
113 showSection = new QAction(sectionName, header());
114 showSection->setCheckable(true);
115 showSection->setChecked(!isColumnHidden(i));
116 showSection->setProperty("column", i);
117 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
118 header()->addAction(showSection);
121 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
124 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
125 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
127 filter->setConfig(config);
133 disconnect(this, 0, model(), 0);
134 disconnect(model(), 0, this, 0);
140 BufferViewFilter *filter = new BufferViewFilter(model_, config);
142 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
147 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
148 if(QTreeView::selectionModel())
149 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
150 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
152 QTreeView::setSelectionModel(selectionModel);
153 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
155 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
156 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
160 void BufferView::setConfig(BufferViewConfig *config) {
161 if(_config == config)
165 disconnect(_config, 0, this, 0);
170 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
171 setRootIndexForNetworkId(config->networkId());
174 setRootIndex(QModelIndex());
178 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
179 if(!networkId.isValid() || !model()) {
181 setRootIndex(QModelIndex());
184 int networkCount = model()->rowCount();
186 for(int i = 0; i < networkCount; i++) {
187 child = model()->index(i, 0);
188 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
194 void BufferView::joinChannel(const QModelIndex &index) {
195 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
197 if(bufferType != BufferInfo::ChannelBuffer)
200 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
202 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
205 void BufferView::keyPressEvent(QKeyEvent *event) {
206 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
208 removeSelectedBuffers();
210 QTreeView::keyPressEvent(event);
213 void BufferView::dropEvent(QDropEvent *event) {
214 QModelIndex index = indexAt(event->pos());
216 QRect indexRect = visualRect(index);
217 QPoint cursorPos = event->pos();
219 // check if we're really _on_ the item and not indicating a move to just above or below the item
220 const int margin = 2;
221 if(cursorPos.y() - indexRect.top() < margin
222 || indexRect.bottom() - cursorPos.y() < margin)
223 return QTreeView::dropEvent(event);
225 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
226 if(bufferList.count() != 1)
227 return QTreeView::dropEvent(event);
229 NetworkId networkId = bufferList[0].first;
230 BufferId bufferId2 = bufferList[0].second;
232 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
233 return QTreeView::dropEvent(event);
235 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
236 return QTreeView::dropEvent(event);
238 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
239 return QTreeView::dropEvent(event);
241 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
242 if(bufferId1 == bufferId2)
243 return QTreeView::dropEvent(event);
245 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
246 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)),
247 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
248 if(res == QMessageBox::Yes) {
249 Client::mergeBuffersPermanently(bufferId1, bufferId2);
253 void BufferView::removeSelectedBuffers(bool permanently) {
258 QSet<BufferId> removedRows;
259 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
260 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
263 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
264 if(removedRows.contains(bufferId))
267 removedRows << bufferId;
270 foreach(BufferId bufferId, removedRows) {
272 config()->requestRemoveBufferPermanently(bufferId);
274 config()->requestRemoveBuffer(bufferId);
278 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
279 QTreeView::rowsInserted(parent, start, end);
281 // ensure that newly inserted network nodes are expanded per default
282 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
285 setExpandedState(parent);
288 void BufferView::on_layoutChanged() {
289 int numNets = model()->rowCount(QModelIndex());
290 for(int row = 0; row < numNets; row++) {
291 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
292 setExpandedState(networkIdx);
296 void BufferView::on_configChanged() {
299 // expand all active networks... collapse inactive ones... unless manually changed
300 QModelIndex networkIdx;
302 for(int row = 0; row < model()->rowCount(); row++) {
303 networkIdx = model()->index(row, 0);
304 if(model()->rowCount(networkIdx) == 0)
307 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
308 if(!networkId.isValid())
311 setExpandedState(networkIdx);
315 // update selection to current one
316 Client::bufferModel()->synchronizeView(this);
320 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
321 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
324 if(isExpanded(networkIdx))
325 oldState |= WasExpanded;
326 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
327 oldState |= WasActive;
329 _expandedState[networkId] = oldState;
332 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
333 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
336 if(model()->rowCount(networkIdx) == 0)
339 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
341 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
342 bool expandNetwork = networkActive;
343 if(_expandedState.contains(networkId)) {
344 int oldState = _expandedState[networkId];
345 if((bool)(oldState & WasActive) == networkActive)
346 expandNetwork = (bool)(oldState & WasExpanded);
349 if(expandNetwork != isExpanded(networkIdx)) {
351 setExpanded(networkIdx, expandNetwork);
353 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
356 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
357 QTreeView::dataChanged(topLeft, bottomRight);
359 // determine how many items have been changed and if any of them is a networkitem
360 // which just swichted from active to inactive or vice versa
361 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
364 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
365 QModelIndex networkIdx = topLeft.sibling(i, 0);
366 setExpandedState(networkIdx);
370 void BufferView::toggleHeader(bool checked) {
371 QAction *action = qobject_cast<QAction *>(sender());
372 header()->setSectionHidden((action->property("column")).toInt(), !checked);
375 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
376 QModelIndex index = indexAt(event->pos());
380 QMenu contextMenu(this);
382 if(index.isValid()) {
383 addActionsToMenu(&contextMenu, index);
386 addFilterActions(&contextMenu, index);
388 if(!contextMenu.actions().isEmpty())
389 contextMenu.exec(QCursor::pos());
392 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
393 QModelIndexList indexList = selectedIndexes();
394 // make sure the item we clicked on is first
395 indexList.removeAll(index);
396 indexList.prepend(index);
398 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
401 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
402 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
404 QList<QAction *> filterActions = filter->actions(index);
405 if(!filterActions.isEmpty()) {
406 contextMenu->addSeparator();
407 foreach(QAction *action, filterActions) {
408 contextMenu->addAction(action);
414 void BufferView::menuActionTriggered(QAction *result) {
415 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
417 case ContextMenuActionProvider::HideBufferTemporarily:
418 removeSelectedBuffers();
420 case ContextMenuActionProvider::HideBufferPermanently:
421 removeSelectedBuffers(true);
428 void BufferView::wheelEvent(QWheelEvent* event) {
429 if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
430 return QTreeView::wheelEvent(event);
432 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
433 QModelIndex currentIndex = selectionModel()->currentIndex();
434 QModelIndex resultingIndex;
435 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
437 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
439 else //if we scroll into a the parent node...
441 QModelIndex parent = currentIndex.parent();
442 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
444 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
446 resultingIndex = aunt.child( 0, 0 );
447 if( !resultingIndex.isValid() )
450 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
451 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
455 QSize BufferView::sizeHint() const {
456 return QTreeView::sizeHint();
459 return QTreeView::sizeHint();
461 if(model()->rowCount() == 0)
462 return QSize(120, 50);
465 for(int i = 0; i < model()->columnCount(); i++) {
466 if(!isColumnHidden(i))
467 columnSize += sizeHintForColumn(i);
469 return QSize(columnSize, 50);
473 // ****************************************
475 // ****************************************
476 class ColorsChangedEvent : public QEvent {
478 ColorsChangedEvent() : QEvent(QEvent::User) {};
481 BufferViewDelegate::BufferViewDelegate(QObject *parent)
482 : QStyledItemDelegate(parent)
486 void BufferViewDelegate::customEvent(QEvent *event) {
487 if(event->type() != QEvent::User)
493 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
494 if(event->type() != QEvent::MouseButtonRelease)
495 return QStyledItemDelegate::editorEvent(event, model, option, index);
497 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
498 return QStyledItemDelegate::editorEvent(event, model, option, index);
500 QVariant value = index.data(Qt::CheckStateRole);
502 return QStyledItemDelegate::editorEvent(event, model, option, index);
504 QStyleOptionViewItemV4 viewOpt(option);
505 initStyleOption(&viewOpt, index);
507 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
508 QMouseEvent *me = static_cast<QMouseEvent*>(event);
510 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
511 return QStyledItemDelegate::editorEvent(event, model, option, index);
513 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
514 if(state == Qt::Unchecked)
515 state = Qt::PartiallyChecked;
516 else if(state == Qt::PartiallyChecked)
519 state = Qt::Unchecked;
520 model->setData(index, state, Qt::CheckStateRole);
524 // ==============================
526 // ==============================
527 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
528 : QDockWidget(config->bufferViewName(), parent)
530 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
531 toggleViewAction()->setData(config->bufferViewId());
532 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
533 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
536 void BufferViewDock::bufferViewRenamed(const QString &newName) {
537 setWindowTitle(newName);
538 toggleViewAction()->setText(newName);
541 int BufferViewDock::bufferViewId() const {
542 BufferView *view = bufferView();
547 return view->config()->bufferViewId();
552 BufferViewConfig *BufferViewDock::config() const {
553 BufferView *view = bufferView();
557 return view->config();