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);
65 void BufferView::init() {
66 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
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 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
87 // afaik this is better on Mac and Windows
88 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
92 void BufferView::setModel(QAbstractItemModel *model) {
93 delete selectionModel();
95 QTreeView::setModel(model);
98 QList<QAction *> oldactions = header()->actions();
99 foreach(QAction *action, oldactions) {
100 header()->removeAction(action);
101 action->deleteLater();
108 QAction *showSection;
109 for(int i = 1; i < model->columnCount(); i++) {
110 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
111 showSection = new QAction(sectionName, header());
112 showSection->setCheckable(true);
113 showSection->setChecked(!isColumnHidden(i));
114 showSection->setProperty("column", i);
115 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
116 header()->addAction(showSection);
121 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
122 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
124 filter->setConfig(config);
130 disconnect(this, 0, model(), 0);
131 disconnect(model(), 0, this, 0);
137 BufferViewFilter *filter = new BufferViewFilter(model_, config);
139 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
144 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
145 if(QTreeView::selectionModel())
146 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
147 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
149 QTreeView::setSelectionModel(selectionModel);
150 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
152 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
153 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
157 void BufferView::setConfig(BufferViewConfig *config) {
158 if(_config == config)
162 disconnect(_config, 0, this, 0);
167 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
168 setRootIndexForNetworkId(config->networkId());
171 setRootIndex(QModelIndex());
175 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
176 if(!networkId.isValid() || !model()) {
178 setRootIndex(QModelIndex());
181 int networkCount = model()->rowCount();
183 for(int i = 0; i < networkCount; i++) {
184 child = model()->index(i, 0);
185 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
191 void BufferView::joinChannel(const QModelIndex &index) {
192 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
194 if(bufferType != BufferInfo::ChannelBuffer)
197 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
199 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
202 void BufferView::keyPressEvent(QKeyEvent *event) {
203 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
205 removeSelectedBuffers();
207 QTreeView::keyPressEvent(event);
210 void BufferView::dropEvent(QDropEvent *event) {
211 QModelIndex index = indexAt(event->pos());
213 QRect indexRect = visualRect(index);
214 QPoint cursorPos = event->pos();
216 // check if we're really _on_ the item and not indicating a move to just above or below the item
217 const int margin = 2;
218 if(cursorPos.y() - indexRect.top() < margin
219 || indexRect.bottom() - cursorPos.y() < margin)
220 return QTreeView::dropEvent(event);
222 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
223 if(bufferList.count() != 1)
224 return QTreeView::dropEvent(event);
226 NetworkId networkId = bufferList[0].first;
227 BufferId bufferId2 = bufferList[0].second;
229 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
230 return QTreeView::dropEvent(event);
232 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
233 return QTreeView::dropEvent(event);
235 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
236 return QTreeView::dropEvent(event);
238 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
239 if(bufferId1 == bufferId2)
240 return QTreeView::dropEvent(event);
242 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
243 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)),
244 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
245 if(res == QMessageBox::Yes) {
246 Client::mergeBuffersPermanently(bufferId1, bufferId2);
250 void BufferView::removeSelectedBuffers(bool permanently) {
255 QSet<BufferId> removedRows;
256 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
257 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
260 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
261 if(removedRows.contains(bufferId))
264 removedRows << bufferId;
267 config()->requestRemoveBufferPermanently(bufferId);
269 config()->requestRemoveBuffer(bufferId);
273 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
274 QTreeView::rowsInserted(parent, start, end);
276 // ensure that newly inserted network nodes are expanded per default
277 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
280 if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
281 // without updating the parent the expand will have no effect... Qt Bug?
287 void BufferView::on_configChanged() {
290 // expand all active networks... collapse inactive ones... unless manually changed
291 QModelIndex networkIdx;
293 for(int row = 0; row < model()->rowCount(); row++) {
294 networkIdx = model()->index(row, 0);
295 if(model()->rowCount(networkIdx) == 0)
298 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
299 if(!networkId.isValid())
303 setExpandedState(networkIdx);
307 // update selection to current one
308 Client::bufferModel()->synchronizeView(this);
314 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
315 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
318 if(isExpanded(networkIdx))
319 oldState |= WasExpanded;
320 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
321 oldState |= WasActive;
323 _expandedState[networkId] = oldState;
326 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
327 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
330 if(model()->rowCount(networkIdx) == 0)
333 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
335 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
336 bool expandNetwork = networkActive;
337 if(_expandedState.contains(networkId)) {
338 int oldState = _expandedState[networkId];
339 if((bool)(oldState & WasActive) == networkActive)
340 expandNetwork = (bool)(oldState & WasExpanded);
343 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
344 if(expandNetwork != isExpanded(networkIdx))
345 setExpanded(networkIdx, expandNetwork);
348 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
349 QTreeView::dataChanged(topLeft, bottomRight);
351 // determine how many items have been changed and if any of them is a networkitem
352 // which just swichted from active to inactive or vice versa
353 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
356 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
357 QModelIndex networkIdx = topLeft.sibling(i, 0);
358 setExpandedState(networkIdx);
362 void BufferView::toggleHeader(bool checked) {
363 QAction *action = qobject_cast<QAction *>(sender());
364 header()->setSectionHidden((action->property("column")).toInt(), !checked);
367 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
368 QModelIndex index = indexAt(event->pos());
372 QMenu contextMenu(this);
374 if(index.isValid()) {
375 addActionsToMenu(&contextMenu, index);
378 addFilterActions(&contextMenu, index);
380 if(!contextMenu.actions().isEmpty())
381 contextMenu.exec(QCursor::pos());
384 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
385 QModelIndexList indexList = selectedIndexes();
386 // make sure the item we clicked on is first
387 indexList.removeAll(index);
388 indexList.prepend(index);
390 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
393 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
394 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
396 QList<QAction *> filterActions = filter->actions(index);
397 if(!filterActions.isEmpty()) {
398 contextMenu->addSeparator();
399 foreach(QAction *action, filterActions) {
400 contextMenu->addAction(action);
406 void BufferView::menuActionTriggered(QAction *result) {
407 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
409 case ContextMenuActionProvider::HideBufferTemporarily:
410 removeSelectedBuffers();
412 case ContextMenuActionProvider::HideBufferPermanently:
413 removeSelectedBuffers(true);
420 void BufferView::wheelEvent(QWheelEvent* event) {
421 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
422 return QTreeView::wheelEvent(event);
424 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
425 QModelIndex currentIndex = selectionModel()->currentIndex();
426 QModelIndex resultingIndex;
427 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
429 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
431 else //if we scroll into a the parent node...
433 QModelIndex parent = currentIndex.parent();
434 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
436 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
438 resultingIndex = aunt.child( 0, 0 );
439 if( !resultingIndex.isValid() )
442 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
443 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
447 QSize BufferView::sizeHint() const {
448 return QTreeView::sizeHint();
451 return QTreeView::sizeHint();
453 if(model()->rowCount() == 0)
454 return QSize(120, 50);
457 for(int i = 0; i < model()->columnCount(); i++) {
458 if(!isColumnHidden(i))
459 columnSize += sizeHintForColumn(i);
461 return QSize(columnSize, 50);
465 // ****************************************
467 // ****************************************
468 class ColorsChangedEvent : public QEvent {
470 ColorsChangedEvent() : QEvent(QEvent::User) {};
473 BufferViewDelegate::BufferViewDelegate(QObject *parent)
474 : QStyledItemDelegate(parent),
479 UiSettings s("QtUiStyle/Colors");
480 s.notify("inactiveActivityFG", this, SLOT(colorsChanged()));
481 s.notify("noActivityFG", this, SLOT(colorsChanged()));
482 s.notify("highlightActivityFG", this, SLOT(colorsChanged()));
483 s.notify("newMessageActivityFG", this, SLOT(colorsChanged()));
484 s.notify("otherActivityFG", this, SLOT(colorsChanged()));
487 void BufferViewDelegate::colorsChanged() {
488 // avoid mutliple unneded reloads of all colors
491 _updateColors = true;
492 QCoreApplication::postEvent(this, new ColorsChangedEvent());
495 void BufferViewDelegate::customEvent(QEvent *event) {
496 if(event->type() != QEvent::User)
500 _updateColors = false;
505 void BufferViewDelegate::loadColors() {
506 UiSettings s("QtUiStyle/Colors");
507 _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
508 _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
509 _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
510 _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
511 _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
514 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
515 if(event->type() != QEvent::MouseButtonRelease)
516 return QStyledItemDelegate::editorEvent(event, model, option, index);
518 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
519 return QStyledItemDelegate::editorEvent(event, model, option, index);
521 QVariant value = index.data(Qt::CheckStateRole);
523 return QStyledItemDelegate::editorEvent(event, model, option, index);
525 QStyleOptionViewItemV4 viewOpt(option);
526 initStyleOption(&viewOpt, index);
528 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
529 QMouseEvent *me = static_cast<QMouseEvent*>(event);
531 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
532 return QStyledItemDelegate::editorEvent(event, model, option, index);
534 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
535 if(state == Qt::Unchecked)
536 state = Qt::PartiallyChecked;
537 else if(state == Qt::PartiallyChecked)
540 state = Qt::Unchecked;
541 model->setData(index, state, Qt::CheckStateRole);
545 void BufferViewDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const {
546 QStyledItemDelegate::initStyleOption(option, index);
551 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
553 QColor fgColor = _FgColorNoActivity;
554 if(activity & BufferInfo::Highlight) {
555 fgColor = _FgColorHighlightActivity;
556 } else if(activity & BufferInfo::NewMessage) {
557 fgColor = _FgColorNewMessageActivity;
558 } else if(activity & BufferInfo::OtherActivity) {
559 fgColor = _FgColorOtherActivity;
560 } else if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool()) {
561 fgColor = _FgColorInactiveActivity;
564 option->palette.setColor(QPalette::Text, fgColor);
568 // ==============================
570 // ==============================
571 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
572 : QDockWidget(config->bufferViewName(), parent)
574 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
575 toggleViewAction()->setData(config->bufferViewId());
576 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
577 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
580 void BufferViewDock::bufferViewRenamed(const QString &newName) {
581 setWindowTitle(newName);
582 toggleViewAction()->setText(newName);