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