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