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 "iconloader.h"
40 #include "networkmodel.h"
41 #include "networkmodelactionprovider.h"
42 #include "quasselui.h"
43 #include "uisettings.h"
45 /*****************************************
46 * The TreeView showing the Buffers
47 *****************************************/
48 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
49 // to be on the safe side: call QTreeView's method aswell
50 BufferView::BufferView(QWidget *parent)
53 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
54 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
56 setSelectionMode(QAbstractItemView::ExtendedSelection);
58 QAbstractItemDelegate *oldDelegate = itemDelegate();
59 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
60 setItemDelegate(tristateDelegate);
64 void BufferView::init() {
65 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
73 #ifndef QT_NO_DRAGANDDROP
76 setDropIndicatorShown(true);
79 setSortingEnabled(true);
80 sortByColumn(0, Qt::AscendingOrder);
82 // activated() fails on X11 and Qtopia at least
83 #if defined Q_WS_QWS || defined Q_WS_X11
84 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
86 // afaik this is better on Mac and Windows
87 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
91 void BufferView::setModel(QAbstractItemModel *model) {
92 delete selectionModel();
94 QTreeView::setModel(model);
97 QList<QAction *> oldactions = header()->actions();
98 foreach(QAction *action, oldactions) {
99 header()->removeAction(action);
100 action->deleteLater();
107 QAction *showSection;
108 for(int i = 1; i < model->columnCount(); i++) {
109 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
110 showSection = new QAction(sectionName, header());
111 showSection->setCheckable(true);
112 showSection->setChecked(!isColumnHidden(i));
113 showSection->setProperty("column", i);
114 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
115 header()->addAction(showSection);
120 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
121 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
123 filter->setConfig(config);
129 disconnect(this, 0, model(), 0);
130 disconnect(model(), 0, this, 0);
136 BufferViewFilter *filter = new BufferViewFilter(model_, config);
138 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
143 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
144 if(QTreeView::selectionModel())
145 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
146 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
148 QTreeView::setSelectionModel(selectionModel);
149 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
151 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
152 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
156 void BufferView::setConfig(BufferViewConfig *config) {
157 if(_config == config)
161 disconnect(_config, 0, this, 0);
166 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
167 setRootIndexForNetworkId(config->networkId());
170 setRootIndex(QModelIndex());
174 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
175 if(!networkId.isValid() || !model()) {
177 setRootIndex(QModelIndex());
180 int networkCount = model()->rowCount();
182 for(int i = 0; i < networkCount; i++) {
183 child = model()->index(i, 0);
184 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
190 void BufferView::joinChannel(const QModelIndex &index) {
191 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
193 if(bufferType != BufferInfo::ChannelBuffer)
196 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
198 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
201 void BufferView::keyPressEvent(QKeyEvent *event) {
202 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
204 removeSelectedBuffers();
206 QTreeView::keyPressEvent(event);
209 void BufferView::dropEvent(QDropEvent *event) {
210 QModelIndex index = indexAt(event->pos());
212 QRect indexRect = visualRect(index);
213 QPoint cursorPos = event->pos();
215 // check if we're really _on_ the item and not indicating a move to just above or below the item
216 const int margin = 2;
217 if(cursorPos.y() - indexRect.top() < margin
218 || indexRect.bottom() - cursorPos.y() < margin)
219 return QTreeView::dropEvent(event);
221 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
222 if(bufferList.count() != 1)
223 return QTreeView::dropEvent(event);
225 NetworkId networkId = bufferList[0].first;
226 BufferId bufferId2 = bufferList[0].second;
228 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
229 return QTreeView::dropEvent(event);
231 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
232 return QTreeView::dropEvent(event);
234 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
235 return QTreeView::dropEvent(event);
237 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
238 if(bufferId1 == bufferId2)
239 return QTreeView::dropEvent(event);
241 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
242 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)),
243 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
244 if(res == QMessageBox::Yes) {
245 Client::mergeBuffersPermanently(bufferId1, bufferId2);
249 void BufferView::removeSelectedBuffers(bool permanently) {
254 QSet<BufferId> removedRows;
255 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
256 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
259 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
260 if(removedRows.contains(bufferId))
263 removedRows << bufferId;
266 config()->requestRemoveBufferPermanently(bufferId);
268 config()->requestRemoveBuffer(bufferId);
272 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
273 QTreeView::rowsInserted(parent, start, end);
275 // ensure that newly inserted network nodes are expanded per default
276 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
279 if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
280 // without updating the parent the expand will have no effect... Qt Bug?
286 void BufferView::on_configChanged() {
289 // expand all active networks... collapse inactive ones... unless manually changed
290 QModelIndex networkIdx;
292 for(int row = 0; row < model()->rowCount(); row++) {
293 networkIdx = model()->index(row, 0);
294 if(model()->rowCount(networkIdx) == 0)
297 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
298 if(!networkId.isValid())
302 setExpandedState(networkIdx);
306 // update selection to current one
307 Client::bufferModel()->synchronizeView(this);
313 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
314 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
317 if(isExpanded(networkIdx))
318 oldState |= WasExpanded;
319 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
320 oldState |= WasActive;
322 _expandedState[networkId] = oldState;
325 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
326 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
329 if(model()->rowCount(networkIdx) == 0)
332 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
334 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
335 bool expandNetwork = networkActive;
336 if(_expandedState.contains(networkId)) {
337 int oldState = _expandedState[networkId];
338 if((bool)(oldState & WasActive) == networkActive)
339 expandNetwork = (bool)(oldState & WasExpanded);
342 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
343 if(expandNetwork != isExpanded(networkIdx))
344 setExpanded(networkIdx, expandNetwork);
347 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
348 QTreeView::dataChanged(topLeft, bottomRight);
350 // determine how many items have been changed and if any of them is a networkitem
351 // which just swichted from active to inactive or vice versa
352 if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
355 for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
356 QModelIndex networkIdx = topLeft.sibling(i, 0);
357 setExpandedState(networkIdx);
361 void BufferView::toggleHeader(bool checked) {
362 QAction *action = qobject_cast<QAction *>(sender());
363 header()->setSectionHidden((action->property("column")).toInt(), !checked);
366 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
367 QModelIndex index = indexAt(event->pos());
371 QMenu contextMenu(this);
373 if(index.isValid()) {
374 addActionsToMenu(&contextMenu, index);
377 addFilterActions(&contextMenu, index);
379 if(!contextMenu.actions().isEmpty())
380 contextMenu.exec(QCursor::pos());
383 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
384 QModelIndexList indexList = selectedIndexes();
385 // make sure the item we clicked on is first
386 indexList.removeAll(index);
387 indexList.prepend(index);
389 Client::mainUi()->actionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
392 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
393 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
395 QList<QAction *> filterActions = filter->actions(index);
396 if(!filterActions.isEmpty()) {
397 contextMenu->addSeparator();
398 foreach(QAction *action, filterActions) {
399 contextMenu->addAction(action);
405 void BufferView::menuActionTriggered(QAction *result) {
406 NetworkModelActionProvider::ActionType type = (NetworkModelActionProvider::ActionType)result->data().toInt();
408 case NetworkModelActionProvider::HideBufferTemporarily:
409 removeSelectedBuffers();
411 case NetworkModelActionProvider::HideBufferPermanently:
412 removeSelectedBuffers(true);
419 void BufferView::wheelEvent(QWheelEvent* event) {
420 if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
421 return QTreeView::wheelEvent(event);
423 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
424 QModelIndex currentIndex = selectionModel()->currentIndex();
425 QModelIndex resultingIndex;
426 if( model()->hasIndex( currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
428 resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
430 else //if we scroll into a the parent node...
432 QModelIndex parent = currentIndex.parent();
433 QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
435 resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
437 resultingIndex = aunt.child( 0, 0 );
438 if( !resultingIndex.isValid() )
441 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
442 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
446 QSize BufferView::sizeHint() const {
447 return QTreeView::sizeHint();
450 return QTreeView::sizeHint();
452 if(model()->rowCount() == 0)
453 return QSize(120, 50);
456 for(int i = 0; i < model()->columnCount(); i++) {
457 if(!isColumnHidden(i))
458 columnSize += sizeHintForColumn(i);
460 return QSize(columnSize, 50);
464 // ****************************************
466 // ****************************************
467 BufferViewDelegate::BufferViewDelegate(QObject *parent)
468 : QStyledItemDelegate(parent)
470 UiSettings s("QtUiStyle/Colors");
471 _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
472 _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
473 _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
474 _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
475 _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
478 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
479 if(event->type() != QEvent::MouseButtonRelease)
480 return QStyledItemDelegate::editorEvent(event, model, option, index);
482 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
483 return QStyledItemDelegate::editorEvent(event, model, option, index);
485 QVariant value = index.data(Qt::CheckStateRole);
487 return QStyledItemDelegate::editorEvent(event, model, option, index);
489 QStyleOptionViewItemV4 viewOpt(option);
490 initStyleOption(&viewOpt, index);
492 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
493 QMouseEvent *me = static_cast<QMouseEvent*>(event);
495 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
496 return QStyledItemDelegate::editorEvent(event, model, option, index);
498 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
499 if(state == Qt::Unchecked)
500 state = Qt::PartiallyChecked;
501 else if(state == Qt::PartiallyChecked)
504 state = Qt::Unchecked;
505 model->setData(index, state, Qt::CheckStateRole);
509 void BufferViewDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const {
510 QStyledItemDelegate::initStyleOption(option, index);
512 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
514 QColor fgColor = _FgColorNoActivity;
515 if(activity & BufferInfo::Highlight) {
516 fgColor = _FgColorHighlightActivity;
517 } else if(activity & BufferInfo::NewMessage) {
518 fgColor = _FgColorNewMessageActivity;
519 } else if(activity & BufferInfo::OtherActivity) {
520 fgColor = _FgColorOtherActivity;
521 } else if(!index.data(NetworkModel::ItemActiveRole).toBool() || index.data(NetworkModel::UserAwayRole).toBool()) {
522 fgColor = _FgColorInactiveActivity;
525 option->palette.setColor(QPalette::Text, fgColor);
529 // ==============================
531 // ==============================
532 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
533 : QDockWidget(config->bufferViewName(), parent)
535 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
536 toggleViewAction()->setData(config->bufferViewId());
537 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
538 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
541 void BufferViewDock::bufferViewRenamed(const QString &newName) {
542 setWindowTitle(newName);
543 toggleViewAction()->setText(newName);