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