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