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"
43 #include "uisettings.h"
45 /*****************************************
46 * The TreeView showing the Buffers
47 *****************************************/
48 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
49 // to be on the safe side: call QTreeView's method aswell
50 BufferView::BufferView(QWidget *parent)
53 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
54 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
56 setSelectionMode(QAbstractItemView::ExtendedSelection);
58 QAbstractItemDelegate *oldDelegate = itemDelegate();
59 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
60 setItemDelegate(tristateDelegate);
63 UiStyleSettings s("QtUiStyle/Fonts"); // li'l dirty here, but fonts are stored in QtUiStyle :/
64 s.notify("BufferView", this, SLOT(setCustomFont(QVariant)));
65 setCustomFont(s.value("BufferView", QFont()));
68 void BufferView::init() {
69 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
77 #ifndef QT_NO_DRAGANDDROP
80 setDropIndicatorShown(true);
83 setSortingEnabled(true);
84 sortByColumn(0, Qt::AscendingOrder);
86 // activated() fails on X11 and Qtopia at least
87 #if defined Q_WS_QWS || defined Q_WS_X11
88 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
89 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
91 // afaik this is better on Mac and Windows
92 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
93 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
97 void BufferView::setModel(QAbstractItemModel *model) {
98 delete selectionModel();
100 QTreeView::setModel(model);
102 // remove old Actions
103 QList<QAction *> oldactions = header()->actions();
104 foreach(QAction *action, oldactions) {
105 header()->removeAction(action);
106 action->deleteLater();
113 QAction *showSection;
114 for(int i = 1; i < model->columnCount(); i++) {
115 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
116 showSection = new QAction(sectionName, header());
117 showSection->setCheckable(true);
118 showSection->setChecked(!isColumnHidden(i));
119 showSection->setProperty("column", i);
120 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
121 header()->addAction(showSection);
124 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
127 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
128 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
130 filter->setConfig(config);
136 disconnect(this, 0, model(), 0);
137 disconnect(model(), 0, this, 0);
143 BufferViewFilter *filter = new BufferViewFilter(model_, config);
145 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
150 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
151 if(QTreeView::selectionModel())
152 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
153 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
155 QTreeView::setSelectionModel(selectionModel);
156 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
158 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
159 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
163 void BufferView::setConfig(BufferViewConfig *config) {
164 if(_config == config)
168 disconnect(_config, 0, this, 0);
173 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
174 setRootIndexForNetworkId(config->networkId());
177 setRootIndex(QModelIndex());
181 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
182 if(!networkId.isValid() || !model()) {
184 setRootIndex(QModelIndex());
187 int networkCount = model()->rowCount();
189 for(int i = 0; i < networkCount; i++) {
190 child = model()->index(i, 0);
191 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
197 void BufferView::setCustomFont(const QVariant &v) {
198 QFont font = v.value<QFont>();
199 if(font.family().isEmpty())
200 font = QApplication::font();
204 void BufferView::joinChannel(const QModelIndex &index) {
205 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
207 if(bufferType != BufferInfo::ChannelBuffer)
210 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
212 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
215 void BufferView::keyPressEvent(QKeyEvent *event) {
216 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
218 removeSelectedBuffers();
220 QTreeView::keyPressEvent(event);
223 void BufferView::dropEvent(QDropEvent *event) {
224 QModelIndex index = indexAt(event->pos());
226 QRect indexRect = visualRect(index);
227 QPoint cursorPos = event->pos();
229 // check if we're really _on_ the item and not indicating a move to just above or below the item
230 const int margin = 2;
231 if(cursorPos.y() - indexRect.top() < margin
232 || indexRect.bottom() - cursorPos.y() < margin)
233 return QTreeView::dropEvent(event);
235 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
236 if(bufferList.count() != 1)
237 return QTreeView::dropEvent(event);
239 NetworkId networkId = bufferList[0].first;
240 BufferId bufferId2 = bufferList[0].second;
242 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
243 return QTreeView::dropEvent(event);
245 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
246 return QTreeView::dropEvent(event);
248 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
249 return QTreeView::dropEvent(event);
251 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
252 if(bufferId1 == bufferId2)
253 return QTreeView::dropEvent(event);
255 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
256 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)),
257 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
258 if(res == QMessageBox::Yes) {
259 Client::mergeBuffersPermanently(bufferId1, bufferId2);
263 void BufferView::removeSelectedBuffers(bool permanently) {
268 QSet<BufferId> removedRows;
269 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
270 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
273 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
274 if(removedRows.contains(bufferId))
277 removedRows << bufferId;
280 foreach(BufferId bufferId, removedRows) {
282 config()->requestRemoveBufferPermanently(bufferId);
284 config()->requestRemoveBuffer(bufferId);
288 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
289 QTreeView::rowsInserted(parent, start, end);
291 // ensure that newly inserted network nodes are expanded per default
292 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
295 setExpandedState(parent);
298 void BufferView::on_layoutChanged() {
299 int numNets = model()->rowCount(QModelIndex());
300 for(int row = 0; row < numNets; row++) {
301 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
302 setExpandedState(networkIdx);
306 void BufferView::on_configChanged() {
309 // expand all active networks... collapse inactive ones... unless manually changed
310 QModelIndex networkIdx;
312 for(int row = 0; row < model()->rowCount(); row++) {
313 networkIdx = model()->index(row, 0);
314 if(model()->rowCount(networkIdx) == 0)
317 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
318 if(!networkId.isValid())
321 setExpandedState(networkIdx);
325 // update selection to current one
326 Client::bufferModel()->synchronizeView(this);
330 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
331 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
334 if(isExpanded(networkIdx))
335 oldState |= WasExpanded;
336 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
337 oldState |= WasActive;
339 _expandedState[networkId] = oldState;
342 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
343 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
346 if(model()->rowCount(networkIdx) == 0)
349 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
351 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
352 bool expandNetwork = networkActive;
353 if(_expandedState.contains(networkId)) {
354 int oldState = _expandedState[networkId];
355 if((bool)(oldState & WasActive) == networkActive)
356 expandNetwork = (bool)(oldState & WasExpanded);
359 if(expandNetwork != isExpanded(networkIdx)) {
361 setExpanded(networkIdx, expandNetwork);
363 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
366 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
367 QTreeView::dataChanged(topLeft, bottomRight);
369 // determine how many items have been changed and if any of them is a networkitem
370 // which just swichted from active to inactive or vice versa
371 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
374 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
375 QModelIndex networkIdx = topLeft.sibling(i, 0);
376 setExpandedState(networkIdx);
380 void BufferView::toggleHeader(bool checked) {
381 QAction *action = qobject_cast<QAction *>(sender());
382 header()->setSectionHidden((action->property("column")).toInt(), !checked);
385 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
386 QModelIndex index = indexAt(event->pos());
390 QMenu contextMenu(this);
392 if(index.isValid()) {
393 addActionsToMenu(&contextMenu, index);
396 addFilterActions(&contextMenu, index);
398 if(!contextMenu.actions().isEmpty())
399 contextMenu.exec(QCursor::pos());
402 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
403 QModelIndexList indexList = selectedIndexes();
404 // make sure the item we clicked on is first
405 indexList.removeAll(index);
406 indexList.prepend(index);
408 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
411 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
412 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
414 QList<QAction *> filterActions = filter->actions(index);
415 if(!filterActions.isEmpty()) {
416 contextMenu->addSeparator();
417 foreach(QAction *action, filterActions) {
418 contextMenu->addAction(action);
424 void BufferView::menuActionTriggered(QAction *result) {
425 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
427 case ContextMenuActionProvider::HideBufferTemporarily:
428 removeSelectedBuffers();
430 case ContextMenuActionProvider::HideBufferPermanently:
431 removeSelectedBuffers(true);
438 void BufferView::wheelEvent(QWheelEvent* event) {
439 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
440 return QTreeView::wheelEvent(event);
442 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
443 QModelIndex currentIndex = selectionModel()->currentIndex();
444 QModelIndex resultingIndex;
445 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
447 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
449 else //if we scroll into a the parent node...
451 QModelIndex parent = currentIndex.parent();
452 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
454 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
456 resultingIndex = aunt.child( 0, 0 );
457 if( !resultingIndex.isValid() )
460 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
461 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
465 QSize BufferView::sizeHint() const {
466 return QTreeView::sizeHint();
469 return QTreeView::sizeHint();
471 if(model()->rowCount() == 0)
472 return QSize(120, 50);
475 for(int i = 0; i < model()->columnCount(); i++) {
476 if(!isColumnHidden(i))
477 columnSize += sizeHintForColumn(i);
479 return QSize(columnSize, 50);
483 // ****************************************
485 // ****************************************
486 class ColorsChangedEvent : public QEvent {
488 ColorsChangedEvent() : QEvent(QEvent::User) {};
491 BufferViewDelegate::BufferViewDelegate(QObject *parent)
492 : QStyledItemDelegate(parent)
496 void BufferViewDelegate::customEvent(QEvent *event) {
497 if(event->type() != QEvent::User)
503 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
504 if(event->type() != QEvent::MouseButtonRelease)
505 return QStyledItemDelegate::editorEvent(event, model, option, index);
507 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
508 return QStyledItemDelegate::editorEvent(event, model, option, index);
510 QVariant value = index.data(Qt::CheckStateRole);
512 return QStyledItemDelegate::editorEvent(event, model, option, index);
514 QStyleOptionViewItemV4 viewOpt(option);
515 initStyleOption(&viewOpt, index);
517 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
518 QMouseEvent *me = static_cast<QMouseEvent*>(event);
520 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
521 return QStyledItemDelegate::editorEvent(event, model, option, index);
523 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
524 if(state == Qt::Unchecked)
525 state = Qt::PartiallyChecked;
526 else if(state == Qt::PartiallyChecked)
529 state = Qt::Unchecked;
530 model->setData(index, state, Qt::CheckStateRole);
534 // ==============================
536 // ==============================
537 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
538 : QDockWidget(config->bufferViewName(), parent)
540 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
541 toggleViewAction()->setData(config->bufferViewId());
542 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
543 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
546 void BufferViewDock::bufferViewRenamed(const QString &newName) {
547 setWindowTitle(newName);
548 toggleViewAction()->setText(newName);
551 int BufferViewDock::bufferViewId() const {
552 BufferView *view = bufferView();
557 return view->config()->bufferViewId();
562 BufferViewConfig *BufferViewDock::config() const {
563 BufferView *view = bufferView();
567 return view->config();