Moving branches/0.3 to 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) : 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 #ifdef SPUTDEV
267     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
268 #else
269     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
270 #endif
271   }
272 }
273
274
275 void BufferView::toggleHeader(bool checked) {
276   QAction *action = qobject_cast<QAction *>(sender());
277   header()->setSectionHidden((action->property("column")).toInt(), !checked);
278 }
279
280 void BufferView::showContextMenu(const QPoint &pos) {
281   QModelIndex index = indexAt(pos);
282   if(!index.isValid()) return;
283   QMenu contextMenu(this);
284   QAction *connectNetAction = contextMenu.addAction(tr("Connect"));
285   QAction *disconnectNetAction = contextMenu.addAction(tr("Disconnect"));
286   QAction *joinChannelAction = contextMenu.addAction(tr("Join Channel"));
287
288   QAction *joinBufferAction = contextMenu.addAction(tr("Join"));
289   QAction *partBufferAction = contextMenu.addAction(tr("Part"));
290   QAction *hideBufferAction = contextMenu.addAction(tr("Remove buffers"));
291   hideBufferAction->setToolTip(tr("Removes the selected buffers from a custom view but leaves the buffer itself untouched"));
292   QAction *removeBufferAction = contextMenu.addAction(tr("Delete buffer"));
293
294   QMenu *hideEventsMenu = contextMenu.addMenu(tr("Hide Events"));
295   QAction *hideJoinAction = hideEventsMenu->addAction(tr("Join Events"));
296   QAction *hidePartAction = hideEventsMenu->addAction(tr("Part Events"));
297   QAction *hideKillAction = hideEventsMenu->addAction(tr("Kill Events"));
298   QAction *hideQuitAction = hideEventsMenu->addAction(tr("Quit Events"));
299   QAction *hideModeAction = hideEventsMenu->addAction(tr("Mode Events"));
300   hideJoinAction->setCheckable(true);
301   hidePartAction->setCheckable(true);
302   hideKillAction->setCheckable(true);
303   hideQuitAction->setCheckable(true);
304   hideModeAction->setCheckable(true);
305   hideJoinAction->setEnabled(false);
306   hidePartAction->setEnabled(false);
307   hideKillAction->setEnabled(false);
308   hideQuitAction->setEnabled(false);
309   hideModeAction->setEnabled(false);
310
311   QAction *ignoreListAction = new QAction(tr("Ignore list"), this);
312   ignoreListAction->setEnabled(false);
313   QAction *whoBufferAction = new QAction(tr("WHO"), this);
314
315   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
316     if(index.data(NetworkModel::ItemActiveRole).toBool()) {
317       contextMenu.addAction(disconnectNetAction);
318       contextMenu.addSeparator();
319       contextMenu.addAction(joinChannelAction);
320     } else {
321       contextMenu.addAction(connectNetAction);
322     }
323   }
324
325   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
326   QString channelname = index.sibling(index.row(), 0).data().toString();
327
328   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
329     if(bufferInfo.type() != BufferInfo::ChannelBuffer && bufferInfo.type() != BufferInfo::QueryBuffer) return;
330     contextMenu.addAction(joinBufferAction);
331     contextMenu.addAction(partBufferAction);
332     if(config())
333       contextMenu.addAction(hideBufferAction);
334     contextMenu.addAction(removeBufferAction);
335     contextMenu.addMenu(hideEventsMenu);
336     contextMenu.addAction(ignoreListAction);
337     contextMenu.addAction(whoBufferAction);
338
339     if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
340       if(index.data(NetworkModel::ItemActiveRole).toBool()) {
341         removeBufferAction->setEnabled(false);
342         removeBufferAction->setToolTip("To delete the buffer, part the channel first.");
343         joinBufferAction->setVisible(false);
344         whoBufferAction->setVisible(false);
345       } else {
346         partBufferAction->setVisible(false);
347       }
348     } else {
349       joinBufferAction->setVisible(false);
350       partBufferAction->setVisible(false);
351     }
352   }
353
354   QAction *result = contextMenu.exec(QCursor::pos());
355   if(result == connectNetAction || result == disconnectNetAction) {
356     const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
357     if(!network) return;
358     if(network->connectionState() == Network::Disconnected) 
359       network->requestConnect();
360     else 
361       network->requestDisconnect();
362   } else
363   if(result == joinChannelAction) {
364     // FIXME no QInputDialog in Qtopia
365 #ifndef Q_WS_QWS
366     bool ok;
367     QString channelName = QInputDialog::getText(this, tr("Join Channel"), 
368                                                 tr("Input channel name:"),QLineEdit::Normal,
369                                                 QDir::home().dirName(), &ok);
370
371     if (ok && !channelName.isEmpty()) {
372       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
373       if(bufferInfo.isValid()) {
374         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
375       }
376     }
377 #endif
378   } else if(result == joinBufferAction) {
379     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(channelname));
380   } else if(result == partBufferAction) {
381     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(channelname));
382   } else if(result == hideBufferAction) {
383     removeSelectedBuffers();
384   } else if(result == removeBufferAction) {
385     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
386                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
387                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
388                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
389     if(res == QMessageBox::Yes) {
390       Client::removeBuffer(bufferInfo.bufferId());
391     } 
392   } else 
393   if(result == whoBufferAction) {
394     Client::instance()->userInput(bufferInfo, QString("/WHO %1").arg(channelname));
395   }
396 }
397
398 void BufferView::wheelEvent(QWheelEvent* event) {
399   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
400     return QTreeView::wheelEvent(event);
401
402   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
403   QModelIndex currentIndex = selectionModel()->currentIndex();
404   QModelIndex resultingIndex;
405   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
406     {
407       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
408     }
409     else //if we scroll into a the parent node...
410       {
411         QModelIndex parent = currentIndex.parent();
412         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
413         if( rowDelta == -1 )
414           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
415         else
416           resultingIndex = aunt.child( 0, 0 );
417         if( !resultingIndex.isValid() )
418           return;
419       }
420   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
421   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
422   
423 }
424
425
426 QSize BufferView::sizeHint() const {
427   return QTreeView::sizeHint();
428   
429   if(!model())
430     return QTreeView::sizeHint();
431
432   if(model()->rowCount() == 0)
433     return QSize(120, 50);
434
435   int columnSize = 0;
436   for(int i = 0; i < model()->columnCount(); i++) {
437     if(!isColumnHidden(i))
438       columnSize += sizeHintForColumn(i);
439   }
440   return QSize(columnSize, 50);
441 }
442
443 // ==============================
444 //  BufferView Dock
445 // ==============================
446 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
447   : QDockWidget(config->bufferViewName(), parent)
448 {
449   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
450   toggleViewAction()->setData(config->bufferViewId());
451   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
452   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
453 }
454
455 BufferViewDock::BufferViewDock(QWidget *parent)
456   : QDockWidget(tr("All Buffers"), parent)
457 {
458   setObjectName("BufferViewDock--1");
459   toggleViewAction()->setData((int)-1);
460   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
461 }
462
463 void BufferViewDock::bufferViewRenamed(const QString &newName) {
464   setWindowTitle(newName);
465   toggleViewAction()->setText(newName);
466 }