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