Merge pull request #136 from sandsmark/sonnet
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 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
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
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     QTreeView::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
214 void BufferView::keyPressEvent(QKeyEvent *event)
215 {
216     if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
217         event->accept();
218         removeSelectedBuffers();
219     }
220     QTreeView::keyPressEvent(event);
221 }
222
223
224 void BufferView::dropEvent(QDropEvent *event)
225 {
226     QModelIndex index = indexAt(event->pos());
227
228     QRect indexRect = visualRect(index);
229     QPoint cursorPos = event->pos();
230
231     // check if we're really _on_ the item and not indicating a move to just above or below the item
232     const int margin = 2;
233     if (cursorPos.y() - indexRect.top() < margin
234         || indexRect.bottom() - cursorPos.y() < margin)
235         return QTreeView::dropEvent(event);
236
237     QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
238     if (bufferList.count() != 1)
239         return QTreeView::dropEvent(event);
240
241     BufferId bufferId2 = bufferList[0].second;
242
243     if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
244         return QTreeView::dropEvent(event);
245
246     if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
247         return QTreeView::dropEvent(event);
248
249     BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
250     if (bufferId1 == bufferId2)
251         return QTreeView::dropEvent(event);
252
253     int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
254         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)),
255         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
256     if (res == QMessageBox::Yes) {
257         Client::mergeBuffersPermanently(bufferId1, bufferId2);
258     }
259 }
260
261
262 void BufferView::removeSelectedBuffers(bool permanently)
263 {
264     if (!config())
265         return;
266
267     BufferId bufferId;
268     QSet<BufferId> removedRows;
269     foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
270         if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
271             continue;
272
273         bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
274         if (removedRows.contains(bufferId))
275             continue;
276
277         removedRows << bufferId;
278     }
279
280     foreach(BufferId bufferId, removedRows) {
281         if (permanently)
282             config()->requestRemoveBufferPermanently(bufferId);
283         else
284             config()->requestRemoveBuffer(bufferId);
285     }
286 }
287
288
289 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
290 {
291     QTreeView::rowsInserted(parent, start, end);
292
293     // ensure that newly inserted network nodes are expanded per default
294     if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
295         return;
296
297     setExpandedState(parent);
298 }
299
300
301 void BufferView::on_layoutChanged()
302 {
303     int numNets = model()->rowCount(QModelIndex());
304     for (int row = 0; row < numNets; row++) {
305         QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
306         setExpandedState(networkIdx);
307     }
308 }
309
310
311 void BufferView::on_configChanged()
312 {
313     Q_ASSERT(model());
314
315     // expand all active networks... collapse inactive ones... unless manually changed
316     QModelIndex networkIdx;
317     NetworkId networkId;
318     for (int row = 0; row < model()->rowCount(); row++) {
319         networkIdx = model()->index(row, 0);
320         if (model()->rowCount(networkIdx) ==  0)
321             continue;
322
323         networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
324         if (!networkId.isValid())
325             continue;
326
327         setExpandedState(networkIdx);
328     }
329
330     if (config()) {
331         // update selection to current one
332         Client::bufferModel()->synchronizeView(this);
333     }
334 }
335
336
337 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
338 {
339     NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
340
341     int oldState = 0;
342     if (isExpanded(networkIdx))
343         oldState |= WasExpanded;
344     if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
345         oldState |= WasActive;
346
347     _expandedState[networkId] = oldState;
348 }
349
350
351 void BufferView::setExpandedState(const QModelIndex &networkIdx)
352 {
353     if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
354         return;
355
356     if (model()->rowCount(networkIdx) == 0)
357         return;
358
359     NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
360
361     bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
362     bool expandNetwork = networkActive;
363     if (_expandedState.contains(networkId)) {
364         int oldState = _expandedState[networkId];
365         if ((bool)(oldState & WasActive) == networkActive)
366             expandNetwork = (bool)(oldState & WasExpanded);
367     }
368
369     if (expandNetwork != isExpanded(networkIdx)) {
370         update(networkIdx);
371         setExpanded(networkIdx, expandNetwork);
372     }
373     storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
374 }
375
376 #if QT_VERSION < 0x050000
377 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
378 {
379     QTreeView::dataChanged(topLeft, bottomRight);
380 #else
381 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
382 {
383     QTreeView::dataChanged(topLeft, bottomRight, roles);
384 #endif
385
386     // determine how many items have been changed and if any of them is a networkitem
387     // which just swichted from active to inactive or vice versa
388     if (topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
389         return;
390
391     for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
392         QModelIndex networkIdx = topLeft.sibling(i, 0);
393         setExpandedState(networkIdx);
394     }
395 }
396
397
398 void BufferView::toggleHeader(bool checked)
399 {
400     QAction *action = qobject_cast<QAction *>(sender());
401     header()->setSectionHidden((action->property("column")).toInt(), !checked);
402 }
403
404
405 void BufferView::contextMenuEvent(QContextMenuEvent *event)
406 {
407     QModelIndex index = indexAt(event->pos());
408     if (!index.isValid())
409         index = rootIndex();
410
411     QMenu contextMenu(this);
412
413     if (index.isValid()) {
414         addActionsToMenu(&contextMenu, index);
415     }
416
417     addFilterActions(&contextMenu, index);
418
419     if (!contextMenu.actions().isEmpty())
420         contextMenu.exec(QCursor::pos());
421 }
422
423
424 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
425 {
426     QModelIndexList indexList = selectedIndexes();
427     // make sure the item we clicked on is first
428     indexList.removeAll(index);
429     indexList.prepend(index);
430
431     GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
432 }
433
434
435 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
436 {
437     BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
438     if (filter) {
439         QList<QAction *> filterActions = filter->actions(index);
440         if (!filterActions.isEmpty()) {
441             contextMenu->addSeparator();
442             foreach(QAction *action, filterActions) {
443                 contextMenu->addAction(action);
444             }
445         }
446     }
447 }
448
449
450 void BufferView::menuActionTriggered(QAction *result)
451 {
452     ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
453     switch (type) {
454     case ContextMenuActionProvider::HideBufferTemporarily:
455         removeSelectedBuffers();
456         break;
457     case ContextMenuActionProvider::HideBufferPermanently:
458         removeSelectedBuffers(true);
459         break;
460     default:
461         return;
462     }
463 }
464
465
466 void BufferView::nextBuffer()
467 {
468     changeBuffer(Forward);
469 }
470
471
472 void BufferView::previousBuffer()
473 {
474     changeBuffer(Backward);
475 }
476
477
478 void BufferView::changeBuffer(Direction direction)
479 {
480     QModelIndex currentIndex = selectionModel()->currentIndex();
481     QModelIndex resultingIndex;
482
483     if (currentIndex.parent().isValid()) {
484         //If we are a child node just switch among siblings unless it's the first/last child
485         resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
486
487         if (!resultingIndex.isValid()) {
488             QModelIndex parent = currentIndex.parent();
489             if (direction == Backward)
490                 resultingIndex = parent;
491             else
492                 resultingIndex = parent.sibling(parent.row() + direction, 0);
493         }
494     }
495     else {
496         //If we have a toplevel node, try and get an adjacent child
497         if (direction == Backward) {
498             QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
499             if (model()->hasChildren(newParent))
500                 resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
501             else
502                 resultingIndex = newParent;
503         }
504         else {
505             if (model()->hasChildren(currentIndex))
506                 resultingIndex = currentIndex.child(0, 0);
507             else
508                 resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
509         }
510     }
511
512     if (!resultingIndex.isValid())
513         return;
514
515     selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
516     selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
517 }
518
519
520 void BufferView::wheelEvent(QWheelEvent *event)
521 {
522     if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
523         return QTreeView::wheelEvent(event);
524
525     int rowDelta = (event->delta() > 0) ? -1 : 1;
526     changeBuffer((Direction)rowDelta);
527 }
528
529
530 void BufferView::hideCurrentBuffer()
531 {
532     QModelIndex index = selectionModel()->currentIndex();
533     if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
534         return;
535
536     BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
537
538     //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.
539     changeBuffer(Backward);
540
541     /*if(removedRows.contains(bufferId))
542       continue;
543
544     removedRows << bufferId;*/
545     /*if(permanently)
546       config()->requestRemoveBufferPermanently(bufferId);
547     else*/
548     config()->requestRemoveBuffer(bufferId);
549 }
550
551
552 QSize BufferView::sizeHint() const
553 {
554     return QTreeView::sizeHint();
555
556     if (!model())
557         return QTreeView::sizeHint();
558
559     if (model()->rowCount() == 0)
560         return QSize(120, 50);
561
562     int columnSize = 0;
563     for (int i = 0; i < model()->columnCount(); i++) {
564         if (!isColumnHidden(i))
565             columnSize += sizeHintForColumn(i);
566     }
567     return QSize(columnSize, 50);
568 }
569
570
571 // ****************************************
572 //  BufferViewDelgate
573 // ****************************************
574 class ColorsChangedEvent : public QEvent
575 {
576 public:
577     ColorsChangedEvent() : QEvent(QEvent::User) {};
578 };
579
580
581 BufferViewDelegate::BufferViewDelegate(QObject *parent)
582     : QStyledItemDelegate(parent)
583 {
584 }
585
586
587 void BufferViewDelegate::customEvent(QEvent *event)
588 {
589     if (event->type() != QEvent::User)
590         return;
591
592     event->accept();
593 }
594
595
596 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
597 {
598     if (event->type() != QEvent::MouseButtonRelease)
599         return QStyledItemDelegate::editorEvent(event, model, option, index);
600
601     if (!(model->flags(index) & Qt::ItemIsUserCheckable))
602         return QStyledItemDelegate::editorEvent(event, model, option, index);
603
604     QVariant value = index.data(Qt::CheckStateRole);
605     if (!value.isValid())
606         return QStyledItemDelegate::editorEvent(event, model, option, index);
607
608     QStyleOptionViewItemV4 viewOpt(option);
609     initStyleOption(&viewOpt, index);
610
611     QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
612     QMouseEvent *me = static_cast<QMouseEvent *>(event);
613
614     if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
615         return QStyledItemDelegate::editorEvent(event, model, option, index);
616
617     Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
618     if (state == Qt::Unchecked)
619         state = Qt::PartiallyChecked;
620     else if (state == Qt::PartiallyChecked)
621         state = Qt::Checked;
622     else
623         state = Qt::Unchecked;
624     model->setData(index, state, Qt::CheckStateRole);
625     return true;
626 }
627
628
629 // ==============================
630 //  BufferView Dock
631 // ==============================
632 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
633     : QDockWidget(parent),
634     _active(false),
635     _title(config->bufferViewName())
636 {
637     setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
638     toggleViewAction()->setData(config->bufferViewId());
639     setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
640     connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
641     updateTitle();
642 }
643
644
645 void BufferViewDock::updateTitle()
646 {
647     QString title = _title;
648     if (isActive())
649         title.prepend(QString::fromUtf8("• "));
650     setWindowTitle(title);
651 }
652
653
654 void BufferViewDock::setActive(bool active)
655 {
656     if (active != isActive()) {
657         _active = active;
658         updateTitle();
659         if (active)
660             raise();  // for tabbed docks
661     }
662 }
663
664
665 void BufferViewDock::bufferViewRenamed(const QString &newName)
666 {
667     _title = newName;
668     updateTitle();
669     toggleViewAction()->setText(newName);
670 }
671
672
673 int BufferViewDock::bufferViewId() const
674 {
675     BufferView *view = bufferView();
676     if (!view)
677         return 0;
678
679     if (view->config())
680         return view->config()->bufferViewId();
681     else
682         return 0;
683 }
684
685
686 BufferViewConfig *BufferViewDock::config() const
687 {
688     BufferView *view = bufferView();
689     if (!view)
690         return 0;
691     else
692         return view->config();
693 }