b5f5a573365559011f5ae2d1e0b270a7919129dd
[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 QSize BufferView::sizeHint() const {
489   return QTreeView::sizeHint();
490
491   if(!model())
492     return QTreeView::sizeHint();
493
494   if(model()->rowCount() == 0)
495     return QSize(120, 50);
496
497   int columnSize = 0;
498   for(int i = 0; i < model()->columnCount(); i++) {
499     if(!isColumnHidden(i))
500       columnSize += sizeHintForColumn(i);
501   }
502   return QSize(columnSize, 50);
503 }
504
505
506 // ****************************************
507 //  BufferViewDelgate
508 // ****************************************
509 class ColorsChangedEvent : public QEvent {
510 public:
511   ColorsChangedEvent() : QEvent(QEvent::User) {};
512 };
513
514 BufferViewDelegate::BufferViewDelegate(QObject *parent)
515   : QStyledItemDelegate(parent)
516 {
517 }
518
519 void BufferViewDelegate::customEvent(QEvent *event) {
520   if(event->type() != QEvent::User)
521     return;
522
523   event->accept();
524 }
525
526 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
527   if(event->type() != QEvent::MouseButtonRelease)
528     return QStyledItemDelegate::editorEvent(event, model, option, index);
529
530   if(!(model->flags(index) & Qt::ItemIsUserCheckable))
531     return QStyledItemDelegate::editorEvent(event, model, option, index);
532
533   QVariant value = index.data(Qt::CheckStateRole);
534   if(!value.isValid())
535     return QStyledItemDelegate::editorEvent(event, model, option, index);
536
537   QStyleOptionViewItemV4 viewOpt(option);
538   initStyleOption(&viewOpt, index);
539
540   QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
541   QMouseEvent *me = static_cast<QMouseEvent*>(event);
542
543   if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
544     return QStyledItemDelegate::editorEvent(event, model, option, index);
545
546   Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
547   if(state == Qt::Unchecked)
548     state = Qt::PartiallyChecked;
549   else if(state == Qt::PartiallyChecked)
550     state = Qt::Checked;
551   else
552     state = Qt::Unchecked;
553   model->setData(index, state, Qt::CheckStateRole);
554   return true;
555 }
556
557 // ==============================
558 //  BufferView Dock
559 // ==============================
560 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
561   : QDockWidget(parent),
562     _active(false),
563     _title(config->bufferViewName())
564 {
565   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
566   toggleViewAction()->setData(config->bufferViewId());
567   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
568   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
569   updateTitle();
570 }
571
572 void BufferViewDock::updateTitle() {
573   QString title = _title;
574   if(isActive())
575     title.prepend(QString::fromUtf8("• "));
576   setWindowTitle(title);
577 }
578
579 void BufferViewDock::setActive(bool active) {
580   if(active != isActive()) {
581     _active = active;
582     updateTitle();
583     if(active)
584       raise(); // for tabbed docks
585   }
586 }
587
588 void BufferViewDock::bufferViewRenamed(const QString &newName) {
589   _title = newName;
590   updateTitle();
591   toggleViewAction()->setText(newName);
592 }
593
594 int BufferViewDock::bufferViewId() const {
595   BufferView *view = bufferView();
596   if(!view)
597     return 0;
598
599   if(view->config())
600     return view->config()->bufferViewId();
601   else
602     return 0;
603 }
604
605 BufferViewConfig *BufferViewDock::config() const {
606   BufferView *view = bufferView();
607   if(!view)
608     return 0;
609   else
610     return view->config();
611 }