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 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
90 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
92 // afaik this is better on Mac and Windows
93 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
94 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
98 void BufferView::setModel(QAbstractItemModel *model) {
99 delete selectionModel();
101 QTreeView::setModel(model);
103 // remove old Actions
104 QList<QAction *> oldactions = header()->actions();
105 foreach(QAction *action, oldactions) {
106 header()->removeAction(action);
107 action->deleteLater();
114 QAction *showSection;
115 for(int i = 1; i < model->columnCount(); i++) {
116 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
117 showSection = new QAction(sectionName, header());
118 showSection->setCheckable(true);
119 showSection->setChecked(!isColumnHidden(i));
120 showSection->setProperty("column", i);
121 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
122 header()->addAction(showSection);
125 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
128 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
129 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
131 filter->setConfig(config);
137 disconnect(this, 0, model(), 0);
138 disconnect(model(), 0, this, 0);
144 BufferViewFilter *filter = new BufferViewFilter(model_, config);
146 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
151 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
152 if(QTreeView::selectionModel())
153 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
154 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
156 QTreeView::setSelectionModel(selectionModel);
157 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
159 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
160 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
164 void BufferView::setConfig(BufferViewConfig *config) {
165 if(_config == config)
169 disconnect(_config, 0, this, 0);
174 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
175 setRootIndexForNetworkId(config->networkId());
178 setRootIndex(QModelIndex());
182 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
183 if(!networkId.isValid() || !model()) {
185 setRootIndex(QModelIndex());
188 int networkCount = model()->rowCount();
190 for(int i = 0; i < networkCount; i++) {
191 child = model()->index(i, 0);
192 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
198 void BufferView::setCustomFont(const QVariant &v) {
199 QFont font = v.value<QFont>();
200 if(font.family().isEmpty())
201 font = QApplication::font();
205 void BufferView::joinChannel(const QModelIndex &index) {
206 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
208 if(bufferType != BufferInfo::ChannelBuffer)
211 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
213 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
216 void BufferView::keyPressEvent(QKeyEvent *event) {
217 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
219 removeSelectedBuffers();
221 QTreeView::keyPressEvent(event);
224 void BufferView::dropEvent(QDropEvent *event) {
225 QModelIndex index = indexAt(event->pos());
227 QRect indexRect = visualRect(index);
228 QPoint cursorPos = event->pos();
230 // check if we're really _on_ the item and not indicating a move to just above or below the item
231 const int margin = 2;
232 if(cursorPos.y() - indexRect.top() < margin
233 || indexRect.bottom() - cursorPos.y() < margin)
234 return QTreeView::dropEvent(event);
236 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
237 if(bufferList.count() != 1)
238 return QTreeView::dropEvent(event);
240 NetworkId networkId = bufferList[0].first;
241 BufferId bufferId2 = bufferList[0].second;
243 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
244 return QTreeView::dropEvent(event);
246 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
247 return QTreeView::dropEvent(event);
249 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
250 return QTreeView::dropEvent(event);
252 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
253 if(bufferId1 == bufferId2)
254 return QTreeView::dropEvent(event);
256 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
257 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)),
258 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
259 if(res == QMessageBox::Yes) {
260 Client::mergeBuffersPermanently(bufferId1, bufferId2);
264 void BufferView::removeSelectedBuffers(bool permanently) {
269 QSet<BufferId> removedRows;
270 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
271 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
274 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
275 if(removedRows.contains(bufferId))
278 removedRows << bufferId;
281 foreach(BufferId bufferId, removedRows) {
283 config()->requestRemoveBufferPermanently(bufferId);
285 config()->requestRemoveBuffer(bufferId);
289 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
290 QTreeView::rowsInserted(parent, start, end);
292 // ensure that newly inserted network nodes are expanded per default
293 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
296 setExpandedState(parent);
299 void BufferView::on_layoutChanged() {
300 int numNets = model()->rowCount(QModelIndex());
301 for(int row = 0; row < numNets; row++) {
302 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
303 setExpandedState(networkIdx);
307 void BufferView::on_configChanged() {
310 // expand all active networks... collapse inactive ones... unless manually changed
311 QModelIndex networkIdx;
313 for(int row = 0; row < model()->rowCount(); row++) {
314 networkIdx = model()->index(row, 0);
315 if(model()->rowCount(networkIdx) == 0)
318 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
319 if(!networkId.isValid())
322 setExpandedState(networkIdx);
326 // update selection to current one
327 Client::bufferModel()->synchronizeView(this);
331 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
332 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
335 if(isExpanded(networkIdx))
336 oldState |= WasExpanded;
337 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
338 oldState |= WasActive;
340 _expandedState[networkId] = oldState;
343 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
344 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
347 if(model()->rowCount(networkIdx) == 0)
350 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
352 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
353 bool expandNetwork = networkActive;
354 if(_expandedState.contains(networkId)) {
355 int oldState = _expandedState[networkId];
356 if((bool)(oldState & WasActive) == networkActive)
357 expandNetwork = (bool)(oldState & WasExpanded);
360 if(expandNetwork != isExpanded(networkIdx)) {
362 setExpanded(networkIdx, expandNetwork);
364 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
367 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
368 QTreeView::dataChanged(topLeft, bottomRight);
370 // determine how many items have been changed and if any of them is a networkitem
371 // which just swichted from active to inactive or vice versa
372 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
375 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
376 QModelIndex networkIdx = topLeft.sibling(i, 0);
377 setExpandedState(networkIdx);
381 void BufferView::toggleHeader(bool checked) {
382 QAction *action = qobject_cast<QAction *>(sender());
383 header()->setSectionHidden((action->property("column")).toInt(), !checked);
386 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
387 QModelIndex index = indexAt(event->pos());
391 QMenu contextMenu(this);
393 if(index.isValid()) {
394 addActionsToMenu(&contextMenu, index);
397 addFilterActions(&contextMenu, index);
399 if(!contextMenu.actions().isEmpty())
400 contextMenu.exec(QCursor::pos());
403 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
404 QModelIndexList indexList = selectedIndexes();
405 // make sure the item we clicked on is first
406 indexList.removeAll(index);
407 indexList.prepend(index);
409 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
412 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
413 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
415 QList<QAction *> filterActions = filter->actions(index);
416 if(!filterActions.isEmpty()) {
417 contextMenu->addSeparator();
418 foreach(QAction *action, filterActions) {
419 contextMenu->addAction(action);
425 void BufferView::menuActionTriggered(QAction *result) {
426 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
428 case ContextMenuActionProvider::HideBufferTemporarily:
429 removeSelectedBuffers();
431 case ContextMenuActionProvider::HideBufferPermanently:
432 removeSelectedBuffers(true);
439 void BufferView::wheelEvent(QWheelEvent* event) {
440 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
441 return QTreeView::wheelEvent(event);
443 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
444 QModelIndex currentIndex = selectionModel()->currentIndex();
445 QModelIndex resultingIndex;
446 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
448 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
450 else //if we scroll into a the parent node...
452 QModelIndex parent = currentIndex.parent();
453 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
455 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
457 resultingIndex = aunt.child( 0, 0 );
458 if( !resultingIndex.isValid() )
461 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
462 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
466 QSize BufferView::sizeHint() const {
467 return QTreeView::sizeHint();
470 return QTreeView::sizeHint();
472 if(model()->rowCount() == 0)
473 return QSize(120, 50);
476 for(int i = 0; i < model()->columnCount(); i++) {
477 if(!isColumnHidden(i))
478 columnSize += sizeHintForColumn(i);
480 return QSize(columnSize, 50);
484 // ****************************************
486 // ****************************************
487 class ColorsChangedEvent : public QEvent {
489 ColorsChangedEvent() : QEvent(QEvent::User) {};
492 BufferViewDelegate::BufferViewDelegate(QObject *parent)
493 : QStyledItemDelegate(parent),
498 UiSettings s("QtUiStyle/Colors");
499 s.notify("inactiveActivityFG", this, SLOT(colorsChanged()));
500 s.notify("noActivityFG", this, SLOT(colorsChanged()));
501 s.notify("highlightActivityFG", this, SLOT(colorsChanged()));
502 s.notify("newMessageActivityFG", this, SLOT(colorsChanged()));
503 s.notify("otherActivityFG", this, SLOT(colorsChanged()));
506 void BufferViewDelegate::colorsChanged() {
507 // avoid mutliple unneded reloads of all colors
510 _updateColors = true;
511 QCoreApplication::postEvent(this, new ColorsChangedEvent());
514 void BufferViewDelegate::customEvent(QEvent *event) {
515 if(event->type() != QEvent::User)
519 _updateColors = false;
524 void BufferViewDelegate::loadColors() {
525 UiSettings s("QtUiStyle/Colors");
526 _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
527 _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
528 _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
529 _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
530 _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
533 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
534 if(event->type() != QEvent::MouseButtonRelease)
535 return QStyledItemDelegate::editorEvent(event, model, option, index);
537 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
538 return QStyledItemDelegate::editorEvent(event, model, option, index);
540 QVariant value = index.data(Qt::CheckStateRole);
542 return QStyledItemDelegate::editorEvent(event, model, option, index);
544 QStyleOptionViewItemV4 viewOpt(option);
545 initStyleOption(&viewOpt, index);
547 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
548 QMouseEvent *me = static_cast<QMouseEvent*>(event);
550 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
551 return QStyledItemDelegate::editorEvent(event, model, option, index);
553 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
554 if(state == Qt::Unchecked)
555 state = Qt::PartiallyChecked;
556 else if(state == Qt::PartiallyChecked)
559 state = Qt::Unchecked;
560 model->setData(index, state, Qt::CheckStateRole);
564 void BufferViewDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const {
565 QStyledItemDelegate::initStyleOption(option, index);
570 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
572 QColor fgColor = _FgColorNoActivity;
573 if(activity & BufferInfo::Highlight) {
574 fgColor = _FgColorHighlightActivity;
575 } else if(activity & BufferInfo::NewMessage) {
576 fgColor = _FgColorNewMessageActivity;
577 } else if(activity & BufferInfo::OtherActivity) {
578 fgColor = _FgColorOtherActivity;
579 } else if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool()) {
580 fgColor = _FgColorInactiveActivity;
583 option->palette.setColor(QPalette::Text, fgColor);
587 // ==============================
589 // ==============================
590 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
591 : QDockWidget(config->bufferViewName(), parent)
593 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
594 toggleViewAction()->setData(config->bufferViewId());
595 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
596 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
599 void BufferViewDock::bufferViewRenamed(const QString &newName) {
600 setWindowTitle(newName);
601 toggleViewAction()->setText(newName);