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