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