introducing query merging (per drag & drop). needs a core update
[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 <QAction>
22 #include <QFlags>
23 #include <QHeaderView>
24 #include <QLineEdit>
25 #include <QMenu>
26 #include <QMessageBox>
27 #include <QSet>
28
29 #include "bufferview.h"
30
31 #include "action.h"
32 #include "buffermodel.h"
33 #include "bufferviewfilter.h"
34 #include "buffersettings.h"
35 #include "buffersyncer.h"
36 #include "client.h"
37 #include "iconloader.h"
38 #include "mappedselectionmodel.h"
39 #include "network.h"
40 #include "networkmodel.h"
41 #include "networkmodelactionprovider.h"
42 #include "quasselui.h"
43 #include "uisettings.h"
44
45 /*****************************************
46 * The TreeView showing the Buffers
47 *****************************************/
48 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
49 // to be on the safe side: call QTreeView's method aswell
50 BufferView::BufferView(QWidget *parent) : QTreeView(parent) {
51   connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(on_collapse(const QModelIndex &)));
52   connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(on_expand(const QModelIndex &)));
53
54   setSelectionMode(QAbstractItemView::ExtendedSelection);
55 }
56
57 void BufferView::init() {
58   setIndentation(10);
59   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
60   hideColumn(1);
61   hideColumn(2);
62   expandAll();
63
64   setAnimated(true);
65
66 #ifndef QT_NO_DRAGANDDROP
67   setDragEnabled(true);
68   setAcceptDrops(true);
69   setDropIndicatorShown(true);
70 #endif
71
72   setSortingEnabled(true);
73   sortByColumn(0, Qt::AscendingOrder);
74
75   // activated() fails on X11 and Qtopia at least
76 #if defined Q_WS_QWS || defined Q_WS_X11
77   connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
78 #else
79   // afaik this is better on Mac and Windows
80   connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
81 #endif
82 }
83
84 void BufferView::setModel(QAbstractItemModel *model) {
85   delete selectionModel();
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   QString sectionName;
100   QAction *showSection;
101   for(int i = 1; i < model->columnCount(); i++) {
102     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
103     showSection = new QAction(sectionName, header());
104     showSection->setCheckable(true);
105     showSection->setChecked(!isColumnHidden(i));
106     showSection->setProperty("column", i);
107     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
108     header()->addAction(showSection);
109   }
110
111 }
112
113 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
114   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
115   if(filter) {
116     filter->setConfig(config);
117     setConfig(config);
118     return;
119   }
120
121   if(model()) {
122     disconnect(this, 0, model(), 0);
123     disconnect(model(), 0, this, 0);
124   }
125
126   if(!model_) {
127     setModel(model_);
128   } else {
129     BufferViewFilter *filter = new BufferViewFilter(model_, config);
130     setModel(filter);
131     connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
132   }
133   setConfig(config);
134 }
135
136 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
137   if(QTreeView::selectionModel())
138     disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
139                model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
140
141   QTreeView::setSelectionModel(selectionModel);
142   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
143   if(filter) {
144     connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
145             filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
146   }
147 }
148
149 void BufferView::setConfig(BufferViewConfig *config) {
150   if(_config == config)
151     return;
152
153   if(_config) {
154     disconnect(_config, 0, this, 0);
155   }
156
157   _config = config;
158   if(config) {
159     connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
160     setRootIndexForNetworkId(config->networkId());
161   } else {
162     setRootIndex(QModelIndex());
163   }
164 }
165
166 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
167   if(!networkId.isValid() || !model()) {
168     setRootIndex(QModelIndex());
169   } else {
170     int networkCount = model()->rowCount();
171     QModelIndex child;
172     for(int i = 0; i < networkCount; i++) {
173       child = model()->index(i, 0);
174       if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
175         setRootIndex(child);
176     }
177   }
178 }
179
180 void BufferView::joinChannel(const QModelIndex &index) {
181   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
182
183   if(bufferType != BufferInfo::ChannelBuffer)
184     return;
185
186   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
187
188   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
189 }
190
191 void BufferView::keyPressEvent(QKeyEvent *event) {
192   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
193     event->accept();
194     removeSelectedBuffers();
195   }
196   QTreeView::keyPressEvent(event);
197 }
198
199 void BufferView::dropEvent(QDropEvent *event) {
200   QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
201
202   if(bufferList.count() != 1)
203     return QTreeView::dropEvent(event);
204
205   NetworkId networkId = bufferList[0].first;
206   BufferId bufferId2 = bufferList[0].second;
207
208   QModelIndex index = indexAt(event->pos());
209   if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
210     return;
211
212   if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
213     return;
214
215   if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
216     return;
217
218   BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
219   if(bufferId1 == bufferId2)
220     return;
221
222   int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
223                                   tr("Do you want to merge the buffer \"%1\" permanently into buffer \"%2\"?\n This cannot be reversed!").arg(Client::networkModel()->bufferName(bufferId2)).arg(Client::networkModel()->bufferName(bufferId1)),
224                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
225   if(res == QMessageBox::Yes) {
226     Client::mergeBuffersPermanently(bufferId1, bufferId2);
227   }
228 }
229
230 void BufferView::removeSelectedBuffers(bool permanently) {
231   if(!config())
232     return;
233
234   BufferId bufferId;
235   QSet<BufferId> removedRows;
236   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
237     if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
238       continue;
239
240     bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
241     if(removedRows.contains(bufferId))
242       continue;
243
244     removedRows << bufferId;
245
246     if(permanently)
247       config()->requestRemoveBufferPermanently(bufferId);
248     else
249       config()->requestRemoveBuffer(bufferId);
250   }
251 }
252
253 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
254   QTreeView::rowsInserted(parent, start, end);
255
256   // ensure that newly inserted network nodes are expanded per default
257   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
258     return;
259
260   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
261     // without updating the parent the expand will have no effect... Qt Bug?
262     update(parent);
263     expand(parent);
264   }
265 }
266
267 void BufferView::on_configChanged() {
268   Q_ASSERT(model());
269
270   // expand all active networks... collapse inactive ones... unless manually changed
271   QModelIndex networkIdx;
272   NetworkId networkId;
273   for(int row = 0; row < model()->rowCount(); row++) {
274     networkIdx = model()->index(row, 0);
275     if(model()->rowCount(networkIdx) ==  0)
276       continue;
277
278     networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
279     if(!networkId.isValid())
280       continue;
281
282     update(networkIdx);
283
284     bool expandNetwork = false;
285     if(_expandedState.contains(networkId))
286       expandNetwork = _expandedState[networkId];
287     else
288       expandNetwork = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
289
290     if(expandNetwork)
291       expand(networkIdx);
292     else
293       collapse(networkIdx);
294   }
295
296   // update selection to current one
297   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
298   if(!config() || !mappedSelectionModel)
299     return;
300
301   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
302   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
303 }
304
305 void BufferView::on_collapse(const QModelIndex &index) {
306   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), false);
307 }
308
309 void BufferView::on_expand(const QModelIndex &index) {
310   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), true);
311 }
312
313 void BufferView::storeExpandedState(NetworkId networkId, bool expanded) {
314   _expandedState[networkId] = expanded;
315 }
316
317 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
318   QTreeView::dataChanged(topLeft, bottomRight);
319
320   // determine how many items have been changed and if any of them is a networkitem
321   // which just swichted from active to inactive or vice versa
322   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
323     return;
324
325   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
326     QModelIndex networkIdx = topLeft.sibling(i, 0);
327     if(model()->rowCount(networkIdx) == 0)
328       continue;
329
330     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
331 #ifdef SPUTDEV
332     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
333 #else
334     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
335 #endif
336   }
337 }
338
339 void BufferView::toggleHeader(bool checked) {
340   QAction *action = qobject_cast<QAction *>(sender());
341   header()->setSectionHidden((action->property("column")).toInt(), !checked);
342 }
343
344 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
345   QModelIndex index = indexAt(event->pos());
346   if(!index.isValid())
347     index = rootIndex();
348   if(!index.isValid())
349     return;
350
351   QMenu contextMenu(this);
352   addActionsToMenu(&contextMenu, index);
353   if(!contextMenu.actions().isEmpty())
354     contextMenu.exec(QCursor::pos());
355
356 }
357
358 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
359   Client::mainUi()->actionProvider()->addActions(contextMenu, index, this, "menuActionTriggered", (bool)config());
360 }
361
362 void BufferView::menuActionTriggered(QAction *result) {
363   NetworkModelActionProvider::ActionType type = (NetworkModelActionProvider::ActionType)result->data().toInt();
364   switch(type) {
365     case NetworkModelActionProvider::HideBufferTemporarily:
366       removeSelectedBuffers();
367       break;
368     case NetworkModelActionProvider::HideBufferPermanently:
369       removeSelectedBuffers(true);
370       break;
371     default:
372       return;
373   }
374 }
375
376 void BufferView::wheelEvent(QWheelEvent* event) {
377   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
378     return QTreeView::wheelEvent(event);
379
380   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
381   QModelIndex currentIndex = selectionModel()->currentIndex();
382   QModelIndex resultingIndex;
383   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
384     {
385       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
386     }
387     else //if we scroll into a the parent node...
388       {
389         QModelIndex parent = currentIndex.parent();
390         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
391         if( rowDelta == -1 )
392           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
393         else
394           resultingIndex = aunt.child( 0, 0 );
395         if( !resultingIndex.isValid() )
396           return;
397       }
398   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
399   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
400
401 }
402
403 QSize BufferView::sizeHint() const {
404   return QTreeView::sizeHint();
405
406   if(!model())
407     return QTreeView::sizeHint();
408
409   if(model()->rowCount() == 0)
410     return QSize(120, 50);
411
412   int columnSize = 0;
413   for(int i = 0; i < model()->columnCount(); i++) {
414     if(!isColumnHidden(i))
415       columnSize += sizeHintForColumn(i);
416   }
417   return QSize(columnSize, 50);
418 }
419
420 // ==============================
421 //  BufferView Dock
422 // ==============================
423 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
424   : QDockWidget(config->bufferViewName(), parent)
425 {
426   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
427   toggleViewAction()->setData(config->bufferViewId());
428   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
429   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
430 }
431
432 BufferViewDock::BufferViewDock(QWidget *parent)
433   : QDockWidget(tr("All Buffers"), parent)
434 {
435   setObjectName("BufferViewDock--1");
436   toggleViewAction()->setData((int)-1);
437   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
438 }
439
440 void BufferViewDock::bufferViewRenamed(const QString &newName) {
441   setWindowTitle(newName);
442   toggleViewAction()->setText(newName);
443 }