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 #ifndef QT_NO_DRAGANDDROP
81 setDropIndicatorShown(true);
84 setSortingEnabled(true);
85 sortByColumn(0, Qt::AscendingOrder);
87 // activated() fails on X11 and Qtopia at least
88 #if defined Q_WS_QWS || defined Q_WS_X11
89 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
91 // afaik this is better on Mac and Windows
92 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
96 void BufferView::setModel(QAbstractItemModel *model) {
97 delete selectionModel();
99 QTreeView::setModel(model);
101 // remove old Actions
102 QList<QAction *> oldactions = header()->actions();
103 foreach(QAction *action, oldactions) {
104 header()->removeAction(action);
105 action->deleteLater();
112 QAction *showSection;
113 for(int i = 1; i < model->columnCount(); i++) {
114 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
115 showSection = new QAction(sectionName, header());
116 showSection->setCheckable(true);
117 showSection->setChecked(!isColumnHidden(i));
118 showSection->setProperty("column", i);
119 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
120 header()->addAction(showSection);
125 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
126 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
128 filter->setConfig(config);
134 disconnect(this, 0, model(), 0);
135 disconnect(model(), 0, this, 0);
141 BufferViewFilter *filter = new BufferViewFilter(model_, config);
143 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
148 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
149 if(QTreeView::selectionModel())
150 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
151 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
153 QTreeView::setSelectionModel(selectionModel);
154 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
156 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
157 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
161 void BufferView::setConfig(BufferViewConfig *config) {
162 if(_config == config)
166 disconnect(_config, 0, this, 0);
171 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
172 setRootIndexForNetworkId(config->networkId());
175 setRootIndex(QModelIndex());
179 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
180 if(!networkId.isValid() || !model()) {
182 setRootIndex(QModelIndex());
185 int networkCount = model()->rowCount();
187 for(int i = 0; i < networkCount; i++) {
188 child = model()->index(i, 0);
189 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
195 void BufferView::setCustomFont(const QVariant &v) {
196 QFont font = v.value<QFont>();
197 if(font.family().isEmpty())
198 font = QApplication::font();
202 void BufferView::joinChannel(const QModelIndex &index) {
203 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
205 if(bufferType != BufferInfo::ChannelBuffer)
208 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
210 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
213 void BufferView::keyPressEvent(QKeyEvent *event) {
214 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
216 removeSelectedBuffers();
218 QTreeView::keyPressEvent(event);
221 void BufferView::dropEvent(QDropEvent *event) {
222 QModelIndex index = indexAt(event->pos());
224 QRect indexRect = visualRect(index);
225 QPoint cursorPos = event->pos();
227 // check if we're really _on_ the item and not indicating a move to just above or below the item
228 const int margin = 2;
229 if(cursorPos.y() - indexRect.top() < margin
230 || indexRect.bottom() - cursorPos.y() < margin)
231 return QTreeView::dropEvent(event);
233 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
234 if(bufferList.count() != 1)
235 return QTreeView::dropEvent(event);
237 NetworkId networkId = bufferList[0].first;
238 BufferId bufferId2 = bufferList[0].second;
240 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
241 return QTreeView::dropEvent(event);
243 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
244 return QTreeView::dropEvent(event);
246 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
247 return QTreeView::dropEvent(event);
249 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
250 if(bufferId1 == bufferId2)
251 return QTreeView::dropEvent(event);
253 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
254 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)),
255 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
256 if(res == QMessageBox::Yes) {
257 Client::mergeBuffersPermanently(bufferId1, bufferId2);
261 void BufferView::removeSelectedBuffers(bool permanently) {
266 QSet<BufferId> removedRows;
267 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
268 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
271 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
272 if(removedRows.contains(bufferId))
275 removedRows << bufferId;
278 config()->requestRemoveBufferPermanently(bufferId);
280 config()->requestRemoveBuffer(bufferId);
284 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
285 QTreeView::rowsInserted(parent, start, end);
287 // ensure that newly inserted network nodes are expanded per default
288 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
291 if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
292 // without updating the parent the expand will have no effect... Qt Bug?
298 void BufferView::on_configChanged() {
301 // expand all active networks... collapse inactive ones... unless manually changed
302 QModelIndex networkIdx;
304 for(int row = 0; row < model()->rowCount(); row++) {
305 networkIdx = model()->index(row, 0);
306 if(model()->rowCount(networkIdx) == 0)
309 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
310 if(!networkId.isValid())
314 setExpandedState(networkIdx);
318 // update selection to current one
319 Client::bufferModel()->synchronizeView(this);
325 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
326 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
329 if(isExpanded(networkIdx))
330 oldState |= WasExpanded;
331 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
332 oldState |= WasActive;
334 _expandedState[networkId] = oldState;
337 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
338 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
341 if(model()->rowCount(networkIdx) == 0)
344 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
346 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
347 bool expandNetwork = networkActive;
348 if(_expandedState.contains(networkId)) {
349 int oldState = _expandedState[networkId];
350 if((bool)(oldState & WasActive) == networkActive)
351 expandNetwork = (bool)(oldState & WasExpanded);
354 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
355 if(expandNetwork != isExpanded(networkIdx))
356 setExpanded(networkIdx, expandNetwork);
359 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
360 QTreeView::dataChanged(topLeft, bottomRight);
362 // determine how many items have been changed and if any of them is a networkitem
363 // which just swichted from active to inactive or vice versa
364 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
367 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
368 QModelIndex networkIdx = topLeft.sibling(i, 0);
369 setExpandedState(networkIdx);
373 void BufferView::toggleHeader(bool checked) {
374 QAction *action = qobject_cast<QAction *>(sender());
375 header()->setSectionHidden((action->property("column")).toInt(), !checked);
378 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
379 QModelIndex index = indexAt(event->pos());
383 QMenu contextMenu(this);
385 if(index.isValid()) {
386 addActionsToMenu(&contextMenu, index);
389 addFilterActions(&contextMenu, index);
391 if(!contextMenu.actions().isEmpty())
392 contextMenu.exec(QCursor::pos());
395 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
396 QModelIndexList indexList = selectedIndexes();
397 // make sure the item we clicked on is first
398 indexList.removeAll(index);
399 indexList.prepend(index);
401 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
404 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
405 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
407 QList<QAction *> filterActions = filter->actions(index);
408 if(!filterActions.isEmpty()) {
409 contextMenu->addSeparator();
410 foreach(QAction *action, filterActions) {
411 contextMenu->addAction(action);
417 void BufferView::menuActionTriggered(QAction *result) {
418 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
420 case ContextMenuActionProvider::HideBufferTemporarily:
421 removeSelectedBuffers();
423 case ContextMenuActionProvider::HideBufferPermanently:
424 removeSelectedBuffers(true);
431 void BufferView::wheelEvent(QWheelEvent* event) {
432 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
433 return QTreeView::wheelEvent(event);
435 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
436 QModelIndex currentIndex = selectionModel()->currentIndex();
437 QModelIndex resultingIndex;
438 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
440 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
442 else //if we scroll into a the parent node...
444 QModelIndex parent = currentIndex.parent();
445 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
447 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
449 resultingIndex = aunt.child( 0, 0 );
450 if( !resultingIndex.isValid() )
453 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
454 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
458 QSize BufferView::sizeHint() const {
459 return QTreeView::sizeHint();
462 return QTreeView::sizeHint();
464 if(model()->rowCount() == 0)
465 return QSize(120, 50);
468 for(int i = 0; i < model()->columnCount(); i++) {
469 if(!isColumnHidden(i))
470 columnSize += sizeHintForColumn(i);
472 return QSize(columnSize, 50);
476 // ****************************************
478 // ****************************************
479 class ColorsChangedEvent : public QEvent {
481 ColorsChangedEvent() : QEvent(QEvent::User) {};
484 BufferViewDelegate::BufferViewDelegate(QObject *parent)
485 : QStyledItemDelegate(parent),
490 UiSettings s("QtUiStyle/Colors");
491 s.notify("inactiveActivityFG", this, SLOT(colorsChanged()));
492 s.notify("noActivityFG", this, SLOT(colorsChanged()));
493 s.notify("highlightActivityFG", this, SLOT(colorsChanged()));
494 s.notify("newMessageActivityFG", this, SLOT(colorsChanged()));
495 s.notify("otherActivityFG", this, SLOT(colorsChanged()));
498 void BufferViewDelegate::colorsChanged() {
499 // avoid mutliple unneded reloads of all colors
502 _updateColors = true;
503 QCoreApplication::postEvent(this, new ColorsChangedEvent());
506 void BufferViewDelegate::customEvent(QEvent *event) {
507 if(event->type() != QEvent::User)
511 _updateColors = false;
516 void BufferViewDelegate::loadColors() {
517 UiSettings s("QtUiStyle/Colors");
518 _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
519 _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
520 _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
521 _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
522 _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
525 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
526 if(event->type() != QEvent::MouseButtonRelease)
527 return QStyledItemDelegate::editorEvent(event, model, option, index);
529 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
530 return QStyledItemDelegate::editorEvent(event, model, option, index);
532 QVariant value = index.data(Qt::CheckStateRole);
534 return QStyledItemDelegate::editorEvent(event, model, option, index);
536 QStyleOptionViewItemV4 viewOpt(option);
537 initStyleOption(&viewOpt, index);
539 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
540 QMouseEvent *me = static_cast<QMouseEvent*>(event);
542 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
543 return QStyledItemDelegate::editorEvent(event, model, option, index);
545 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
546 if(state == Qt::Unchecked)
547 state = Qt::PartiallyChecked;
548 else if(state == Qt::PartiallyChecked)
551 state = Qt::Unchecked;
552 model->setData(index, state, Qt::CheckStateRole);
556 void BufferViewDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const {
557 QStyledItemDelegate::initStyleOption(option, index);
562 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
564 QColor fgColor = _FgColorNoActivity;
565 if(activity & BufferInfo::Highlight) {
566 fgColor = _FgColorHighlightActivity;
567 } else if(activity & BufferInfo::NewMessage) {
568 fgColor = _FgColorNewMessageActivity;
569 } else if(activity & BufferInfo::OtherActivity) {
570 fgColor = _FgColorOtherActivity;
571 } else if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool()) {
572 fgColor = _FgColorInactiveActivity;
575 option->palette.setColor(QPalette::Text, fgColor);
579 // ==============================
581 // ==============================
582 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
583 : QDockWidget(config->bufferViewName(), parent)
585 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
586 toggleViewAction()->setData(config->bufferViewId());
587 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
588 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
591 void BufferViewDock::bufferViewRenamed(const QString &newName) {
592 setWindowTitle(newName);
593 toggleViewAction()->setText(newName);