1 /***************************************************************************
2 * Copyright (C) 2005-2010 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"
41 #include "networkmodel.h"
42 #include "contextmenuactionprovider.h"
44 /*****************************************
45 * The TreeView showing the Buffers
46 *****************************************/
47 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
48 // to be on the safe side: call QTreeView's method aswell
49 BufferView::BufferView(QWidget *parent)
52 connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
53 connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
55 setSelectionMode(QAbstractItemView::ExtendedSelection);
57 QAbstractItemDelegate *oldDelegate = itemDelegate();
58 BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
59 setItemDelegate(tristateDelegate);
63 void BufferView::init() {
64 header()->setContextMenuPolicy(Qt::ActionsContextMenu);
70 header()->hide(); // nobody seems to use this anyway
74 // FIXME This is to workaround bug #663
75 setUniformRowHeights(true);
77 #ifndef QT_NO_DRAGANDDROP
80 setDropIndicatorShown(true);
83 setSortingEnabled(true);
84 sortByColumn(0, Qt::AscendingOrder);
86 // activated() fails on X11 and Qtopia at least
87 #if defined Q_WS_QWS || defined Q_WS_X11
88 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
89 connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
91 // afaik this is better on Mac and Windows
92 disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
93 connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
97 void BufferView::setModel(QAbstractItemModel *model) {
98 delete selectionModel();
100 QTreeView::setModel(model);
102 // remove old Actions
103 QList<QAction *> oldactions = header()->actions();
104 foreach(QAction *action, oldactions) {
105 header()->removeAction(action);
106 action->deleteLater();
113 QAction *showSection;
114 for(int i = 1; i < model->columnCount(); i++) {
115 sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
116 showSection = new QAction(sectionName, header());
117 showSection->setCheckable(true);
118 showSection->setChecked(!isColumnHidden(i));
119 showSection->setProperty("column", i);
120 connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
121 header()->addAction(showSection);
124 connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
127 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
128 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
130 filter->setConfig(config);
136 disconnect(this, 0, model(), 0);
137 disconnect(model(), 0, this, 0);
143 BufferViewFilter *filter = new BufferViewFilter(model_, config);
145 connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
150 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
151 if(QTreeView::selectionModel())
152 disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
153 model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
155 QTreeView::setSelectionModel(selectionModel);
156 BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
158 connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
159 filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
163 void BufferView::setConfig(BufferViewConfig *config) {
164 if(_config == config)
168 disconnect(_config, 0, this, 0);
173 connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
174 setRootIndexForNetworkId(config->networkId());
177 setRootIndex(QModelIndex());
181 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
182 if(!networkId.isValid() || !model()) {
184 setRootIndex(QModelIndex());
187 int networkCount = model()->rowCount();
189 for(int i = 0; i < networkCount; i++) {
190 child = model()->index(i, 0);
191 if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
197 void BufferView::joinChannel(const QModelIndex &index) {
198 BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
200 if(bufferType != BufferInfo::ChannelBuffer)
203 BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
205 Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
208 void BufferView::keyPressEvent(QKeyEvent *event) {
209 if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
211 removeSelectedBuffers();
213 QTreeView::keyPressEvent(event);
216 void BufferView::dropEvent(QDropEvent *event) {
217 QModelIndex index = indexAt(event->pos());
219 QRect indexRect = visualRect(index);
220 QPoint cursorPos = event->pos();
222 // check if we're really _on_ the item and not indicating a move to just above or below the item
223 const int margin = 2;
224 if(cursorPos.y() - indexRect.top() < margin
225 || indexRect.bottom() - cursorPos.y() < margin)
226 return QTreeView::dropEvent(event);
228 QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
229 if(bufferList.count() != 1)
230 return QTreeView::dropEvent(event);
232 NetworkId networkId = bufferList[0].first;
233 BufferId bufferId2 = bufferList[0].second;
235 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
236 return QTreeView::dropEvent(event);
238 if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
239 return QTreeView::dropEvent(event);
241 if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
242 return QTreeView::dropEvent(event);
244 BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
245 if(bufferId1 == bufferId2)
246 return QTreeView::dropEvent(event);
248 int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
249 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)),
250 QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
251 if(res == QMessageBox::Yes) {
252 Client::mergeBuffersPermanently(bufferId1, bufferId2);
256 void BufferView::removeSelectedBuffers(bool permanently) {
261 QSet<BufferId> removedRows;
262 foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
263 if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
266 bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
267 if(removedRows.contains(bufferId))
270 removedRows << bufferId;
273 foreach(BufferId bufferId, removedRows) {
275 config()->requestRemoveBufferPermanently(bufferId);
277 config()->requestRemoveBuffer(bufferId);
281 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
282 QTreeView::rowsInserted(parent, start, end);
284 // ensure that newly inserted network nodes are expanded per default
285 if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
288 setExpandedState(parent);
291 void BufferView::on_layoutChanged() {
292 int numNets = model()->rowCount(QModelIndex());
293 for(int row = 0; row < numNets; row++) {
294 QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
295 setExpandedState(networkIdx);
299 void BufferView::on_configChanged() {
302 // expand all active networks... collapse inactive ones... unless manually changed
303 QModelIndex networkIdx;
305 for(int row = 0; row < model()->rowCount(); row++) {
306 networkIdx = model()->index(row, 0);
307 if(model()->rowCount(networkIdx) == 0)
310 networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
311 if(!networkId.isValid())
314 setExpandedState(networkIdx);
318 // update selection to current one
319 Client::bufferModel()->synchronizeView(this);
323 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
324 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
327 if(isExpanded(networkIdx))
328 oldState |= WasExpanded;
329 if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
330 oldState |= WasActive;
332 _expandedState[networkId] = oldState;
335 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
336 if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
339 if(model()->rowCount(networkIdx) == 0)
342 NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
344 bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
345 bool expandNetwork = networkActive;
346 if(_expandedState.contains(networkId)) {
347 int oldState = _expandedState[networkId];
348 if((bool)(oldState & WasActive) == networkActive)
349 expandNetwork = (bool)(oldState & WasExpanded);
352 if(expandNetwork != isExpanded(networkIdx)) {
354 setExpanded(networkIdx, expandNetwork);
356 storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
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::nextBuffer() {
432 changeBuffer(Forward);
435 void BufferView::previousBuffer() {
436 changeBuffer(Backward);
439 void BufferView::changeBuffer(Direction direction) {
440 QModelIndex currentIndex = selectionModel()->currentIndex();
441 QModelIndex resultingIndex;
442 if(model()->hasIndex( currentIndex.row() + direction, currentIndex.column(), currentIndex.parent()))
443 resultingIndex = currentIndex.sibling(currentIndex.row() + direction, currentIndex.column());
446 //if we scroll into a the parent node...
447 QModelIndex parent = currentIndex.parent();
448 QModelIndex aunt = parent.sibling(parent.row() + direction, parent.column());
449 if(direction == Backward)
450 resultingIndex = aunt.child(model()->rowCount(aunt) - 1, 0);
452 resultingIndex = aunt.child(0, 0);
453 if(!resultingIndex.isValid())
456 selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
457 selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
460 void BufferView::wheelEvent(QWheelEvent* event) {
461 if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
462 return QTreeView::wheelEvent(event);
464 int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
465 changeBuffer((Direction)rowDelta);
468 QSize BufferView::sizeHint() const {
469 return QTreeView::sizeHint();
472 return QTreeView::sizeHint();
474 if(model()->rowCount() == 0)
475 return QSize(120, 50);
478 for(int i = 0; i < model()->columnCount(); i++) {
479 if(!isColumnHidden(i))
480 columnSize += sizeHintForColumn(i);
482 return QSize(columnSize, 50);
486 // ****************************************
488 // ****************************************
489 class ColorsChangedEvent : public QEvent {
491 ColorsChangedEvent() : QEvent(QEvent::User) {};
494 BufferViewDelegate::BufferViewDelegate(QObject *parent)
495 : QStyledItemDelegate(parent)
499 void BufferViewDelegate::customEvent(QEvent *event) {
500 if(event->type() != QEvent::User)
506 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
507 if(event->type() != QEvent::MouseButtonRelease)
508 return QStyledItemDelegate::editorEvent(event, model, option, index);
510 if(!(model->flags(index) & Qt::ItemIsUserCheckable))
511 return QStyledItemDelegate::editorEvent(event, model, option, index);
513 QVariant value = index.data(Qt::CheckStateRole);
515 return QStyledItemDelegate::editorEvent(event, model, option, index);
517 QStyleOptionViewItemV4 viewOpt(option);
518 initStyleOption(&viewOpt, index);
520 QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
521 QMouseEvent *me = static_cast<QMouseEvent*>(event);
523 if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
524 return QStyledItemDelegate::editorEvent(event, model, option, index);
526 Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
527 if(state == Qt::Unchecked)
528 state = Qt::PartiallyChecked;
529 else if(state == Qt::PartiallyChecked)
532 state = Qt::Unchecked;
533 model->setData(index, state, Qt::CheckStateRole);
537 // ==============================
539 // ==============================
540 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
541 : QDockWidget(parent),
543 _title(config->bufferViewName())
545 setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
546 toggleViewAction()->setData(config->bufferViewId());
547 setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
548 connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
552 void BufferViewDock::updateTitle() {
553 QString title = _title;
555 title.prepend(QString::fromUtf8("• "));
556 setWindowTitle(title);
559 void BufferViewDock::setActive(bool active) {
560 if(active != isActive()) {
564 raise(); // for tabbed docks
568 void BufferViewDock::bufferViewRenamed(const QString &newName) {
571 toggleViewAction()->setText(newName);
574 int BufferViewDock::bufferViewId() const {
575 BufferView *view = bufferView();
580 return view->config()->bufferViewId();
585 BufferViewConfig *BufferViewDock::config() const {
586 BufferView *view = bufferView();
590 return view->config();