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"
40 #include "iconloader.h"
42 #include "networkmodel.h"
43 #include "contextmenuactionprovider.h"
44 #include "uisettings.h"
46 /*****************************************
47 * The TreeView showing the Buffers
48 *****************************************/
49 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
50 // to be on the safe side: call QTreeView's method aswell
51 BufferView::BufferView(QWidget *parent)
54 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
55 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
57 setSelectionMode(QAbstractItemView::ExtendedSelection);
59 QAbstractItemDelegate *oldDelegate = itemDelegate();
60 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
61 setItemDelegate(tristateDelegate);
64 UiStyleSettings s("QtUiStyle/Fonts"); // li'l dirty here, but fonts are stored in QtUiStyle :/
65 s.notify("BufferView", this, SLOT(setCustomFont(QVariant)));
66 setCustomFont(s.value("BufferView", QFont()));
69 void BufferView::init() {
70 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
78 // FIXME This is to workaround bug #663
79 setUniformRowHeights(true);
81 #ifndef QT_NO_DRAGANDDROP
84 setDropIndicatorShown(true);
87 setSortingEnabled(true);
88 sortByColumn(0, Qt::AscendingOrder);
90 // activated() fails on X11 and Qtopia at least
91 #if defined Q_WS_QWS || defined Q_WS_X11
92 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
93 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
95 // afaik this is better on Mac and Windows
96 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
97 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
101 void BufferView::setModel(QAbstractItemModel *model) {
102 delete selectionModel();
104 QTreeView::setModel(model);
106 // remove old Actions
107 QList<QAction *> oldactions = header()->actions();
108 foreach(QAction *action, oldactions) {
109 header()->removeAction(action);
110 action->deleteLater();
117 QAction *showSection;
118 for(int i = 1; i < model->columnCount(); i++) {
119 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
120 showSection = new QAction(sectionName, header());
121 showSection->setCheckable(true);
122 showSection->setChecked(!isColumnHidden(i));
123 showSection->setProperty("column", i);
124 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
125 header()->addAction(showSection);
128 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
131 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
132 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
134 filter->setConfig(config);
140 disconnect(this, 0, model(), 0);
141 disconnect(model(), 0, this, 0);
147 BufferViewFilter *filter = new BufferViewFilter(model_, config);
149 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
154 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
155 if(QTreeView::selectionModel())
156 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
157 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
159 QTreeView::setSelectionModel(selectionModel);
160 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
162 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
163 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
167 void BufferView::setConfig(BufferViewConfig *config) {
168 if(_config == config)
172 disconnect(_config, 0, this, 0);
177 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
178 setRootIndexForNetworkId(config->networkId());
181 setRootIndex(QModelIndex());
185 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
186 if(!networkId.isValid() || !model()) {
188 setRootIndex(QModelIndex());
191 int networkCount = model()->rowCount();
193 for(int i = 0; i < networkCount; i++) {
194 child = model()->index(i, 0);
195 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
201 void BufferView::setCustomFont(const QVariant &v) {
202 QFont font = v.value<QFont>();
203 if(font.family().isEmpty())
204 font = QApplication::font();
208 void BufferView::joinChannel(const QModelIndex &index) {
209 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
211 if(bufferType != BufferInfo::ChannelBuffer)
214 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
216 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
219 void BufferView::keyPressEvent(QKeyEvent *event) {
220 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
222 removeSelectedBuffers();
224 QTreeView::keyPressEvent(event);
227 void BufferView::dropEvent(QDropEvent *event) {
228 QModelIndex index = indexAt(event->pos());
230 QRect indexRect = visualRect(index);
231 QPoint cursorPos = event->pos();
233 // check if we're really _on_ the item and not indicating a move to just above or below the item
234 const int margin = 2;
235 if(cursorPos.y() - indexRect.top() < margin
236 || indexRect.bottom() - cursorPos.y() < margin)
237 return QTreeView::dropEvent(event);
239 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
240 if(bufferList.count() != 1)
241 return QTreeView::dropEvent(event);
243 NetworkId networkId = bufferList[0].first;
244 BufferId bufferId2 = bufferList[0].second;
246 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
247 return QTreeView::dropEvent(event);
249 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
250 return QTreeView::dropEvent(event);
252 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
253 return QTreeView::dropEvent(event);
255 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
256 if(bufferId1 == bufferId2)
257 return QTreeView::dropEvent(event);
259 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
260 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)),
261 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
262 if(res == QMessageBox::Yes) {
263 Client::mergeBuffersPermanently(bufferId1, bufferId2);
267 void BufferView::removeSelectedBuffers(bool permanently) {
272 QSet<BufferId> removedRows;
273 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
274 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
277 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
278 if(removedRows.contains(bufferId))
281 removedRows << bufferId;
284 foreach(BufferId bufferId, removedRows) {
286 config()->requestRemoveBufferPermanently(bufferId);
288 config()->requestRemoveBuffer(bufferId);
292 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
293 QTreeView::rowsInserted(parent, start, end);
295 // ensure that newly inserted network nodes are expanded per default
296 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
299 setExpandedState(parent);
302 void BufferView::on_layoutChanged() {
303 int numNets = model()->rowCount(QModelIndex());
304 for(int row = 0; row < numNets; row++) {
305 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
306 setExpandedState(networkIdx);
310 void BufferView::on_configChanged() {
313 // expand all active networks... collapse inactive ones... unless manually changed
314 QModelIndex networkIdx;
316 for(int row = 0; row < model()->rowCount(); row++) {
317 networkIdx = model()->index(row, 0);
318 if(model()->rowCount(networkIdx) == 0)
321 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
322 if(!networkId.isValid())
325 setExpandedState(networkIdx);
329 // update selection to current one
330 Client::bufferModel()->synchronizeView(this);
334 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
335 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
338 if(isExpanded(networkIdx))
339 oldState |= WasExpanded;
340 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
341 oldState |= WasActive;
343 _expandedState[networkId] = oldState;
346 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
347 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
350 if(model()->rowCount(networkIdx) == 0)
353 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
355 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
356 bool expandNetwork = networkActive;
357 if(_expandedState.contains(networkId)) {
358 int oldState = _expandedState[networkId];
359 if((bool)(oldState & WasActive) == networkActive)
360 expandNetwork = (bool)(oldState & WasExpanded);
363 if(expandNetwork != isExpanded(networkIdx)) {
365 setExpanded(networkIdx, expandNetwork);
367 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
370 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
371 QTreeView::dataChanged(topLeft, bottomRight);
373 // determine how many items have been changed and if any of them is a networkitem
374 // which just swichted from active to inactive or vice versa
375 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
378 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
379 QModelIndex networkIdx = topLeft.sibling(i, 0);
380 setExpandedState(networkIdx);
384 void BufferView::toggleHeader(bool checked) {
385 QAction *action = qobject_cast<QAction *>(sender());
386 header()->setSectionHidden((action->property("column")).toInt(), !checked);
389 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
390 QModelIndex index = indexAt(event->pos());
394 QMenu contextMenu(this);
396 if(index.isValid()) {
397 addActionsToMenu(&contextMenu, index);
400 addFilterActions(&contextMenu, index);
402 if(!contextMenu.actions().isEmpty())
403 contextMenu.exec(QCursor::pos());
406 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
407 QModelIndexList indexList = selectedIndexes();
408 // make sure the item we clicked on is first
409 indexList.removeAll(index);
410 indexList.prepend(index);
412 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
415 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
416 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
418 QList<QAction *> filterActions = filter->actions(index);
419 if(!filterActions.isEmpty()) {
420 contextMenu->addSeparator();
421 foreach(QAction *action, filterActions) {
422 contextMenu->addAction(action);
428 void BufferView::menuActionTriggered(QAction *result) {
429 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
431 case ContextMenuActionProvider::HideBufferTemporarily:
432 removeSelectedBuffers();
434 case ContextMenuActionProvider::HideBufferPermanently:
435 removeSelectedBuffers(true);
442 void BufferView::wheelEvent(QWheelEvent* event) {
443 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
444 return QTreeView::wheelEvent(event);
446 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
447 QModelIndex currentIndex = selectionModel()->currentIndex();
448 QModelIndex resultingIndex;
449 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
451 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
453 else //if we scroll into a the parent node...
455 QModelIndex parent = currentIndex.parent();
456 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
458 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
460 resultingIndex = aunt.child( 0, 0 );
461 if( !resultingIndex.isValid() )
464 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
465 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
469 QSize BufferView::sizeHint() const {
470 return QTreeView::sizeHint();
473 return QTreeView::sizeHint();
475 if(model()->rowCount() == 0)
476 return QSize(120, 50);
479 for(int i = 0; i < model()->columnCount(); i++) {
480 if(!isColumnHidden(i))
481 columnSize += sizeHintForColumn(i);
483 return QSize(columnSize, 50);
487 // ****************************************
489 // ****************************************
490 class ColorsChangedEvent : public QEvent {
492 ColorsChangedEvent() : QEvent(QEvent::User) {};
495 BufferViewDelegate::BufferViewDelegate(QObject *parent)
496 : QStyledItemDelegate(parent),
501 UiSettings s("QtUiStyle/Colors");
502 s.notify("inactiveActivityFG", this, SLOT(colorsChanged()));
503 s.notify("noActivityFG", this, SLOT(colorsChanged()));
504 s.notify("highlightActivityFG", this, SLOT(colorsChanged()));
505 s.notify("newMessageActivityFG", this, SLOT(colorsChanged()));
506 s.notify("otherActivityFG", this, SLOT(colorsChanged()));
509 void BufferViewDelegate::colorsChanged() {
510 // avoid mutliple unneded reloads of all colors
513 _updateColors = true;
514 QCoreApplication::postEvent(this, new ColorsChangedEvent());
517 void BufferViewDelegate::customEvent(QEvent *event) {
518 if(event->type() != QEvent::User)
522 _updateColors = false;
527 void BufferViewDelegate::loadColors() {
528 UiSettings s("QtUiStyle/Colors");
529 _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
530 _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
531 _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
532 _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
533 _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
536 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
537 if(event->type() != QEvent::MouseButtonRelease)
538 return QStyledItemDelegate::editorEvent(event, model, option, index);
540 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
541 return QStyledItemDelegate::editorEvent(event, model, option, index);
543 QVariant value = index.data(Qt::CheckStateRole);
545 return QStyledItemDelegate::editorEvent(event, model, option, index);
547 QStyleOptionViewItemV4 viewOpt(option);
548 initStyleOption(&viewOpt, index);
550 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
551 QMouseEvent *me = static_cast<QMouseEvent*>(event);
553 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
554 return QStyledItemDelegate::editorEvent(event, model, option, index);
556 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
557 if(state == Qt::Unchecked)
558 state = Qt::PartiallyChecked;
559 else if(state == Qt::PartiallyChecked)
562 state = Qt::Unchecked;
563 model->setData(index, state, Qt::CheckStateRole);
567 void BufferViewDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const {
568 QStyledItemDelegate::initStyleOption(option, index);
573 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
575 QColor fgColor = _FgColorNoActivity;
576 if(activity & BufferInfo::Highlight) {
577 fgColor = _FgColorHighlightActivity;
578 } else if(activity & BufferInfo::NewMessage) {
579 fgColor = _FgColorNewMessageActivity;
580 } else if(activity & BufferInfo::OtherActivity) {
581 fgColor = _FgColorOtherActivity;
582 } else if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool()) {
583 fgColor = _FgColorInactiveActivity;
586 option->palette.setColor(QPalette::Text, fgColor);
590 // ==============================
592 // ==============================
593 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
594 : QDockWidget(config->bufferViewName(), parent)
596 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
597 toggleViewAction()->setData(config->bufferViewId());
598 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
599 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
602 void BufferViewDock::bufferViewRenamed(const QString &newName) {
603 setWindowTitle(newName);
604 toggleViewAction()->setText(newName);