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