- It's now possible to select multiple buffers at once (helpfull for view customization)
[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) : QTreeView(parent) {
50   setContextMenuPolicy(Qt::CustomContextMenu);
51
52   connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
53           this, SLOT(showContextMenu(const QPoint &)));
54
55   setSelectionMode(QAbstractItemView::ExtendedSelection);
56 }
57
58 void BufferView::init() {
59   setIndentation(10);
60   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
61   hideColumn(1);
62   hideColumn(2);
63   expandAll();
64
65   setAnimated(true);
66
67 #ifndef QT_NO_DRAGANDDROP
68   setDragEnabled(true);
69   setAcceptDrops(true);
70   setDropIndicatorShown(true);
71 #endif
72
73   setSortingEnabled(true);
74   sortByColumn(0, Qt::AscendingOrder);
75 #ifndef Q_WS_QWS
76   // this is a workaround to not join channels automatically... we need a saner way to navigate for qtopia anyway though,
77   // such as mark first, activate at second click...
78   connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
79 #else
80   connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));  // Qtopia uses single click for activation
81 #endif
82 }
83
84 void BufferView::setModel(QAbstractItemModel *model) {
85   delete selectionModel();
86   if(QTreeView::model()) {
87     disconnect(QTreeView::model(), SIGNAL(layoutChanged()), this, SLOT(layoutChanged()));
88   }
89   
90   QTreeView::setModel(model);
91   init();
92   // remove old Actions
93   QList<QAction *> oldactions = header()->actions();
94   foreach(QAction *action, oldactions) {
95     header()->removeAction(action);
96     action->deleteLater();
97   }
98
99   if(!model)
100     return;
101
102   connect(model, SIGNAL(layoutChanged()), this, SLOT(layoutChanged()));
103   
104   QString sectionName;
105   QAction *showSection;
106   for(int i = 1; i < model->columnCount(); i++) {
107     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
108     showSection = new QAction(sectionName, header());
109     showSection->setCheckable(true);
110     showSection->setChecked(!isColumnHidden(i));
111     showSection->setProperty("column", i);
112     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
113     header()->addAction(showSection);
114   }
115   
116 }
117
118 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
119   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
120   if(filter) {
121     filter->setConfig(config);
122     setConfig(config);
123     return;
124   }
125
126   if(model()) {
127     disconnect(this, 0, model(), 0);
128   }
129
130   if(!model_) {
131     setModel(model_);
132   } else {
133     BufferViewFilter *filter = new BufferViewFilter(model_, config);
134     setModel(filter);
135     connect(this, SIGNAL(removeBuffer(const QModelIndex &)),
136             filter, SLOT(removeBuffer(const QModelIndex &)));
137   }
138   setConfig(config);
139 }
140
141 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
142   if(QTreeView::selectionModel())
143     disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
144                model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
145     
146   QTreeView::setSelectionModel(selectionModel);
147   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
148   if(filter) {
149     connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
150             filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
151   }
152 }
153
154 void BufferView::setConfig(BufferViewConfig *config) {
155   if(_config == config)
156     return;
157   
158   if(_config) {
159     disconnect(_config, 0, this, 0);
160   }
161
162   _config = config;
163   if(config) {
164     connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
165     setRootIndexForNetworkId(config->networkId());
166   } else {
167     setRootIndex(QModelIndex());
168   }
169 }
170
171 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
172   if(!networkId.isValid() || !model()) {
173     setRootIndex(QModelIndex());
174   } else {
175     int networkCount = model()->rowCount();
176     QModelIndex child;
177     for(int i = 0; i < networkCount; i++) {
178       child = model()->index(i, 0);
179       if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
180         setRootIndex(child);
181     }
182   }
183 }
184
185 void BufferView::joinChannel(const QModelIndex &index) {
186   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
187
188   if(bufferType != BufferInfo::ChannelBuffer)
189     return;
190
191   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
192   
193   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
194 }
195
196 void BufferView::keyPressEvent(QKeyEvent *event) {
197   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
198     event->accept();
199     removeSelectedBuffers();
200   }
201   QTreeView::keyPressEvent(event);
202 }
203
204 void BufferView::removeSelectedBuffers() {
205   QSet<int> removedRows;
206   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
207     if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType && !removedRows.contains(index.row())) {
208       removedRows << index.row();
209       emit removeBuffer(index);
210     }
211   }
212 }
213
214 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
215   QTreeView::rowsInserted(parent, start, end);
216
217   // ensure that newly inserted network nodes are expanded per default
218   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
219     return;
220   
221   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
222     // without updating the parent the expand will have no effect... Qt Bug?
223     update(parent);
224     expand(parent);
225   }
226 }
227
228 void BufferView::layoutChanged() {
229   Q_ASSERT(model());
230
231   // expand all active networks
232   QModelIndex networkIdx;
233   for(int row = 0; row < model()->rowCount(); row++) {
234     networkIdx = model()->index(row, 0);
235     update(networkIdx);
236     if(model()->rowCount(networkIdx) > 0 && model()->data(networkIdx, NetworkModel::ItemActiveRole) == true) {
237       expand(networkIdx);
238     } else {
239       collapse(networkIdx);
240     }
241   }
242
243   // update selection to current one
244   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
245   if(!config() || !mappedSelectionModel)
246     return;
247
248   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
249   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
250 }
251
252 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
253   QTreeView::dataChanged(topLeft, bottomRight);
254   
255   // determine how many items have been changed and if any of them is a networkitem
256   // which just swichted from active to inactive or vice versa
257   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
258     return;
259
260   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
261     QModelIndex networkIdx = topLeft.sibling(topLeft.row(), 0);
262     if(model()->rowCount(networkIdx) == 0)
263       continue;
264
265     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
266     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
267   }
268 }
269
270
271 void BufferView::toggleHeader(bool checked) {
272   QAction *action = qobject_cast<QAction *>(sender());
273   header()->setSectionHidden((action->property("column")).toInt(), !checked);
274 }
275
276 void BufferView::showContextMenu(const QPoint &pos) {
277   QModelIndex index = indexAt(pos);
278   if(!index.isValid()) return;
279   QMenu contextMenu(this);
280   QAction *connectNetAction = new QAction(tr("Connect"), this);
281   QAction *disconnectNetAction = new QAction(tr("Disconnect"), this);
282   QAction *joinChannelAction = new QAction(tr("Join Channel"), this);
283
284   QAction *joinBufferAction = new QAction(tr("Join"), this);
285   QAction *partBufferAction = new QAction(tr("Part"), this);
286   QAction *hideBufferAction = new QAction(tr("Remove buffers"), this);
287   hideBufferAction->setToolTip(tr("Removes the selected buffers from a custom view but leaves the buffer itself untouched"));
288   QAction *removeBufferAction = new QAction(tr("Delete buffer"), this);
289
290   QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), this);
291   QAction *hideJoinAction = hideEventsMenu->addAction(tr("Join Events"));
292   QAction *hidePartAction = hideEventsMenu->addAction(tr("Part Events"));
293   QAction *hideKillAction = hideEventsMenu->addAction(tr("Kill Events"));
294   QAction *hideQuitAction = hideEventsMenu->addAction(tr("Quit Events"));
295   QAction *hideModeAction = hideEventsMenu->addAction(tr("Mode Events"));
296   hideJoinAction->setCheckable(true);
297   hidePartAction->setCheckable(true);
298   hideKillAction->setCheckable(true);
299   hideQuitAction->setCheckable(true);
300   hideModeAction->setCheckable(true);
301   hideJoinAction->setEnabled(false);
302   hidePartAction->setEnabled(false);
303   hideKillAction->setEnabled(false);
304   hideQuitAction->setEnabled(false);
305   hideModeAction->setEnabled(false);
306
307   QAction *ignoreListAction = new QAction(tr("Ignore list"), this);
308   ignoreListAction->setEnabled(false);
309   QAction *whoBufferAction = new QAction(tr("WHO"), this);
310
311   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
312     if(index.data(NetworkModel::ItemActiveRole).toBool()) {
313       contextMenu.addAction(disconnectNetAction);
314       contextMenu.addSeparator();
315       contextMenu.addAction(joinChannelAction);
316     } else {
317       contextMenu.addAction(connectNetAction);
318     }
319   }
320
321   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
322   QString channelname = index.sibling(index.row(), 0).data().toString();
323
324   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
325     if(bufferInfo.type() != BufferInfo::ChannelBuffer && bufferInfo.type() != BufferInfo::QueryBuffer) return;
326     contextMenu.addAction(joinBufferAction);
327     contextMenu.addAction(partBufferAction);
328     if(config())
329       contextMenu.addAction(hideBufferAction);
330     contextMenu.addAction(removeBufferAction);
331     contextMenu.addMenu(hideEventsMenu);
332     contextMenu.addAction(ignoreListAction);
333     contextMenu.addAction(whoBufferAction);
334
335     if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
336       if(index.data(NetworkModel::ItemActiveRole).toBool()) {
337         removeBufferAction->setEnabled(false);
338         removeBufferAction->setToolTip("To delete the buffer, part the channel first.");
339         joinBufferAction->setVisible(false);
340         whoBufferAction->setVisible(false);
341       } else {
342         partBufferAction->setVisible(false);
343       }
344     } else {
345       joinBufferAction->setVisible(false);
346       partBufferAction->setVisible(false);
347     }
348   }
349
350   QAction *result = contextMenu.exec(QCursor::pos());
351   if(result == connectNetAction || result == disconnectNetAction) {
352     const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
353     if(!network) return;
354     if(network->connectionState() == Network::Disconnected) 
355       network->requestConnect();
356     else 
357       network->requestDisconnect();
358   } else
359   if(result == joinChannelAction) {
360     // FIXME no QInputDialog in Qtopia
361 #ifndef Q_WS_QWS
362     bool ok;
363     QString channelName = QInputDialog::getText(this, tr("Join Channel"), 
364                                                 tr("Input channel name:"),QLineEdit::Normal,
365                                                 QDir::home().dirName(), &ok);
366
367     if (ok && !channelName.isEmpty()) {
368       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
369       if(bufferInfo.isValid()) {
370         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
371       }
372     }
373 #endif
374   } else if(result == joinBufferAction) {
375     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(channelname));
376   } else if(result == partBufferAction) {
377     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(channelname));
378   } else if(result == hideBufferAction) {
379     removeSelectedBuffers();
380   } else if(result == removeBufferAction) {
381     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
382                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
383                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
384                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
385     if(res == QMessageBox::Yes) {
386       Client::removeBuffer(bufferInfo.bufferId());
387     } 
388   } else 
389   if(result == whoBufferAction) {
390     Client::instance()->userInput(bufferInfo, QString("/WHO %1").arg(channelname));
391   }
392 }
393
394 void BufferView::wheelEvent(QWheelEvent* event) {
395   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
396     return QTreeView::wheelEvent(event);
397
398   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
399   QModelIndex currentIndex = selectionModel()->currentIndex();
400   QModelIndex resultingIndex;
401   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
402     {
403       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
404     }
405     else //if we scroll into a the parent node...
406       {
407         QModelIndex parent = currentIndex.parent();
408         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
409         if( rowDelta == -1 )
410           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
411         else
412           resultingIndex = aunt.child( 0, 0 );
413         if( !resultingIndex.isValid() )
414           return;
415       }
416   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
417   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
418   
419 }
420
421
422 QSize BufferView::sizeHint() const {
423   return QTreeView::sizeHint();
424   
425   if(!model())
426     return QTreeView::sizeHint();
427
428   if(model()->rowCount() == 0)
429     return QSize(120, 50);
430
431   int columnSize = 0;
432   for(int i = 0; i < model()->columnCount(); i++) {
433     if(!isColumnHidden(i))
434       columnSize += sizeHintForColumn(i);
435   }
436   return QSize(columnSize, 50);
437 }
438
439 // ==============================
440 //  BufferView Dock
441 // ==============================
442 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
443   : QDockWidget(config->bufferViewName(), parent)
444 {
445   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
446   toggleViewAction()->setData(config->bufferViewId());
447   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
448   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
449 }
450
451 BufferViewDock::BufferViewDock(QWidget *parent)
452   : QDockWidget(tr("All Buffers"), parent)
453 {
454   setObjectName("BufferViewDock--1");
455   toggleViewAction()->setData((int)-1);
456   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
457 }
458
459 void BufferViewDock::bufferViewRenamed(const QString &newName) {
460   setWindowTitle(newName);
461   toggleViewAction()->setText(newName);
462 }