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