Note to self: a QSet is not ordered.
[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 "buffermodel.h"
24 #include "bufferviewfilter.h"
25 #include "buffersyncer.h"
26 #include "client.h"
27 #include "iconloader.h"
28 #include "mappedselectionmodel.h"
29 #include "network.h"
30 #include "networkmodel.h"
31
32 #include "uisettings.h"
33
34 #include <QAction>
35 #include <QFlags>
36 #include <QHeaderView>
37 #include <QInputDialog>
38 #include <QLineEdit>
39 #include <QMenu>
40 #include <QMessageBox>
41 #include <QSet>
42
43 /*****************************************
44 * The TreeView showing the Buffers
45 *****************************************/
46 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
47 // to be on the safe side: call QTreeView's method aswell
48 BufferView::BufferView(QWidget *parent)
49   : QTreeView(parent),
50     showChannelList(tr("Show Channel List"), this),
51     _connectNetAction(tr("Connect"), this),
52     _disconnectNetAction(tr("Disconnect"), this),
53     _joinChannelAction(tr("Join Channel"), this),
54
55     _joinBufferAction(tr("Join"), this),
56     _partBufferAction(tr("Part"), this),
57     _hideBufferTemporarilyAction(tr("Hide buffers"), this),
58     _hideBufferPermanentlyAction(tr("Hide buffers permanently"), this),
59     _removeBufferAction(tr("Delete buffer"), this),
60     _ignoreListAction(tr("Ignore list"), this),
61
62     _hideJoinAction(tr("Join Events"), this),
63     _hidePartAction(tr("Part Events"), this),
64     _hideKillAction(tr("Kill Events"), this),
65     _hideQuitAction(tr("Quit Events"), this),
66     _hideModeAction(tr("Mode Events"), this)
67
68 {
69   _hideJoinAction.setCheckable(true);
70   _hidePartAction.setCheckable(true);
71   _hideKillAction.setCheckable(true);
72   _hideQuitAction.setCheckable(true);
73   _hideModeAction.setCheckable(true);
74   _hideJoinAction.setEnabled(false);
75   _hidePartAction.setEnabled(false);
76   _ignoreListAction.setEnabled(false);
77   _hideKillAction.setEnabled(false);
78   _hideQuitAction.setEnabled(false);
79   _hideModeAction.setEnabled(false);
80
81   showChannelList.setIcon(SmallIcon("format-list-unordered"));
82
83   connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(on_collapse(const QModelIndex &)));
84   connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(on_expand(const QModelIndex &)));
85
86   setSelectionMode(QAbstractItemView::ExtendedSelection);
87 }
88
89 void BufferView::init() {
90   setIndentation(10);
91   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
92   hideColumn(1);
93   hideColumn(2);
94   expandAll();
95
96   setAnimated(true);
97
98 #ifndef QT_NO_DRAGANDDROP
99   setDragEnabled(true);
100   setAcceptDrops(true);
101   setDropIndicatorShown(true);
102 #endif
103
104   setSortingEnabled(true);
105   sortByColumn(0, Qt::AscendingOrder);
106 #ifndef Q_WS_QWS
107   // this is a workaround to not join channels automatically... we need a saner way to navigate for qtopia anyway though,
108   // such as mark first, activate at second click...
109   connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
110 #else
111   connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));  // Qtopia uses single click for activation
112 #endif
113 }
114
115 void BufferView::setModel(QAbstractItemModel *model) {
116   delete selectionModel();
117
118   QTreeView::setModel(model);
119   init();
120   // remove old Actions
121   QList<QAction *> oldactions = header()->actions();
122   foreach(QAction *action, oldactions) {
123     header()->removeAction(action);
124     action->deleteLater();
125   }
126
127   if(!model)
128     return;
129
130   QString sectionName;
131   QAction *showSection;
132   for(int i = 1; i < model->columnCount(); i++) {
133     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
134     showSection = new QAction(sectionName, header());
135     showSection->setCheckable(true);
136     showSection->setChecked(!isColumnHidden(i));
137     showSection->setProperty("column", i);
138     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
139     header()->addAction(showSection);
140   }
141
142 }
143
144 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
145   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
146   if(filter) {
147     filter->setConfig(config);
148     setConfig(config);
149     return;
150   }
151
152   if(model()) {
153     disconnect(this, 0, model(), 0);
154     disconnect(model(), 0, this, 0);
155   }
156
157   if(!model_) {
158     setModel(model_);
159   } else {
160     BufferViewFilter *filter = new BufferViewFilter(model_, config);
161     setModel(filter);
162     connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
163   }
164   setConfig(config);
165 }
166
167 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
168   if(QTreeView::selectionModel())
169     disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
170                model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
171
172   QTreeView::setSelectionModel(selectionModel);
173   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
174   if(filter) {
175     connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
176             filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
177   }
178 }
179
180 void BufferView::setConfig(BufferViewConfig *config) {
181   if(_config == config)
182     return;
183
184   if(_config) {
185     disconnect(_config, 0, this, 0);
186   }
187
188   _config = config;
189   if(config) {
190     connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
191     setRootIndexForNetworkId(config->networkId());
192   } else {
193     setRootIndex(QModelIndex());
194   }
195 }
196
197 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
198   if(!networkId.isValid() || !model()) {
199     setRootIndex(QModelIndex());
200   } else {
201     int networkCount = model()->rowCount();
202     QModelIndex child;
203     for(int i = 0; i < networkCount; i++) {
204       child = model()->index(i, 0);
205       if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
206         setRootIndex(child);
207     }
208   }
209 }
210
211 void BufferView::joinChannel(const QModelIndex &index) {
212   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
213
214   if(bufferType != BufferInfo::ChannelBuffer)
215     return;
216
217   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
218
219   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
220 }
221
222 void BufferView::keyPressEvent(QKeyEvent *event) {
223   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
224     event->accept();
225     removeSelectedBuffers();
226   }
227   QTreeView::keyPressEvent(event);
228 }
229
230 void BufferView::removeSelectedBuffers(bool permanently) {
231   if(!config())
232     return;
233
234   BufferId bufferId;
235   QSet<BufferId> removedRows;
236   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
237     if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
238       continue;
239
240     bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
241     if(removedRows.contains(bufferId))
242       continue;
243
244     removedRows << bufferId;
245
246     if(permanently)
247       config()->requestRemoveBufferPermanently(bufferId);
248     else
249       config()->requestRemoveBuffer(bufferId);
250   }
251 }
252
253 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
254   QTreeView::rowsInserted(parent, start, end);
255
256   // ensure that newly inserted network nodes are expanded per default
257   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
258     return;
259
260   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
261     // without updating the parent the expand will have no effect... Qt Bug?
262     update(parent);
263     expand(parent);
264   }
265 }
266
267 void BufferView::on_configChanged() {
268   Q_ASSERT(model());
269
270   // expand all active networks... collapse inactive ones... unless manually changed
271   QModelIndex networkIdx;
272   NetworkId networkId;
273   for(int row = 0; row < model()->rowCount(); row++) {
274     networkIdx = model()->index(row, 0);
275     if(model()->rowCount(networkIdx) ==  0)
276       continue;
277
278     networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
279     if(!networkId.isValid())
280       continue;
281
282     update(networkIdx);
283
284     bool expandNetwork = false;
285     if(_expandedState.contains(networkId))
286       expandNetwork = _expandedState[networkId];
287     else
288       expandNetwork = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
289
290     if(expandNetwork)
291       expand(networkIdx);
292     else
293       collapse(networkIdx);
294   }
295
296   // update selection to current one
297   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
298   if(!config() || !mappedSelectionModel)
299     return;
300
301   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
302   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
303 }
304
305 void BufferView::on_collapse(const QModelIndex &index) {
306   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), false);
307 }
308
309 void BufferView::on_expand(const QModelIndex &index) {
310   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), true);
311 }
312
313 void BufferView::storeExpandedState(NetworkId networkId, bool expanded) {
314   _expandedState[networkId] = expanded;
315 }
316
317 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
318   QTreeView::dataChanged(topLeft, bottomRight);
319
320   // determine how many items have been changed and if any of them is a networkitem
321   // which just swichted from active to inactive or vice versa
322   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
323     return;
324
325   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
326     QModelIndex networkIdx = topLeft.sibling(i, 0);
327     if(model()->rowCount(networkIdx) == 0)
328       continue;
329
330     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
331 #ifdef SPUTDEV
332     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
333 #else
334     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
335 #endif
336   }
337 }
338
339 void BufferView::toggleHeader(bool checked) {
340   QAction *action = qobject_cast<QAction *>(sender());
341   header()->setSectionHidden((action->property("column")).toInt(), !checked);
342 }
343
344 bool BufferView::checkRequirements(const QModelIndex &index, ItemActiveStates requiredActiveState) {
345   if(!index.isValid())
346     return false;
347
348   ItemActiveStates isActive = index.data(NetworkModel::ItemActiveRole).toBool()
349     ? ActiveState
350     : InactiveState;
351
352   if(!(isActive & requiredActiveState))
353     return false;
354
355   return true;
356 }
357
358 void BufferView::addItemToMenu(QAction &action, QMenu &menu, const QModelIndex &index, ItemActiveStates requiredActiveState) {
359   if(checkRequirements(index, requiredActiveState)) {
360     menu.addAction(&action);
361     action.setVisible(true);
362   } else {
363     action.setVisible(false);
364   }
365 }
366
367 void BufferView::addItemToMenu(QAction &action, QMenu &menu, bool condition) {
368   if(condition) {
369     menu.addAction(&action);
370     action.setVisible(true);
371   } else {
372     action.setVisible(false);
373   }
374 }
375
376
377 void BufferView::addItemToMenu(QMenu &subMenu, QMenu &menu, const QModelIndex &index, ItemActiveStates requiredActiveState) {
378   if(checkRequirements(index, requiredActiveState)) {
379     menu.addMenu(&subMenu);
380     subMenu.setVisible(true);
381   } else {
382     subMenu.setVisible(false);
383   }
384 }
385
386 void BufferView::addSeparatorToMenu(QMenu &menu, const QModelIndex &index, ItemActiveStates requiredActiveState) {
387   if(checkRequirements(index, requiredActiveState)) {
388     menu.addSeparator();
389   }
390 }
391
392 QMenu *BufferView::createHideEventsSubMenu(QMenu &menu) {
393   // QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), &menu);
394   QMenu *hideEventsMenu = menu.addMenu(tr("Hide Events"));
395   hideEventsMenu->addAction(&_hideJoinAction);
396   hideEventsMenu->addAction(&_hidePartAction);
397   hideEventsMenu->addAction(&_hideKillAction);
398   hideEventsMenu->addAction(&_hideQuitAction);
399   hideEventsMenu->addAction(&_hideModeAction);
400   return hideEventsMenu;
401 }
402
403 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
404   QModelIndex index = indexAt(event->pos());
405   if(!index.isValid())
406     index = rootIndex();
407   if(!index.isValid())
408     return;
409
410   const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
411   Q_CHECK_PTR(network);
412
413   QPixmap connectionStateIcon;
414   if(network) {
415     if(network->connectionState() == Network::Initialized) {
416       connectionStateIcon = SmallIcon("network-connect");
417     } else if(network->connectionState() == Network::Disconnected) {
418       connectionStateIcon = SmallIcon("network-disconnect");
419     } else {
420       connectionStateIcon = SmallIcon("network-wired");  // FIXME network-connecting
421     }
422   }
423
424   QMenu contextMenu(this);
425   NetworkModel::itemType itemType = static_cast<NetworkModel::itemType>(index.data(NetworkModel::ItemTypeRole).toInt());
426
427   switch(itemType) {
428   case NetworkModel::NetworkItemType:
429     showChannelList.setData(index.data(NetworkModel::NetworkIdRole));
430     _disconnectNetAction.setIcon(connectionStateIcon);
431     _connectNetAction.setIcon(connectionStateIcon);
432     addItemToMenu(showChannelList, contextMenu, index, ActiveState);
433     addItemToMenu(_disconnectNetAction, contextMenu, network->connectionState() != Network::Disconnected);
434     addItemToMenu(_connectNetAction, contextMenu, network->connectionState() == Network::Disconnected);
435     addSeparatorToMenu(contextMenu, index, ActiveState);
436     addItemToMenu(_joinChannelAction, contextMenu, index, ActiveState);
437     break;
438   case NetworkModel::BufferItemType:
439     {
440       BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
441       switch(bufferInfo.type()) {
442       case BufferInfo::ChannelBuffer:
443         addItemToMenu(_joinBufferAction, contextMenu, index, InactiveState);
444         addItemToMenu(_partBufferAction, contextMenu, index, ActiveState);
445         addItemToMenu(_hideBufferTemporarilyAction, contextMenu, (bool)config());
446         addItemToMenu(_hideBufferPermanentlyAction, contextMenu, (bool)config());
447         addItemToMenu(_removeBufferAction, contextMenu, index, InactiveState);
448         createHideEventsSubMenu(contextMenu);
449         addItemToMenu(_ignoreListAction, contextMenu);
450         break;
451       case BufferInfo::QueryBuffer:
452         addItemToMenu(_hideBufferTemporarilyAction, contextMenu, (bool)config());
453         addItemToMenu(_hideBufferPermanentlyAction, contextMenu, (bool)config());
454         addItemToMenu(_removeBufferAction, contextMenu);
455         createHideEventsSubMenu(contextMenu);
456         break;
457       default:
458         addItemToMenu(_hideBufferTemporarilyAction, contextMenu, (bool)config());
459         addItemToMenu(_hideBufferPermanentlyAction, contextMenu, (bool)config());
460         break;
461       }
462     }
463     break;
464   default:
465     return;
466   }
467
468   if(contextMenu.actions().isEmpty())
469     return;
470   QAction *result = contextMenu.exec(QCursor::pos());
471
472   // Handle Result
473   if(network && result == &_connectNetAction) {
474     network->requestConnect();
475     return;
476   }
477
478   if(network && result == &_disconnectNetAction) {
479     network->requestDisconnect();
480     return;
481   }
482
483   if(result == &_joinChannelAction) {
484     // FIXME no QInputDialog in Qtopia
485 #ifndef Q_WS_QWS
486     bool ok;
487     QString channelName = QInputDialog::getText(this, tr("Join Channel"), tr("Input channel name:"), QLineEdit::Normal, QString(), &ok);
488     if(ok && !channelName.isEmpty()) {
489       Client::instance()->userInput(BufferInfo::fakeStatusBuffer(index.data(NetworkModel::NetworkIdRole).value<NetworkId>()), QString("/J %1").arg(channelName));
490     }
491 #endif
492     return;
493   }
494
495   if(result == &_joinBufferAction) {
496     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
497     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
498     return;
499   }
500
501   if(result == &_partBufferAction) {
502     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
503     Client::instance()->userInput(bufferInfo, QString("/PART"));
504     return;
505   }
506
507   if(result == &_hideBufferTemporarilyAction) {
508     removeSelectedBuffers();
509     return;
510   }
511
512   if(result == &_hideBufferPermanentlyAction) {
513     removeSelectedBuffers(true);
514     return;
515   }
516
517   if(result == &_removeBufferAction) {
518     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
519     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
520                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
521                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
522                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
523     if(res == QMessageBox::Yes) {
524       Client::removeBuffer(bufferInfo.bufferId());
525     }
526     return;
527   }
528
529 }
530
531 void BufferView::wheelEvent(QWheelEvent* event) {
532   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
533     return QTreeView::wheelEvent(event);
534
535   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
536   QModelIndex currentIndex = selectionModel()->currentIndex();
537   QModelIndex resultingIndex;
538   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
539     {
540       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
541     }
542     else //if we scroll into a the parent node...
543       {
544         QModelIndex parent = currentIndex.parent();
545         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
546         if( rowDelta == -1 )
547           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
548         else
549           resultingIndex = aunt.child( 0, 0 );
550         if( !resultingIndex.isValid() )
551           return;
552       }
553   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
554   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
555
556 }
557
558
559 QSize BufferView::sizeHint() const {
560   return QTreeView::sizeHint();
561
562   if(!model())
563     return QTreeView::sizeHint();
564
565   if(model()->rowCount() == 0)
566     return QSize(120, 50);
567
568   int columnSize = 0;
569   for(int i = 0; i < model()->columnCount(); i++) {
570     if(!isColumnHidden(i))
571       columnSize += sizeHintForColumn(i);
572   }
573   return QSize(columnSize, 50);
574 }
575
576 // ==============================
577 //  BufferView Dock
578 // ==============================
579 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
580   : QDockWidget(config->bufferViewName(), parent)
581 {
582   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
583   toggleViewAction()->setData(config->bufferViewId());
584   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
585   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
586 }
587
588 BufferViewDock::BufferViewDock(QWidget *parent)
589   : QDockWidget(tr("All Buffers"), parent)
590 {
591   setObjectName("BufferViewDock--1");
592   toggleViewAction()->setData((int)-1);
593   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
594 }
595
596 void BufferViewDock::bufferViewRenamed(const QString &newName) {
597   setWindowTitle(newName);
598   toggleViewAction()->setText(newName);
599 }