Introducing an edit mode to the bufferviews.
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "bufferview.h"
22
23 #include <QApplication>
24 #include <QAction>
25 #include <QFlags>
26 #include <QHeaderView>
27 #include <QLineEdit>
28 #include <QMenu>
29 #include <QMessageBox>
30 #include <QSet>
31
32 #include "action.h"
33 #include "buffermodel.h"
34 #include "bufferviewfilter.h"
35 #include "buffersettings.h"
36 #include "buffersyncer.h"
37 #include "client.h"
38 #include "iconloader.h"
39 #include "mappedselectionmodel.h"
40 #include "network.h"
41 #include "networkmodel.h"
42 #include "networkmodelactionprovider.h"
43 #include "quasselui.h"
44 #include "uisettings.h"
45
46 bool TristateDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
47   if(event->type() != QEvent::MouseButtonRelease)
48     return QStyledItemDelegate::editorEvent(event, model, option, index);
49
50   if(!(model->flags(index) & Qt::ItemIsUserCheckable))
51     return QStyledItemDelegate::editorEvent(event, model, option, index);
52
53   QVariant value = index.data(Qt::CheckStateRole);
54   if(!value.isValid())
55     return QStyledItemDelegate::editorEvent(event, model, option, index);
56
57   QStyleOptionViewItemV4 viewOpt(option);
58   initStyleOption(&viewOpt, index);
59
60   QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
61   QMouseEvent *me = static_cast<QMouseEvent*>(event);
62
63   if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
64     return QStyledItemDelegate::editorEvent(event, model, option, index);
65
66   Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
67   if(state == Qt::Unchecked)
68     state = Qt::PartiallyChecked;
69   else if(state == Qt::PartiallyChecked)
70     state = Qt::Checked;
71   else
72     state = Qt::Unchecked;
73   model->setData(index, state, Qt::CheckStateRole);
74   return true;
75 }
76
77
78
79
80 /*****************************************
81 * The TreeView showing the Buffers
82 *****************************************/
83 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
84 // to be on the safe side: call QTreeView's method aswell
85 BufferView::BufferView(QWidget *parent)
86   : QTreeView(parent)
87 {
88   connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(on_collapse(const QModelIndex &)));
89   connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(on_expand(const QModelIndex &)));
90
91   setSelectionMode(QAbstractItemView::ExtendedSelection);
92
93   QAbstractItemDelegate *oldDelegate = itemDelegate();
94   TristateDelegate *tristateDelegate = new TristateDelegate(this);
95   setItemDelegate(tristateDelegate);
96   delete oldDelegate;
97 }
98
99 void BufferView::init() {
100   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
101   hideColumn(1);
102   hideColumn(2);
103   setIndentation(5);
104   expandAll();
105
106   setAnimated(true);
107
108 #ifndef QT_NO_DRAGANDDROP
109   setDragEnabled(true);
110   setAcceptDrops(true);
111   setDropIndicatorShown(true);
112 #endif
113
114   setSortingEnabled(true);
115   sortByColumn(0, Qt::AscendingOrder);
116
117   // activated() fails on X11 and Qtopia at least
118 #if defined Q_WS_QWS || defined Q_WS_X11
119   connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
120 #else
121   // afaik this is better on Mac and Windows
122   connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
123 #endif
124 }
125
126 void BufferView::setModel(QAbstractItemModel *model) {
127   delete selectionModel();
128
129   QTreeView::setModel(model);
130   init();
131   // remove old Actions
132   QList<QAction *> oldactions = header()->actions();
133   foreach(QAction *action, oldactions) {
134     header()->removeAction(action);
135     action->deleteLater();
136   }
137
138   if(!model)
139     return;
140
141   QString sectionName;
142   QAction *showSection;
143   for(int i = 1; i < model->columnCount(); i++) {
144     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
145     showSection = new QAction(sectionName, header());
146     showSection->setCheckable(true);
147     showSection->setChecked(!isColumnHidden(i));
148     showSection->setProperty("column", i);
149     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
150     header()->addAction(showSection);
151   }
152
153 }
154
155 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
156   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
157   if(filter) {
158     filter->setConfig(config);
159     setConfig(config);
160     return;
161   }
162
163   if(model()) {
164     disconnect(this, 0, model(), 0);
165     disconnect(model(), 0, this, 0);
166   }
167
168   if(!model_) {
169     setModel(model_);
170   } else {
171     BufferViewFilter *filter = new BufferViewFilter(model_, config);
172     setModel(filter);
173     connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
174   }
175   setConfig(config);
176 }
177
178 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
179   if(QTreeView::selectionModel())
180     disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
181                model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
182
183   QTreeView::setSelectionModel(selectionModel);
184   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
185   if(filter) {
186     connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
187             filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
188   }
189 }
190
191 void BufferView::setConfig(BufferViewConfig *config) {
192   if(_config == config)
193     return;
194
195   if(_config) {
196     disconnect(_config, 0, this, 0);
197   }
198
199   _config = config;
200   if(config) {
201     connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
202     setRootIndexForNetworkId(config->networkId());
203   } else {
204     setRootIndex(QModelIndex());
205   }
206 }
207
208 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
209   if(!networkId.isValid() || !model()) {
210     setRootIndex(QModelIndex());
211   } else {
212     int networkCount = model()->rowCount();
213     QModelIndex child;
214     for(int i = 0; i < networkCount; i++) {
215       child = model()->index(i, 0);
216       if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
217         setRootIndex(child);
218     }
219   }
220 }
221
222 void BufferView::joinChannel(const QModelIndex &index) {
223   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
224
225   if(bufferType != BufferInfo::ChannelBuffer)
226     return;
227
228   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
229
230   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
231 }
232
233 void BufferView::keyPressEvent(QKeyEvent *event) {
234   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
235     event->accept();
236     removeSelectedBuffers();
237   }
238   QTreeView::keyPressEvent(event);
239 }
240
241 void BufferView::dropEvent(QDropEvent *event) {
242   QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
243
244   if(bufferList.count() != 1)
245     return QTreeView::dropEvent(event);
246
247   NetworkId networkId = bufferList[0].first;
248   BufferId bufferId2 = bufferList[0].second;
249
250   QModelIndex index = indexAt(event->pos());
251   if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
252     return;
253
254   if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
255     return;
256
257   if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
258     return;
259
260   BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
261   if(bufferId1 == bufferId2)
262     return;
263
264   int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
265                                   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)),
266                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
267   if(res == QMessageBox::Yes) {
268     Client::mergeBuffersPermanently(bufferId1, bufferId2);
269   }
270 }
271
272 void BufferView::removeSelectedBuffers(bool permanently) {
273   if(!config())
274     return;
275
276   BufferId bufferId;
277   QSet<BufferId> removedRows;
278   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
279     if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
280       continue;
281
282     bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
283     if(removedRows.contains(bufferId))
284       continue;
285
286     removedRows << bufferId;
287
288     if(permanently)
289       config()->requestRemoveBufferPermanently(bufferId);
290     else
291       config()->requestRemoveBuffer(bufferId);
292   }
293 }
294
295 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
296   QTreeView::rowsInserted(parent, start, end);
297
298   // ensure that newly inserted network nodes are expanded per default
299   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
300     return;
301
302   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
303     // without updating the parent the expand will have no effect... Qt Bug?
304     update(parent);
305     expand(parent);
306   }
307 }
308
309 void BufferView::on_configChanged() {
310   Q_ASSERT(model());
311
312   // expand all active networks... collapse inactive ones... unless manually changed
313   QModelIndex networkIdx;
314   NetworkId networkId;
315   for(int row = 0; row < model()->rowCount(); row++) {
316     networkIdx = model()->index(row, 0);
317     if(model()->rowCount(networkIdx) ==  0)
318       continue;
319
320     networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
321     if(!networkId.isValid())
322       continue;
323
324     update(networkIdx);
325
326     bool expandNetwork = false;
327     if(_expandedState.contains(networkId))
328       expandNetwork = _expandedState[networkId];
329     else
330       expandNetwork = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
331
332     if(expandNetwork)
333       expand(networkIdx);
334     else
335       collapse(networkIdx);
336   }
337
338   // update selection to current one
339   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
340   if(!config() || !mappedSelectionModel)
341     return;
342
343   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
344   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
345 }
346
347 void BufferView::on_collapse(const QModelIndex &index) {
348   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), false);
349 }
350
351 void BufferView::on_expand(const QModelIndex &index) {
352   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), true);
353 }
354
355 void BufferView::storeExpandedState(NetworkId networkId, bool expanded) {
356   _expandedState[networkId] = expanded;
357 }
358
359 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
360   QTreeView::dataChanged(topLeft, bottomRight);
361
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)
365     return;
366
367   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
368     QModelIndex networkIdx = topLeft.sibling(i, 0);
369     if(model()->rowCount(networkIdx) == 0)
370       continue;
371
372     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
373 #ifdef SPUTDEV
374     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
375 #else
376     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
377 #endif
378   }
379 }
380
381 void BufferView::toggleHeader(bool checked) {
382   QAction *action = qobject_cast<QAction *>(sender());
383   header()->setSectionHidden((action->property("column")).toInt(), !checked);
384 }
385
386 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
387   QModelIndex index = indexAt(event->pos());
388   if(!index.isValid())
389     index = rootIndex();
390
391   QMenu contextMenu(this);
392
393   if(index.isValid()) {
394     addActionsToMenu(&contextMenu, index);
395   }
396
397   addFilterActions(&contextMenu, index);
398
399   if(!contextMenu.actions().isEmpty())
400     contextMenu.exec(QCursor::pos());
401 }
402
403 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
404   Client::mainUi()->actionProvider()->addActions(contextMenu, index, this, "menuActionTriggered", (bool)config());
405 }
406
407 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
408   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
409   if(filter) {
410     QList<QAction *> filterActions = filter->actions(index);
411     if(!filterActions.isEmpty()) {
412       contextMenu->addSeparator();
413       foreach(QAction *action, filterActions) {
414         contextMenu->addAction(action);
415       }
416     }
417   }
418 }
419
420 void BufferView::menuActionTriggered(QAction *result) {
421   NetworkModelActionProvider::ActionType type = (NetworkModelActionProvider::ActionType)result->data().toInt();
422   switch(type) {
423     case NetworkModelActionProvider::HideBufferTemporarily:
424       removeSelectedBuffers();
425       break;
426     case NetworkModelActionProvider::HideBufferPermanently:
427       removeSelectedBuffers(true);
428       break;
429     default:
430       return;
431   }
432 }
433
434 void BufferView::wheelEvent(QWheelEvent* event) {
435   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
436     return QTreeView::wheelEvent(event);
437
438   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
439   QModelIndex currentIndex = selectionModel()->currentIndex();
440   QModelIndex resultingIndex;
441   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
442     {
443       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
444     }
445     else //if we scroll into a the parent node...
446       {
447         QModelIndex parent = currentIndex.parent();
448         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
449         if( rowDelta == -1 )
450           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
451         else
452           resultingIndex = aunt.child( 0, 0 );
453         if( !resultingIndex.isValid() )
454           return;
455       }
456   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
457   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
458
459 }
460
461 QSize BufferView::sizeHint() const {
462   return QTreeView::sizeHint();
463
464   if(!model())
465     return QTreeView::sizeHint();
466
467   if(model()->rowCount() == 0)
468     return QSize(120, 50);
469
470   int columnSize = 0;
471   for(int i = 0; i < model()->columnCount(); i++) {
472     if(!isColumnHidden(i))
473       columnSize += sizeHintForColumn(i);
474   }
475   return QSize(columnSize, 50);
476 }
477
478 // ==============================
479 //  BufferView Dock
480 // ==============================
481 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
482   : QDockWidget(config->bufferViewName(), parent)
483 {
484   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
485   toggleViewAction()->setData(config->bufferViewId());
486   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
487   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
488 }
489
490 BufferViewDock::BufferViewDock(QWidget *parent)
491   : QDockWidget(tr("All Buffers"), parent)
492 {
493   setObjectName("BufferViewDock--1");
494   toggleViewAction()->setData((int)-1);
495   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
496 }
497
498 void BufferViewDock::bufferViewRenamed(const QString &newName) {
499   setWindowTitle(newName);
500   toggleViewAction()->setText(newName);
501 }