Merging branches/0.2/@r859 with trunk
[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     _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   // currently no events can be hidden -> disable actions
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   setSelectionMode(QAbstractItemView::ExtendedSelection);
83 }
84
85 void BufferView::init() {
86   setIndentation(10);
87   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
88   hideColumn(1);
89   hideColumn(2);
90   expandAll();
91
92   setAnimated(true);
93
94 #ifndef QT_NO_DRAGANDDROP
95   setDragEnabled(true);
96   setAcceptDrops(true);
97   setDropIndicatorShown(true);
98 #endif
99
100   setSortingEnabled(true);
101   sortByColumn(0, Qt::AscendingOrder);
102 #ifndef Q_WS_QWS
103   // this is a workaround to not join channels automatically... we need a saner way to navigate for qtopia anyway though,
104   // such as mark first, activate at second click...
105   connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
106 #else
107   connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));  // Qtopia uses single click for activation
108 #endif
109 }
110
111 void BufferView::setModel(QAbstractItemModel *model) {
112   delete selectionModel();
113   if(QTreeView::model()) {
114     disconnect(QTreeView::model(), SIGNAL(layoutChanged()), this, SLOT(layoutChanged()));
115   }
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   connect(model, SIGNAL(layoutChanged()), this, SLOT(layoutChanged()));
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   }
156
157   if(!model_) {
158     setModel(model_);
159   } else {
160     BufferViewFilter *filter = new BufferViewFilter(model_, config);
161     setModel(filter);
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::layoutChanged() {
267   Q_ASSERT(model());
268
269   // expand all active networks
270   QModelIndex networkIdx;
271   for(int row = 0; row < model()->rowCount(); row++) {
272     networkIdx = model()->index(row, 0);
273     update(networkIdx);
274     if(model()->rowCount(networkIdx) > 0 && model()->data(networkIdx, NetworkModel::ItemActiveRole) == true) {
275       expand(networkIdx);
276     } else {
277       collapse(networkIdx);
278     }
279   }
280
281   // update selection to current one
282   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
283   if(!config() || !mappedSelectionModel)
284     return;
285
286   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
287   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
288 }
289
290 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
291   QTreeView::dataChanged(topLeft, bottomRight);
292   
293   // determine how many items have been changed and if any of them is a networkitem
294   // which just swichted from active to inactive or vice versa
295   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
296     return;
297
298   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
299     QModelIndex networkIdx = topLeft.sibling(topLeft.row(), 0);
300     if(model()->rowCount(networkIdx) == 0)
301       continue;
302
303     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
304 #ifdef SPUTDEV
305     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
306 #else
307     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
308 #endif
309   }
310 }
311
312
313 void BufferView::toggleHeader(bool checked) {
314   QAction *action = qobject_cast<QAction *>(sender());
315   header()->setSectionHidden((action->property("column")).toInt(), !checked);
316 }
317
318 bool BufferView::checkRequirements(const QModelIndex &index, ItemActiveStates requiredActiveState) {
319   if(!index.isValid())
320     return false;
321
322 //   NetworkModel::itemTypes itemType = static_cast<NetworkModel::itemTypes>(index.data(NetworkModel::ItemTypeRole).toInt());
323 //   if(!(itemType & validItemTypes))
324 //     return false;
325
326   ItemActiveStates isActive = index.data(NetworkModel::ItemActiveRole).toBool()
327     ? ActiveState
328     : InactiveState;
329
330   if(!(isActive & requiredActiveState))
331     return false;
332
333   return true;
334 }
335
336 void BufferView::addItemToMenu(QAction &action, QMenu &menu, const QModelIndex &index, ItemActiveStates requiredActiveState) {
337   if(checkRequirements(index, requiredActiveState)) {
338     menu.addAction(&action);
339     action.setVisible(true);
340   } else {
341     action.setVisible(false);
342   }
343 }
344
345 void BufferView::addItemToMenu(QAction &action, QMenu &menu, bool condition) {
346   if(condition) {
347     menu.addAction(&action);
348     action.setVisible(true);
349   } else {
350     action.setVisible(false);
351   }
352 }
353
354
355 void BufferView::addItemToMenu(QMenu &subMenu, QMenu &menu, const QModelIndex &index, ItemActiveStates requiredActiveState) {
356   if(checkRequirements(index, requiredActiveState)) {
357     menu.addMenu(&subMenu);
358     subMenu.setVisible(true);
359   } else {
360     subMenu.setVisible(false);
361   }
362 }
363
364 void BufferView::addSeparatorToMenu(QMenu &menu, const QModelIndex &index, ItemActiveStates requiredActiveState) {
365   if(checkRequirements(index, requiredActiveState)) {
366     menu.addSeparator();
367   }
368 }
369
370 QMenu *BufferView::createHideEventsSubMenu(QMenu &menu) {
371   // QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), &menu);
372   QMenu *hideEventsMenu = menu.addMenu(tr("Hide Events"));
373   hideEventsMenu->addAction(&_hideJoinAction);
374   hideEventsMenu->addAction(&_hidePartAction);
375   hideEventsMenu->addAction(&_hideKillAction);
376   hideEventsMenu->addAction(&_hideQuitAction);
377   hideEventsMenu->addAction(&_hideModeAction);
378   return hideEventsMenu;
379 }
380
381 //void BufferView::showContextMenu(const QPoint &pos) {
382 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
383   QModelIndex index = indexAt(event->pos());
384   if(!index.isValid())
385     return;
386
387   const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
388   Q_CHECK_PTR(network);
389
390   QIcon connectionStateIcon;
391   if(network) {
392     if(network->connectionState() == Network::Initialized) {
393       connectionStateIcon = QIcon(":/22x22/actions/network-connect");
394     } else if(network->connectionState() == Network::Disconnected) {
395       connectionStateIcon = QIcon(":/22x22/actions/network-disconnect");
396     } else {
397       connectionStateIcon = QIcon(":/22x22/actions/gear");
398     }
399   }
400   
401   QMenu contextMenu(this);
402   NetworkModel::itemType itemType = static_cast<NetworkModel::itemType>(index.data(NetworkModel::ItemTypeRole).toInt());
403   
404   switch(itemType) {
405   case NetworkModel::NetworkItemType:
406     _disconnectNetAction.setIcon(connectionStateIcon);
407     _connectNetAction.setIcon(connectionStateIcon);
408     addItemToMenu(_disconnectNetAction, contextMenu, index, ActiveState);
409     addItemToMenu(_connectNetAction, contextMenu, index, InactiveState);
410     addSeparatorToMenu(contextMenu, index, ActiveState);
411     addItemToMenu(_joinChannelAction, contextMenu, index, ActiveState);
412     break;
413   case NetworkModel::BufferItemType:
414     {
415       BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
416       switch(bufferInfo.type()) {
417       case BufferInfo::ChannelBuffer:
418         addItemToMenu(_joinBufferAction, contextMenu, index, InactiveState);
419         addItemToMenu(_partBufferAction, contextMenu, index, ActiveState);
420         addItemToMenu(_hideBufferTemporarilyAction, contextMenu, (bool)config());
421         addItemToMenu(_hideBufferPermanentlyAction, contextMenu, (bool)config());
422         addItemToMenu(_removeBufferAction, contextMenu, index, InactiveState);
423         createHideEventsSubMenu(contextMenu);
424         addItemToMenu(_ignoreListAction, contextMenu);
425         break;
426       case BufferInfo::QueryBuffer:
427         addItemToMenu(_hideBufferTemporarilyAction, contextMenu, (bool)config());
428         addItemToMenu(_hideBufferPermanentlyAction, contextMenu, (bool)config());
429         addItemToMenu(_removeBufferAction, contextMenu);
430         createHideEventsSubMenu(contextMenu);
431         break;
432       default:
433         addItemToMenu(_hideBufferTemporarilyAction, contextMenu, (bool)config());
434         addItemToMenu(_hideBufferPermanentlyAction, contextMenu, (bool)config());
435         break;
436       }
437     }
438     break;
439   default:
440     return;
441   }
442   
443   if(contextMenu.actions().isEmpty())
444     return;
445   QAction *result = contextMenu.exec(QCursor::pos());
446   
447   // Handle Result
448   if(network && result == &_connectNetAction) {
449     network->requestConnect();
450     return;
451   }
452
453   if(network && result == &_disconnectNetAction) {
454     network->requestDisconnect();
455     return;
456   }
457
458   if(result == &_joinChannelAction) {
459     // FIXME no QInputDialog in Qtopia
460 #ifndef Q_WS_QWS
461     bool ok;
462     QString channelName = QInputDialog::getText(this, tr("Join Channel"), tr("Input channel name:"), QLineEdit::Normal, QString(), &ok);
463     if(ok && !channelName.isEmpty()) {
464       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
465       if(bufferInfo.isValid()) {
466         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
467       }
468     }
469 #endif
470     return;
471   }
472
473   if(result == &_joinBufferAction) {
474     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
475     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
476     return;
477   }
478
479   if(result == &_partBufferAction) {
480     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
481     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(bufferInfo.bufferName()));
482     return;
483   }
484   
485   if(result == &_hideBufferTemporarilyAction) {
486     removeSelectedBuffers();
487     return;
488   }
489
490   if(result == &_hideBufferPermanentlyAction) {
491     removeSelectedBuffers(true);
492     return;
493   }
494
495   if(result == &_removeBufferAction) {
496     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
497     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
498                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
499                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
500                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
501     if(res == QMessageBox::Yes) {
502       Client::removeBuffer(bufferInfo.bufferId());
503     }
504     return;
505   }
506
507 }
508
509 void BufferView::wheelEvent(QWheelEvent* event) {
510   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
511     return QTreeView::wheelEvent(event);
512
513   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
514   QModelIndex currentIndex = selectionModel()->currentIndex();
515   QModelIndex resultingIndex;
516   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
517     {
518       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
519     }
520     else //if we scroll into a the parent node...
521       {
522         QModelIndex parent = currentIndex.parent();
523         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
524         if( rowDelta == -1 )
525           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
526         else
527           resultingIndex = aunt.child( 0, 0 );
528         if( !resultingIndex.isValid() )
529           return;
530       }
531   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
532   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
533   
534 }
535
536
537 QSize BufferView::sizeHint() const {
538   return QTreeView::sizeHint();
539   
540   if(!model())
541     return QTreeView::sizeHint();
542
543   if(model()->rowCount() == 0)
544     return QSize(120, 50);
545
546   int columnSize = 0;
547   for(int i = 0; i < model()->columnCount(); i++) {
548     if(!isColumnHidden(i))
549       columnSize += sizeHintForColumn(i);
550   }
551   return QSize(columnSize, 50);
552 }
553
554 // ==============================
555 //  BufferView Dock
556 // ==============================
557 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
558   : QDockWidget(config->bufferViewName(), parent)
559 {
560   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
561   toggleViewAction()->setData(config->bufferViewId());
562   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
563   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
564 }
565
566 BufferViewDock::BufferViewDock(QWidget *parent)
567   : QDockWidget(tr("All Buffers"), parent)
568 {
569   setObjectName("BufferViewDock--1");
570   toggleViewAction()->setData((int)-1);
571   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
572 }
573
574 void BufferViewDock::bufferViewRenamed(const QString &newName) {
575   setWindowTitle(newName);
576   toggleViewAction()->setText(newName);
577 }