Merging r732:766 from trunk to branches/0.3.
[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      && (Global::SPUTDEV || 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(Global::SPUTDEV) {
208       if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
209     } else {
210       if(isExpanded(networkIdx) != isActive)
211         setExpanded(networkIdx, isActive);
212     }
213   }
214 }
215
216
217 void BufferView::toggleHeader(bool checked) {
218   QAction *action = qobject_cast<QAction *>(sender());
219   header()->setSectionHidden((action->property("column")).toInt(), !checked);
220 }
221
222 void BufferView::showContextMenu(const QPoint &pos) {
223   QModelIndex index = indexAt(pos);
224   if(!index.isValid()) return;
225   QMenu contextMenu(this);
226   QAction *connectNetAction = new QAction(tr("Connect"), this);
227   QAction *disconnectNetAction = new QAction(tr("Disconnect"), this);
228   QAction *joinChannelAction = new QAction(tr("Join Channel"), this);
229
230   QAction *joinBufferAction = new QAction(tr("Join"), this);
231   QAction *partBufferAction = new QAction(tr("Part"), this);
232   QAction *removeBufferAction = new QAction(tr("Delete buffer"), this);
233
234   QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), this);
235   QAction *hideJoinAction = hideEventsMenu->addAction(tr("Join Events"));
236   QAction *hidePartAction = hideEventsMenu->addAction(tr("Part Events"));
237   QAction *hideKillAction = hideEventsMenu->addAction(tr("Kill Events"));
238   QAction *hideQuitAction = hideEventsMenu->addAction(tr("Quit Events"));
239   QAction *hideModeAction = hideEventsMenu->addAction(tr("Mode Events"));
240   hideJoinAction->setCheckable(true);
241   hidePartAction->setCheckable(true);
242   hideKillAction->setCheckable(true);
243   hideQuitAction->setCheckable(true);
244   hideModeAction->setCheckable(true);
245   hideJoinAction->setEnabled(false);
246   hidePartAction->setEnabled(false);
247   hideKillAction->setEnabled(false);
248   hideQuitAction->setEnabled(false);
249   hideModeAction->setEnabled(false);
250
251   QAction *ignoreListAction = new QAction(tr("Ignore list"), this);
252   ignoreListAction->setEnabled(false);
253   QAction *whoBufferAction = new QAction(tr("WHO"), this);
254
255   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
256     if(index.data(NetworkModel::ItemActiveRole).toBool()) {
257       contextMenu.addAction(disconnectNetAction);
258       contextMenu.addSeparator();
259       contextMenu.addAction(joinChannelAction);
260     } else {
261       contextMenu.addAction(connectNetAction);
262     }
263   }
264
265   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
266   QString channelname = index.sibling(index.row(), 0).data().toString();
267
268   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
269     if(bufferInfo.type() != BufferInfo::ChannelBuffer && bufferInfo.type() != BufferInfo::QueryBuffer) return;
270     contextMenu.addAction(joinBufferAction);
271     contextMenu.addAction(partBufferAction);
272     contextMenu.addAction(removeBufferAction);
273     contextMenu.addMenu(hideEventsMenu);
274     contextMenu.addAction(ignoreListAction);
275     contextMenu.addAction(whoBufferAction);
276
277     if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
278       if(index.data(NetworkModel::ItemActiveRole).toBool()) {
279         removeBufferAction->setEnabled(false);
280         removeBufferAction->setToolTip("To delete the buffer, part the channel first.");
281         joinBufferAction->setVisible(false);
282         whoBufferAction->setVisible(false);
283       } else {
284         partBufferAction->setVisible(false);
285       }
286     } else {
287       joinBufferAction->setVisible(false);
288       partBufferAction->setVisible(false);
289     }
290   }
291
292   QAction *result = contextMenu.exec(QCursor::pos());
293   if(result == connectNetAction || result == disconnectNetAction) {
294     const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
295     if(!network) return;
296     if(network->connectionState() == Network::Disconnected) 
297       network->requestConnect();
298     else 
299       network->requestDisconnect();
300   } else
301   if(result == joinChannelAction) {
302     // FIXME no QInputDialog in Qtopia
303 #ifndef Q_WS_QWS
304     bool ok;
305     QString channelName = QInputDialog::getText(this, tr("Join Channel"), 
306                                                 tr("Input channel name:"),QLineEdit::Normal,
307                                                 QDir::home().dirName(), &ok);
308
309     if (ok && !channelName.isEmpty()) {
310       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
311       if(bufferInfo.isValid()) {
312         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
313       }
314     }
315 #endif
316   } else
317   if(result == joinBufferAction) {
318     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(channelname));
319   } else
320   if(result == partBufferAction) {
321     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(channelname));
322   } else
323   if(result == removeBufferAction) {
324     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
325                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
326                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
327                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
328     if(res == QMessageBox::Yes) {
329       Client::removeBuffer(bufferInfo.bufferId());
330     } 
331   } else 
332   if(result == whoBufferAction) {
333     Client::instance()->userInput(bufferInfo, QString("/WHO %1").arg(channelname));
334   }
335 }
336
337 void BufferView::wheelEvent(QWheelEvent* event) {
338   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
339     return QTreeView::wheelEvent(event);
340
341   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
342   QModelIndex currentIndex = selectionModel()->currentIndex();
343   QModelIndex resultingIndex;
344   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
345     {
346       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
347     }
348     else //if we scroll into a the parent node...
349       {
350         QModelIndex parent = currentIndex.parent();
351         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
352         if( rowDelta == -1 )
353           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
354         else
355           resultingIndex = aunt.child( 0, 0 );
356         if( !resultingIndex.isValid() )
357           return;
358       }
359   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
360   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
361   
362 }
363
364
365 QSize BufferView::sizeHint() const {
366   return QTreeView::sizeHint();
367   
368   if(!model())
369     return QTreeView::sizeHint();
370
371   if(model()->rowCount() == 0)
372     return QSize(120, 50);
373
374   int columnSize = 0;
375   for(int i = 0; i < model()->columnCount(); i++) {
376     if(!isColumnHidden(i))
377       columnSize += sizeHintForColumn(i);
378   }
379   return QSize(columnSize, 50);
380 }
381
382 // ==============================
383 //  BufferView Dock
384 // ==============================
385 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
386   : QDockWidget(config->bufferViewName(), parent)
387 {
388   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
389   toggleViewAction()->setData(config->bufferViewId());
390   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
391   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
392 }
393
394 BufferViewDock::BufferViewDock(QWidget *parent)
395   : QDockWidget(tr("All Buffers"), parent)
396 {
397   setObjectName("BufferViewDock--1");
398   toggleViewAction()->setData((int)-1);
399   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
400 }
401
402 void BufferViewDock::bufferViewRenamed(const QString &newName) {
403   setWindowTitle(newName);
404   toggleViewAction()->setText(newName);
405 }