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