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