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