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