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