Meh, apparently MSVC doesn't accept 'or' in preprocessor defines either :P
[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::removeSelectedBuffers(bool permanently) {
200   if(!config())
201     return;
202
203   BufferId bufferId;
204   QSet<BufferId> removedRows;
205   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
206     if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
207       continue;
208
209     bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
210     if(removedRows.contains(bufferId))
211       continue;
212
213     removedRows << bufferId;
214
215     if(permanently)
216       config()->requestRemoveBufferPermanently(bufferId);
217     else
218       config()->requestRemoveBuffer(bufferId);
219   }
220 }
221
222 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
223   QTreeView::rowsInserted(parent, start, end);
224
225   // ensure that newly inserted network nodes are expanded per default
226   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
227     return;
228
229   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemActiveRole) == true) {
230     // without updating the parent the expand will have no effect... Qt Bug?
231     update(parent);
232     expand(parent);
233   }
234 }
235
236 void BufferView::on_configChanged() {
237   Q_ASSERT(model());
238
239   // expand all active networks... collapse inactive ones... unless manually changed
240   QModelIndex networkIdx;
241   NetworkId networkId;
242   for(int row = 0; row < model()->rowCount(); row++) {
243     networkIdx = model()->index(row, 0);
244     if(model()->rowCount(networkIdx) ==  0)
245       continue;
246
247     networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
248     if(!networkId.isValid())
249       continue;
250
251     update(networkIdx);
252
253     bool expandNetwork = false;
254     if(_expandedState.contains(networkId))
255       expandNetwork = _expandedState[networkId];
256     else
257       expandNetwork = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
258
259     if(expandNetwork)
260       expand(networkIdx);
261     else
262       collapse(networkIdx);
263   }
264
265   // update selection to current one
266   MappedSelectionModel *mappedSelectionModel = qobject_cast<MappedSelectionModel *>(selectionModel());
267   if(!config() || !mappedSelectionModel)
268     return;
269
270   mappedSelectionModel->mappedSetCurrentIndex(Client::bufferModel()->standardSelectionModel()->currentIndex(), QItemSelectionModel::Current);
271   mappedSelectionModel->mappedSelect(Client::bufferModel()->standardSelectionModel()->selection(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
272 }
273
274 void BufferView::on_collapse(const QModelIndex &index) {
275   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), false);
276 }
277
278 void BufferView::on_expand(const QModelIndex &index) {
279   storeExpandedState(index.data(NetworkModel::NetworkIdRole).value<NetworkId>(), true);
280 }
281
282 void BufferView::storeExpandedState(NetworkId networkId, bool expanded) {
283   _expandedState[networkId] = expanded;
284 }
285
286 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
287   QTreeView::dataChanged(topLeft, bottomRight);
288
289   // determine how many items have been changed and if any of them is a networkitem
290   // which just swichted from active to inactive or vice versa
291   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
292     return;
293
294   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
295     QModelIndex networkIdx = topLeft.sibling(i, 0);
296     if(model()->rowCount(networkIdx) == 0)
297       continue;
298
299     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
300 #ifdef SPUTDEV
301     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
302 #else
303     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
304 #endif
305   }
306 }
307
308 void BufferView::toggleHeader(bool checked) {
309   QAction *action = qobject_cast<QAction *>(sender());
310   header()->setSectionHidden((action->property("column")).toInt(), !checked);
311 }
312
313 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
314   QModelIndex index = indexAt(event->pos());
315   if(!index.isValid())
316     index = rootIndex();
317   if(!index.isValid())
318     return;
319
320   QMenu contextMenu(this);
321   addActionsToMenu(&contextMenu, index);
322   if(!contextMenu.actions().isEmpty())
323     contextMenu.exec(QCursor::pos());
324
325 }
326
327 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
328   Client::mainUi()->actionProvider()->addActions(contextMenu, index, this, "menuActionTriggered", (bool)config());
329 }
330
331 void BufferView::menuActionTriggered(QAction *result) {
332   NetworkModelActionProvider::ActionType type = (NetworkModelActionProvider::ActionType)result->data().toInt();
333   switch(type) {
334     case NetworkModelActionProvider::HideBufferTemporarily:
335       removeSelectedBuffers();
336       break;
337     case NetworkModelActionProvider::HideBufferPermanently:
338       removeSelectedBuffers(true);
339       break;
340     default:
341       return;
342   }
343 }
344
345 void BufferView::wheelEvent(QWheelEvent* event) {
346   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
347     return QTreeView::wheelEvent(event);
348
349   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
350   QModelIndex currentIndex = selectionModel()->currentIndex();
351   QModelIndex resultingIndex;
352   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
353     {
354       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
355     }
356     else //if we scroll into a the parent node...
357       {
358         QModelIndex parent = currentIndex.parent();
359         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
360         if( rowDelta == -1 )
361           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
362         else
363           resultingIndex = aunt.child( 0, 0 );
364         if( !resultingIndex.isValid() )
365           return;
366       }
367   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
368   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
369
370 }
371
372 QSize BufferView::sizeHint() const {
373   return QTreeView::sizeHint();
374
375   if(!model())
376     return QTreeView::sizeHint();
377
378   if(model()->rowCount() == 0)
379     return QSize(120, 50);
380
381   int columnSize = 0;
382   for(int i = 0; i < model()->columnCount(); i++) {
383     if(!isColumnHidden(i))
384       columnSize += sizeHintForColumn(i);
385   }
386   return QSize(columnSize, 50);
387 }
388
389 // ==============================
390 //  BufferView Dock
391 // ==============================
392 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
393   : QDockWidget(config->bufferViewName(), parent)
394 {
395   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
396   toggleViewAction()->setData(config->bufferViewId());
397   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
398   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
399 }
400
401 BufferViewDock::BufferViewDock(QWidget *parent)
402   : QDockWidget(tr("All Buffers"), parent)
403 {
404   setObjectName("BufferViewDock--1");
405   toggleViewAction()->setData((int)-1);
406   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
407 }
408
409 void BufferViewDock::bufferViewRenamed(const QString &newName) {
410   setWindowTitle(newName);
411   toggleViewAction()->setText(newName);
412 }