Change shortcut for hiding the current buffer to a standard keysequence
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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 "contextmenuactionprovider.h"
39 #include "graphicalui.h"
40 #include "network.h"
41 #include "networkmodel.h"
42 #include "contextmenuactionprovider.h"
43
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)
50   : QTreeView(parent)
51 {
52   connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
53   connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
54
55   setSelectionMode(QAbstractItemView::ExtendedSelection);
56
57   QAbstractItemDelegate *oldDelegate = itemDelegate();
58   BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
59   setItemDelegate(tristateDelegate);
60   delete oldDelegate;
61 }
62
63 void BufferView::init() {
64   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
65   hideColumn(1);
66   hideColumn(2);
67   setIndentation(10);
68
69   expandAll();
70
71   header()->hide(); // nobody seems to use this anyway
72
73   // breaks with Qt 4.8
74   if(QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
75     setAnimated(true);
76
77   // FIXME This is to workaround bug #663
78   setUniformRowHeights(true);
79
80 #ifndef QT_NO_DRAGANDDROP
81   setDragEnabled(true);
82   setAcceptDrops(true);
83   setDropIndicatorShown(true);
84 #endif
85
86   setSortingEnabled(true);
87   sortByColumn(0, Qt::AscendingOrder);
88
89   // activated() fails on X11 and Qtopia at least
90 #if defined Q_WS_QWS || defined Q_WS_X11
91   disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
92   connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
93 #else
94   // afaik this is better on Mac and Windows
95   disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
96   connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
97 #endif
98 }
99
100 void BufferView::setModel(QAbstractItemModel *model) {
101   delete selectionModel();
102
103   QTreeView::setModel(model);
104   init();
105   // remove old Actions
106   QList<QAction *> oldactions = header()->actions();
107   foreach(QAction *action, oldactions) {
108     header()->removeAction(action);
109     action->deleteLater();
110   }
111
112   if(!model)
113     return;
114
115   QString sectionName;
116   QAction *showSection;
117   for(int i = 1; i < model->columnCount(); i++) {
118     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
119     showSection = new QAction(sectionName, header());
120     showSection->setCheckable(true);
121     showSection->setChecked(!isColumnHidden(i));
122     showSection->setProperty("column", i);
123     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
124     header()->addAction(showSection);
125   }
126
127   connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
128 }
129
130 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
131   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
132   if(filter) {
133     filter->setConfig(config);
134     setConfig(config);
135     return;
136   }
137
138   if(model()) {
139     disconnect(this, 0, model(), 0);
140     disconnect(model(), 0, this, 0);
141   }
142
143   if(!model_) {
144     setModel(model_);
145   } else {
146     BufferViewFilter *filter = new BufferViewFilter(model_, config);
147     setModel(filter);
148     connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
149   }
150   setConfig(config);
151 }
152
153 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
154   if(QTreeView::selectionModel())
155     disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
156                model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
157
158   QTreeView::setSelectionModel(selectionModel);
159   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
160   if(filter) {
161     connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
162             filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
163   }
164 }
165
166 void BufferView::setConfig(BufferViewConfig *config) {
167   if(_config == config)
168     return;
169
170   if(_config) {
171     disconnect(_config, 0, this, 0);
172   }
173
174   _config = config;
175   if(config) {
176     connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
177     setRootIndexForNetworkId(config->networkId());
178   } else {
179     setIndentation(10);
180     setRootIndex(QModelIndex());
181   }
182 }
183
184 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
185   if(!networkId.isValid() || !model()) {
186     setIndentation(10);
187     setRootIndex(QModelIndex());
188   } else {
189     setIndentation(5);
190     int networkCount = model()->rowCount();
191     QModelIndex child;
192     for(int i = 0; i < networkCount; i++) {
193       child = model()->index(i, 0);
194       if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
195         setRootIndex(child);
196     }
197   }
198 }
199
200 void BufferView::joinChannel(const QModelIndex &index) {
201   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
202
203   if(bufferType != BufferInfo::ChannelBuffer)
204     return;
205
206   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
207
208   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
209 }
210
211 void BufferView::keyPressEvent(QKeyEvent *event) {
212   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
213     event->accept();
214     removeSelectedBuffers();
215   }
216   QTreeView::keyPressEvent(event);
217 }
218
219 void BufferView::dropEvent(QDropEvent *event) {
220   QModelIndex index = indexAt(event->pos());
221
222   QRect indexRect = visualRect(index);
223   QPoint cursorPos = event->pos();
224
225   // check if we're really _on_ the item and not indicating a move to just above or below the item
226   const int margin = 2;
227   if(cursorPos.y() - indexRect.top() < margin
228      || indexRect.bottom() - cursorPos.y() < margin)
229     return QTreeView::dropEvent(event);
230
231   QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
232   if(bufferList.count() != 1)
233     return QTreeView::dropEvent(event);
234
235   NetworkId networkId = bufferList[0].first;
236   BufferId bufferId2 = bufferList[0].second;
237
238   if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
239     return QTreeView::dropEvent(event);
240
241   if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
242     return QTreeView::dropEvent(event);
243
244   if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
245     return QTreeView::dropEvent(event);
246
247   BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
248   if(bufferId1 == bufferId2)
249     return QTreeView::dropEvent(event);
250
251   int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
252                                   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)),
253                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
254   if(res == QMessageBox::Yes) {
255     Client::mergeBuffersPermanently(bufferId1, bufferId2);
256   }
257 }
258
259 void BufferView::removeSelectedBuffers(bool permanently) {
260   if(!config())
261     return;
262
263   BufferId bufferId;
264   QSet<BufferId> removedRows;
265   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
266     if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
267       continue;
268
269     bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
270     if(removedRows.contains(bufferId))
271       continue;
272
273     removedRows << bufferId;
274   }
275
276   foreach(BufferId bufferId, removedRows) {
277     if(permanently)
278       config()->requestRemoveBufferPermanently(bufferId);
279     else
280       config()->requestRemoveBuffer(bufferId);
281   }
282 }
283
284 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
285   QTreeView::rowsInserted(parent, start, end);
286
287   // ensure that newly inserted network nodes are expanded per default
288   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
289     return;
290
291   setExpandedState(parent);
292 }
293
294 void BufferView::on_layoutChanged() {
295   int numNets = model()->rowCount(QModelIndex());
296   for(int row = 0; row < numNets; row++) {
297     QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
298     setExpandedState(networkIdx);
299   }
300 }
301
302 void BufferView::on_configChanged() {
303   Q_ASSERT(model());
304
305   // expand all active networks... collapse inactive ones... unless manually changed
306   QModelIndex networkIdx;
307   NetworkId networkId;
308   for(int row = 0; row < model()->rowCount(); row++) {
309     networkIdx = model()->index(row, 0);
310     if(model()->rowCount(networkIdx) ==  0)
311       continue;
312
313     networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
314     if(!networkId.isValid())
315       continue;
316
317     setExpandedState(networkIdx);
318   }
319
320   if(config()) {
321     // update selection to current one
322     Client::bufferModel()->synchronizeView(this);
323   }
324 }
325
326 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
327   NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
328
329   int oldState = 0;
330   if(isExpanded(networkIdx))
331     oldState |= WasExpanded;
332   if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
333     oldState |= WasActive;
334
335   _expandedState[networkId] = oldState;
336 }
337
338 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
339   if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
340     return;
341
342   if(model()->rowCount(networkIdx) == 0)
343     return;
344
345   NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
346
347   bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
348   bool expandNetwork = networkActive;
349   if(_expandedState.contains(networkId)) {
350     int oldState = _expandedState[networkId];
351     if((bool)(oldState & WasActive) == networkActive)
352       expandNetwork = (bool)(oldState & WasExpanded);
353   }
354
355   if(expandNetwork != isExpanded(networkIdx)) {
356     update(networkIdx);
357     setExpanded(networkIdx, expandNetwork);
358   }
359   storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
360 }
361
362 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
363   QTreeView::dataChanged(topLeft, bottomRight);
364
365   // determine how many items have been changed and if any of them is a networkitem
366   // which just swichted from active to inactive or vice versa
367   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
368     return;
369
370   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
371     QModelIndex networkIdx = topLeft.sibling(i, 0);
372     setExpandedState(networkIdx);
373   }
374 }
375
376 void BufferView::toggleHeader(bool checked) {
377   QAction *action = qobject_cast<QAction *>(sender());
378   header()->setSectionHidden((action->property("column")).toInt(), !checked);
379 }
380
381 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
382   QModelIndex index = indexAt(event->pos());
383   if(!index.isValid())
384     index = rootIndex();
385
386   QMenu contextMenu(this);
387
388   if(index.isValid()) {
389     addActionsToMenu(&contextMenu, index);
390   }
391
392   addFilterActions(&contextMenu, index);
393
394   if(!contextMenu.actions().isEmpty())
395     contextMenu.exec(QCursor::pos());
396 }
397
398 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
399   QModelIndexList indexList = selectedIndexes();
400   // make sure the item we clicked on is first
401   indexList.removeAll(index);
402   indexList.prepend(index);
403
404   GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, 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   ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
422   switch(type) {
423     case ContextMenuActionProvider::HideBufferTemporarily:
424       removeSelectedBuffers();
425       break;
426     case ContextMenuActionProvider::HideBufferPermanently:
427       removeSelectedBuffers(true);
428       break;
429     default:
430       return;
431   }
432 }
433
434 void BufferView::nextBuffer() {
435   changeBuffer(Forward);
436 }
437
438 void BufferView::previousBuffer() {
439   changeBuffer(Backward);
440 }
441
442 void BufferView::changeBuffer(Direction direction) {
443   QModelIndex currentIndex = selectionModel()->currentIndex();
444   QModelIndex resultingIndex;
445
446   if(currentIndex.parent().isValid()) {
447     //If we are a child node just switch among siblings unless it's the first/last child
448     resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
449
450     if(!resultingIndex.isValid()) {
451       QModelIndex parent = currentIndex.parent();
452       if(direction == Backward)
453         resultingIndex = parent;
454       else
455         resultingIndex = parent.sibling(parent.row() + direction, 0);
456     }
457   } else {
458     //If we have a toplevel node, try and get an adjacent child
459     if(direction == Backward) {
460       QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
461       if(model()->hasChildren(newParent))
462         resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
463       else
464         resultingIndex = newParent;
465     } else {
466       if(model()->hasChildren(currentIndex))
467         resultingIndex = currentIndex.child(0, 0);
468       else
469         resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
470     }
471   }
472
473   if(!resultingIndex.isValid())
474     return;
475
476   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
477   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
478 }
479
480 void BufferView::wheelEvent(QWheelEvent* event) {
481   if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
482     return QTreeView::wheelEvent(event);
483
484   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
485   changeBuffer((Direction)rowDelta);
486 }
487
488 void BufferView::hideCurrentBuffer() {
489   QModelIndex index = selectionModel()->currentIndex();
490   if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
491     return;
492
493   BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
494
495   //The check above means we won't be looking at a network, which should always be the first row, so we can just go backwards.
496   changeBuffer(Backward);
497
498   /*if(removedRows.contains(bufferId))
499     continue;
500
501   removedRows << bufferId;*/
502   /*if(permanently)
503     config()->requestRemoveBufferPermanently(bufferId);
504   else*/
505   config()->requestRemoveBuffer(bufferId);
506 }
507
508 QSize BufferView::sizeHint() const {
509   return QTreeView::sizeHint();
510
511   if(!model())
512     return QTreeView::sizeHint();
513
514   if(model()->rowCount() == 0)
515     return QSize(120, 50);
516
517   int columnSize = 0;
518   for(int i = 0; i < model()->columnCount(); i++) {
519     if(!isColumnHidden(i))
520       columnSize += sizeHintForColumn(i);
521   }
522   return QSize(columnSize, 50);
523 }
524
525
526 // ****************************************
527 //  BufferViewDelgate
528 // ****************************************
529 class ColorsChangedEvent : public QEvent {
530 public:
531   ColorsChangedEvent() : QEvent(QEvent::User) {};
532 };
533
534 BufferViewDelegate::BufferViewDelegate(QObject *parent)
535   : QStyledItemDelegate(parent)
536 {
537 }
538
539 void BufferViewDelegate::customEvent(QEvent *event) {
540   if(event->type() != QEvent::User)
541     return;
542
543   event->accept();
544 }
545
546 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
547   if(event->type() != QEvent::MouseButtonRelease)
548     return QStyledItemDelegate::editorEvent(event, model, option, index);
549
550   if(!(model->flags(index) & Qt::ItemIsUserCheckable))
551     return QStyledItemDelegate::editorEvent(event, model, option, index);
552
553   QVariant value = index.data(Qt::CheckStateRole);
554   if(!value.isValid())
555     return QStyledItemDelegate::editorEvent(event, model, option, index);
556
557   QStyleOptionViewItemV4 viewOpt(option);
558   initStyleOption(&viewOpt, index);
559
560   QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
561   QMouseEvent *me = static_cast<QMouseEvent*>(event);
562
563   if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
564     return QStyledItemDelegate::editorEvent(event, model, option, index);
565
566   Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
567   if(state == Qt::Unchecked)
568     state = Qt::PartiallyChecked;
569   else if(state == Qt::PartiallyChecked)
570     state = Qt::Checked;
571   else
572     state = Qt::Unchecked;
573   model->setData(index, state, Qt::CheckStateRole);
574   return true;
575 }
576
577 // ==============================
578 //  BufferView Dock
579 // ==============================
580 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
581   : QDockWidget(parent),
582     _active(false),
583     _title(config->bufferViewName())
584 {
585   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
586   toggleViewAction()->setData(config->bufferViewId());
587   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
588   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
589   updateTitle();
590 }
591
592 void BufferViewDock::updateTitle() {
593   QString title = _title;
594   if(isActive())
595     title.prepend(QString::fromUtf8("• "));
596   setWindowTitle(title);
597 }
598
599 void BufferViewDock::setActive(bool active) {
600   if(active != isActive()) {
601     _active = active;
602     updateTitle();
603     if(active)
604       raise(); // for tabbed docks
605   }
606 }
607
608 void BufferViewDock::bufferViewRenamed(const QString &newName) {
609   _title = newName;
610   updateTitle();
611   toggleViewAction()->setText(newName);
612 }
613
614 int BufferViewDock::bufferViewId() const {
615   BufferView *view = bufferView();
616   if(!view)
617     return 0;
618
619   if(view->config())
620     return view->config()->bufferViewId();
621   else
622     return 0;
623 }
624
625 BufferViewConfig *BufferViewDock::config() const {
626   BufferView *view = bufferView();
627   if(!view)
628     return 0;
629   else
630     return view->config();
631 }