active and inactive networks are now expanded and collapsed properly
[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(layoutChanged()));
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(layoutChanged()));
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 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
191   QTreeView::rowsInserted(parent, start, end);
192
193   // ensure that newly inserted network nodes are expanded per default
194   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
195     return;
196   
197   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
198     // without updating the parent the expand will have no effect... Qt Bug?
199     update(parent);
200     expand(parent);
201   }
202 }
203
204 void BufferView::layoutChanged() {
205   Q_ASSERT(model());
206
207   // expand all active networks
208   QModelIndex networkIdx;
209   for(int row = 0; row < model()->rowCount(); row++) {
210     networkIdx = model()->index(row, 0);
211     update(networkIdx);
212     if(model()->rowCount(networkIdx) > 0 && model()->data(networkIdx, NetworkModel::ItemActiveRole) == true) {
213       expand(networkIdx);
214     } else {
215       collapse(networkIdx);
216     }
217   }
218
219   // update selection to current one
220   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
221   if(!config() || !mappedSelectionModel)
222     return;
223
224   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
225   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
226 }
227
228 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
229   QTreeView::dataChanged(topLeft, bottomRight);
230   
231   // determine how many items have been changed and if any of them is a networkitem
232   // which just swichted from active to inactive or vice versa
233   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
234     return;
235
236   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
237     QModelIndex networkIdx = topLeft.sibling(topLeft.row(), 0);
238     if(model()->rowCount(networkIdx) == 0)
239       continue;
240
241     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
242     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
243   }
244 }
245
246
247 void BufferView::toggleHeader(bool checked) {
248   QAction *action = qobject_cast<QAction *>(sender());
249   header()->setSectionHidden((action->property("column")).toInt(), !checked);
250 }
251
252 void BufferView::showContextMenu(const QPoint &pos) {
253   QModelIndex index = indexAt(pos);
254   if(!index.isValid()) return;
255   QMenu contextMenu(this);
256   QAction *connectNetAction = new QAction(tr("Connect"), this);
257   QAction *disconnectNetAction = new QAction(tr("Disconnect"), this);
258   QAction *joinChannelAction = new QAction(tr("Join Channel"), this);
259
260   QAction *joinBufferAction = new QAction(tr("Join"), this);
261   QAction *partBufferAction = new QAction(tr("Part"), this);
262   QAction *removeBufferAction = new QAction(tr("Delete buffer"), this);
263
264   QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), this);
265   QAction *hideJoinAction = hideEventsMenu->addAction(tr("Join Events"));
266   QAction *hidePartAction = hideEventsMenu->addAction(tr("Part Events"));
267   QAction *hideKillAction = hideEventsMenu->addAction(tr("Kill Events"));
268   QAction *hideQuitAction = hideEventsMenu->addAction(tr("Quit Events"));
269   QAction *hideModeAction = hideEventsMenu->addAction(tr("Mode Events"));
270   hideJoinAction->setCheckable(true);
271   hidePartAction->setCheckable(true);
272   hideKillAction->setCheckable(true);
273   hideQuitAction->setCheckable(true);
274   hideModeAction->setCheckable(true);
275   hideJoinAction->setEnabled(false);
276   hidePartAction->setEnabled(false);
277   hideKillAction->setEnabled(false);
278   hideQuitAction->setEnabled(false);
279   hideModeAction->setEnabled(false);
280
281   QAction *ignoreListAction = new QAction(tr("Ignore list"), this);
282   ignoreListAction->setEnabled(false);
283   QAction *whoBufferAction = new QAction(tr("WHO"), this);
284
285   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
286     if(index.data(NetworkModel::ItemActiveRole).toBool()) {
287       contextMenu.addAction(disconnectNetAction);
288       contextMenu.addSeparator();
289       contextMenu.addAction(joinChannelAction);
290     } else {
291       contextMenu.addAction(connectNetAction);
292     }
293   }
294
295   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
296   QString channelname = index.sibling(index.row(), 0).data().toString();
297
298   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
299     if(bufferInfo.type() != BufferInfo::ChannelBuffer && bufferInfo.type() != BufferInfo::QueryBuffer) return;
300     contextMenu.addAction(joinBufferAction);
301     contextMenu.addAction(partBufferAction);
302     contextMenu.addAction(removeBufferAction);
303     contextMenu.addMenu(hideEventsMenu);
304     contextMenu.addAction(ignoreListAction);
305     contextMenu.addAction(whoBufferAction);
306
307     if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
308       if(index.data(NetworkModel::ItemActiveRole).toBool()) {
309         removeBufferAction->setEnabled(false);
310         removeBufferAction->setToolTip("To delete the buffer, part the channel first.");
311         joinBufferAction->setVisible(false);
312         whoBufferAction->setVisible(false);
313       } else {
314         partBufferAction->setVisible(false);
315       }
316     } else {
317       joinBufferAction->setVisible(false);
318       partBufferAction->setVisible(false);
319     }
320   }
321
322   QAction *result = contextMenu.exec(QCursor::pos());
323   if(result == connectNetAction || result == disconnectNetAction) {
324     const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
325     if(!network) return;
326     if(network->connectionState() == Network::Disconnected) 
327       network->requestConnect();
328     else 
329       network->requestDisconnect();
330   } else
331   if(result == joinChannelAction) {
332     // FIXME no QInputDialog in Qtopia
333 #ifndef Q_WS_QWS
334     bool ok;
335     QString channelName = QInputDialog::getText(this, tr("Join Channel"), 
336                                                 tr("Input channel name:"),QLineEdit::Normal,
337                                                 QDir::home().dirName(), &ok);
338
339     if (ok && !channelName.isEmpty()) {
340       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
341       if(bufferInfo.isValid()) {
342         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
343       }
344     }
345 #endif
346   } else
347   if(result == joinBufferAction) {
348     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(channelname));
349   } else
350   if(result == partBufferAction) {
351     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(channelname));
352   } else
353   if(result == removeBufferAction) {
354     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
355                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
356                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
357                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
358     if(res == QMessageBox::Yes) {
359       Client::removeBuffer(bufferInfo.bufferId());
360     } 
361   } else 
362   if(result == whoBufferAction) {
363     Client::instance()->userInput(bufferInfo, QString("/WHO %1").arg(channelname));
364   }
365 }
366
367 void BufferView::wheelEvent(QWheelEvent* event) {
368   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
369     return QTreeView::wheelEvent(event);
370
371   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
372   QModelIndex currentIndex = selectionModel()->currentIndex();
373   QModelIndex resultingIndex;
374   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
375     {
376       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
377     }
378     else //if we scroll into a the parent node...
379       {
380         QModelIndex parent = currentIndex.parent();
381         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
382         if( rowDelta == -1 )
383           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
384         else
385           resultingIndex = aunt.child( 0, 0 );
386         if( !resultingIndex.isValid() )
387           return;
388       }
389   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
390   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
391   
392 }
393
394
395 QSize BufferView::sizeHint() const {
396   return QTreeView::sizeHint();
397   
398   if(!model())
399     return QTreeView::sizeHint();
400
401   if(model()->rowCount() == 0)
402     return QSize(120, 50);
403
404   int columnSize = 0;
405   for(int i = 0; i < model()->columnCount(); i++) {
406     if(!isColumnHidden(i))
407       columnSize += sizeHintForColumn(i);
408   }
409   return QSize(columnSize, 50);
410 }
411
412 // ==============================
413 //  BufferView Dock
414 // ==============================
415 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
416   : QDockWidget(config->bufferViewName(), parent)
417 {
418   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
419   toggleViewAction()->setData(config->bufferViewId());
420   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
421   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
422 }
423
424 BufferViewDock::BufferViewDock(QWidget *parent)
425   : QDockWidget(tr("All Buffers"), parent)
426 {
427   setObjectName("BufferViewDock--1");
428   toggleViewAction()->setData((int)-1);
429   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
430 }
431
432 void BufferViewDock::bufferViewRenamed(const QString &newName) {
433   setWindowTitle(newName);
434   toggleViewAction()->setText(newName);
435 }