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 config()->requestRemoveBufferPermanently(bufferId);
283 config()->requestRemoveBuffer(bufferId);
287 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
288 QTreeView::rowsInserted(parent, start, end);
290 // ensure that newly inserted network nodes are expanded per default
291 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
294 setExpandedState(parent);
297 void BufferView::on_layoutChanged() {
298 int numNets = model()->rowCount(QModelIndex());
299 for(int row = 0; row < numNets; row++) {
300 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
301 setExpandedState(networkIdx);
305 void BufferView::on_configChanged() {
308 // expand all active networks... collapse inactive ones... unless manually changed
309 QModelIndex networkIdx;
311 for(int row = 0; row < model()->rowCount(); row++) {
312 networkIdx = model()->index(row, 0);
313 if(model()->rowCount(networkIdx) == 0)
316 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
317 if(!networkId.isValid())
320 setExpandedState(networkIdx);
324 // update selection to current one
325 Client::bufferModel()->synchronizeView(this);
329 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
330 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
333 if(isExpanded(networkIdx))
334 oldState |= WasExpanded;
335 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
336 oldState |= WasActive;
338 _expandedState[networkId] = oldState;
341 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
342 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
345 if(model()->rowCount(networkIdx) == 0)
348 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
350 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
351 bool expandNetwork = networkActive;
352 if(_expandedState.contains(networkId)) {
353 int oldState = _expandedState[networkId];
354 if((bool)(oldState & WasActive) == networkActive)
355 expandNetwork = (bool)(oldState & WasExpanded);
358 if(expandNetwork != isExpanded(networkIdx)) {
360 setExpanded(networkIdx, expandNetwork);
362 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
365 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
366 QTreeView::dataChanged(topLeft, bottomRight);
368 // determine how many items have been changed and if any of them is a networkitem
369 // which just swichted from active to inactive or vice versa
370 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
373 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
374 QModelIndex networkIdx = topLeft.sibling(i, 0);
375 setExpandedState(networkIdx);
379 void BufferView::toggleHeader(bool checked) {
380 QAction *action = qobject_cast<QAction *>(sender());
381 header()->setSectionHidden((action->property("column")).toInt(), !checked);
384 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
385 QModelIndex index = indexAt(event->pos());
389 QMenu contextMenu(this);
391 if(index.isValid()) {
392 addActionsToMenu(&contextMenu, index);
395 addFilterActions(&contextMenu, index);
397 if(!contextMenu.actions().isEmpty())
398 contextMenu.exec(QCursor::pos());
401 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
402 QModelIndexList indexList = selectedIndexes();
403 // make sure the item we clicked on is first
404 indexList.removeAll(index);
405 indexList.prepend(index);
407 GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
410 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
411 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
413 QList<QAction *> filterActions = filter->actions(index);
414 if(!filterActions.isEmpty()) {
415 contextMenu->addSeparator();
416 foreach(QAction *action, filterActions) {
417 contextMenu->addAction(action);
423 void BufferView::menuActionTriggered(QAction *result) {
424 ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
426 case ContextMenuActionProvider::HideBufferTemporarily:
427 removeSelectedBuffers();
429 case ContextMenuActionProvider::HideBufferPermanently:
430 removeSelectedBuffers(true);
437 void BufferView::wheelEvent(QWheelEvent* event) {
438 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
439 return QTreeView::wheelEvent(event);
441 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
442 QModelIndex currentIndex = selectionModel()->currentIndex();
443 QModelIndex resultingIndex;
444 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
446 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
448 else //if we scroll into a the parent node...
450 QModelIndex parent = currentIndex.parent();
451 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
453 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
455 resultingIndex = aunt.child( 0, 0 );
456 if( !resultingIndex.isValid() )
459 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
460 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
464 QSize BufferView::sizeHint() const {
465 return QTreeView::sizeHint();
468 return QTreeView::sizeHint();
470 if(model()->rowCount() == 0)
471 return QSize(120, 50);
474 for(int i = 0; i < model()->columnCount(); i++) {
475 if(!isColumnHidden(i))
476 columnSize += sizeHintForColumn(i);
478 return QSize(columnSize, 50);
482 // ****************************************
484 // ****************************************
485 class ColorsChangedEvent : public QEvent {
487 ColorsChangedEvent() : QEvent(QEvent::User) {};
490 BufferViewDelegate::BufferViewDelegate(QObject *parent)
491 : QStyledItemDelegate(parent),
496 UiSettings s("QtUiStyle/Colors");
497 s.notify("inactiveActivityFG", this, SLOT(colorsChanged()));
498 s.notify("noActivityFG", this, SLOT(colorsChanged()));
499 s.notify("highlightActivityFG", this, SLOT(colorsChanged()));
500 s.notify("newMessageActivityFG", this, SLOT(colorsChanged()));
501 s.notify("otherActivityFG", this, SLOT(colorsChanged()));
504 void BufferViewDelegate::colorsChanged() {
505 // avoid mutliple unneded reloads of all colors
508 _updateColors = true;
509 QCoreApplication::postEvent(this, new ColorsChangedEvent());
512 void BufferViewDelegate::customEvent(QEvent *event) {
513 if(event->type() != QEvent::User)
517 _updateColors = false;
522 void BufferViewDelegate::loadColors() {
523 UiSettings s("QtUiStyle/Colors");
524 _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
525 _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
526 _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
527 _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
528 _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
531 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
532 if(event->type() != QEvent::MouseButtonRelease)
533 return QStyledItemDelegate::editorEvent(event, model, option, index);
535 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
536 return QStyledItemDelegate::editorEvent(event, model, option, index);
538 QVariant value = index.data(Qt::CheckStateRole);
540 return QStyledItemDelegate::editorEvent(event, model, option, index);
542 QStyleOptionViewItemV4 viewOpt(option);
543 initStyleOption(&viewOpt, index);
545 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
546 QMouseEvent *me = static_cast<QMouseEvent*>(event);
548 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
549 return QStyledItemDelegate::editorEvent(event, model, option, index);
551 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
552 if(state == Qt::Unchecked)
553 state = Qt::PartiallyChecked;
554 else if(state == Qt::PartiallyChecked)
557 state = Qt::Unchecked;
558 model->setData(index, state, Qt::CheckStateRole);
562 void BufferViewDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const {
563 QStyledItemDelegate::initStyleOption(option, index);
568 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
570 QColor fgColor = _FgColorNoActivity;
571 if(activity & BufferInfo::Highlight) {
572 fgColor = _FgColorHighlightActivity;
573 } else if(activity & BufferInfo::NewMessage) {
574 fgColor = _FgColorNewMessageActivity;
575 } else if(activity & BufferInfo::OtherActivity) {
576 fgColor = _FgColorOtherActivity;
577 } else if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool()) {
578 fgColor = _FgColorInactiveActivity;
581 option->palette.setColor(QPalette::Text, fgColor);
585 // ==============================
587 // ==============================
588 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
589 : QDockWidget(config->bufferViewName(), parent)
591 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
592 toggleViewAction()->setData(config->bufferViewId());
593 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
594 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
597 void BufferViewDock::bufferViewRenamed(const QString &newName) {
598 setWindowTitle(newName);
599 toggleViewAction()->setText(newName);