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