If available, use KDE API to force window activation.
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 <QApplication>
24 #include <QAction>
25 #include <QFlags>
26 #include <QHeaderView>
27 #include <QLineEdit>
28 #include <QMenu>
29 #include <QMessageBox>
30 #include <QSet>
31
32 #include "action.h"
33 #include "buffermodel.h"
34 #include "bufferviewfilter.h"
35 #include "buffersettings.h"
36 #include "buffersyncer.h"
37 #include "client.h"
38 #include "contextmenuactionprovider.h"
39 #include "graphicalui.h"
40 #include "network.h"
41 #include "networkmodel.h"
42 #include "contextmenuactionprovider.h"
43
44 /*****************************************
45 * The TreeView showing the Buffers
46 *****************************************/
47 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
48 // to be on the safe side: call QTreeView's method aswell
49 BufferView::BufferView(QWidget *parent)
50   : QTreeView(parent)
51 {
52   connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
53   connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
54
55   setSelectionMode(QAbstractItemView::ExtendedSelection);
56
57   QAbstractItemDelegate *oldDelegate = itemDelegate();
58   BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
59   setItemDelegate(tristateDelegate);
60   delete oldDelegate;
61 }
62
63 void BufferView::init() {
64   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
65   hideColumn(1);
66   hideColumn(2);
67   setIndentation(10);
68   expandAll();
69
70   header()->hide(); // nobody seems to use this anyway
71
72   setAnimated(true);
73
74   // FIXME This is to workaround bug #663
75   setUniformRowHeights(true);
76
77 #ifndef QT_NO_DRAGANDDROP
78   setDragEnabled(true);
79   setAcceptDrops(true);
80   setDropIndicatorShown(true);
81 #endif
82
83   setSortingEnabled(true);
84   sortByColumn(0, Qt::AscendingOrder);
85
86   // activated() fails on X11 and Qtopia at least
87 #if defined Q_WS_QWS || defined Q_WS_X11
88   disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
89   connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
90 #else
91   // afaik this is better on Mac and Windows
92   disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
93   connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
94 #endif
95 }
96
97 void BufferView::setModel(QAbstractItemModel *model) {
98   delete selectionModel();
99
100   QTreeView::setModel(model);
101   init();
102   // remove old Actions
103   QList<QAction *> oldactions = header()->actions();
104   foreach(QAction *action, oldactions) {
105     header()->removeAction(action);
106     action->deleteLater();
107   }
108
109   if(!model)
110     return;
111
112   QString sectionName;
113   QAction *showSection;
114   for(int i = 1; i < model->columnCount(); i++) {
115     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
116     showSection = new QAction(sectionName, header());
117     showSection->setCheckable(true);
118     showSection->setChecked(!isColumnHidden(i));
119     showSection->setProperty("column", i);
120     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
121     header()->addAction(showSection);
122   }
123
124   connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
125 }
126
127 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config) {
128   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
129   if(filter) {
130     filter->setConfig(config);
131     setConfig(config);
132     return;
133   }
134
135   if(model()) {
136     disconnect(this, 0, model(), 0);
137     disconnect(model(), 0, this, 0);
138   }
139
140   if(!model_) {
141     setModel(model_);
142   } else {
143     BufferViewFilter *filter = new BufferViewFilter(model_, config);
144     setModel(filter);
145     connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
146   }
147   setConfig(config);
148 }
149
150 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel) {
151   if(QTreeView::selectionModel())
152     disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
153                model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
154
155   QTreeView::setSelectionModel(selectionModel);
156   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
157   if(filter) {
158     connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
159             filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
160   }
161 }
162
163 void BufferView::setConfig(BufferViewConfig *config) {
164   if(_config == config)
165     return;
166
167   if(_config) {
168     disconnect(_config, 0, this, 0);
169   }
170
171   _config = config;
172   if(config) {
173     connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
174     setRootIndexForNetworkId(config->networkId());
175   } else {
176     setIndentation(10);
177     setRootIndex(QModelIndex());
178   }
179 }
180
181 void BufferView::setRootIndexForNetworkId(const NetworkId &networkId) {
182   if(!networkId.isValid() || !model()) {
183     setIndentation(10);
184     setRootIndex(QModelIndex());
185   } else {
186     setIndentation(5);
187     int networkCount = model()->rowCount();
188     QModelIndex child;
189     for(int i = 0; i < networkCount; i++) {
190       child = model()->index(i, 0);
191       if(networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
192         setRootIndex(child);
193     }
194   }
195 }
196
197 void BufferView::joinChannel(const QModelIndex &index) {
198   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
199
200   if(bufferType != BufferInfo::ChannelBuffer)
201     return;
202
203   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
204
205   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
206 }
207
208 void BufferView::keyPressEvent(QKeyEvent *event) {
209   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
210     event->accept();
211     removeSelectedBuffers();
212   }
213   QTreeView::keyPressEvent(event);
214 }
215
216 void BufferView::dropEvent(QDropEvent *event) {
217   QModelIndex index = indexAt(event->pos());
218
219   QRect indexRect = visualRect(index);
220   QPoint cursorPos = event->pos();
221
222   // check if we're really _on_ the item and not indicating a move to just above or below the item
223   const int margin = 2;
224   if(cursorPos.y() - indexRect.top() < margin
225      || indexRect.bottom() - cursorPos.y() < margin)
226     return QTreeView::dropEvent(event);
227
228   QList< QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
229   if(bufferList.count() != 1)
230     return QTreeView::dropEvent(event);
231
232   NetworkId networkId = bufferList[0].first;
233   BufferId bufferId2 = bufferList[0].second;
234
235   if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
236     return QTreeView::dropEvent(event);
237
238   if(index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
239     return QTreeView::dropEvent(event);
240
241   if(index.data(NetworkModel::NetworkIdRole).value<NetworkId>() != networkId)
242     return QTreeView::dropEvent(event);
243
244   BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
245   if(bufferId1 == bufferId2)
246     return QTreeView::dropEvent(event);
247
248   int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
249                                   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)),
250                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
251   if(res == QMessageBox::Yes) {
252     Client::mergeBuffersPermanently(bufferId1, bufferId2);
253   }
254 }
255
256 void BufferView::removeSelectedBuffers(bool permanently) {
257   if(!config())
258     return;
259
260   BufferId bufferId;
261   QSet<BufferId> removedRows;
262   foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
263     if(index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
264       continue;
265
266     bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
267     if(removedRows.contains(bufferId))
268       continue;
269
270     removedRows << bufferId;
271   }
272
273   foreach(BufferId bufferId, removedRows) {
274     if(permanently)
275       config()->requestRemoveBufferPermanently(bufferId);
276     else
277       config()->requestRemoveBuffer(bufferId);
278   }
279 }
280
281 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end) {
282   QTreeView::rowsInserted(parent, start, end);
283
284   // ensure that newly inserted network nodes are expanded per default
285   if(parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
286     return;
287
288   setExpandedState(parent);
289 }
290
291 void BufferView::on_layoutChanged() {
292   int numNets = model()->rowCount(QModelIndex());
293   for(int row = 0; row < numNets; row++) {
294     QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
295     setExpandedState(networkIdx);
296   }
297 }
298
299 void BufferView::on_configChanged() {
300   Q_ASSERT(model());
301
302   // expand all active networks... collapse inactive ones... unless manually changed
303   QModelIndex networkIdx;
304   NetworkId networkId;
305   for(int row = 0; row < model()->rowCount(); row++) {
306     networkIdx = model()->index(row, 0);
307     if(model()->rowCount(networkIdx) ==  0)
308       continue;
309
310     networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
311     if(!networkId.isValid())
312       continue;
313
314     setExpandedState(networkIdx);
315   }
316
317   if(config()) {
318     // update selection to current one
319     Client::bufferModel()->synchronizeView(this);
320   }
321 }
322
323 void BufferView::storeExpandedState(const QModelIndex &networkIdx) {
324   NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
325
326   int oldState = 0;
327   if(isExpanded(networkIdx))
328     oldState |= WasExpanded;
329   if(model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
330     oldState |= WasActive;
331
332   _expandedState[networkId] = oldState;
333 }
334
335 void BufferView::setExpandedState(const QModelIndex &networkIdx) {
336   if(model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
337     return;
338
339   if(model()->rowCount(networkIdx) == 0)
340     return;
341
342   NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
343
344   bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
345   bool expandNetwork = networkActive;
346   if(_expandedState.contains(networkId)) {
347     int oldState = _expandedState[networkId];
348     if((bool)(oldState & WasActive) == networkActive)
349       expandNetwork = (bool)(oldState & WasExpanded);
350   }
351
352   if(expandNetwork != isExpanded(networkIdx)) {
353     update(networkIdx);
354     setExpanded(networkIdx, expandNetwork);
355   }
356   storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
357 }
358
359 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
360   QTreeView::dataChanged(topLeft, bottomRight);
361
362   // determine how many items have been changed and if any of them is a networkitem
363   // which just swichted from active to inactive or vice versa
364   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
365     return;
366
367   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
368     QModelIndex networkIdx = topLeft.sibling(i, 0);
369     setExpandedState(networkIdx);
370   }
371 }
372
373 void BufferView::toggleHeader(bool checked) {
374   QAction *action = qobject_cast<QAction *>(sender());
375   header()->setSectionHidden((action->property("column")).toInt(), !checked);
376 }
377
378 void BufferView::contextMenuEvent(QContextMenuEvent *event) {
379   QModelIndex index = indexAt(event->pos());
380   if(!index.isValid())
381     index = rootIndex();
382
383   QMenu contextMenu(this);
384
385   if(index.isValid()) {
386     addActionsToMenu(&contextMenu, index);
387   }
388
389   addFilterActions(&contextMenu, index);
390
391   if(!contextMenu.actions().isEmpty())
392     contextMenu.exec(QCursor::pos());
393 }
394
395 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index) {
396   QModelIndexList indexList = selectedIndexes();
397   // make sure the item we clicked on is first
398   indexList.removeAll(index);
399   indexList.prepend(index);
400
401   GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
402 }
403
404 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index) {
405   BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
406   if(filter) {
407     QList<QAction *> filterActions = filter->actions(index);
408     if(!filterActions.isEmpty()) {
409       contextMenu->addSeparator();
410       foreach(QAction *action, filterActions) {
411         contextMenu->addAction(action);
412       }
413     }
414   }
415 }
416
417 void BufferView::menuActionTriggered(QAction *result) {
418   ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
419   switch(type) {
420     case ContextMenuActionProvider::HideBufferTemporarily:
421       removeSelectedBuffers();
422       break;
423     case ContextMenuActionProvider::HideBufferPermanently:
424       removeSelectedBuffers(true);
425       break;
426     default:
427       return;
428   }
429 }
430
431 void BufferView::wheelEvent(QWheelEvent* event) {
432   if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
433     return QTreeView::wheelEvent(event);
434
435   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
436   QModelIndex currentIndex = selectionModel()->currentIndex();
437   QModelIndex resultingIndex;
438   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
439     {
440       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
441     }
442     else //if we scroll into a the parent node...
443       {
444         QModelIndex parent = currentIndex.parent();
445         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
446         if( rowDelta == -1 )
447           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
448         else
449           resultingIndex = aunt.child( 0, 0 );
450         if( !resultingIndex.isValid() )
451           return;
452       }
453   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
454   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
455
456 }
457
458 QSize BufferView::sizeHint() const {
459   return QTreeView::sizeHint();
460
461   if(!model())
462     return QTreeView::sizeHint();
463
464   if(model()->rowCount() == 0)
465     return QSize(120, 50);
466
467   int columnSize = 0;
468   for(int i = 0; i < model()->columnCount(); i++) {
469     if(!isColumnHidden(i))
470       columnSize += sizeHintForColumn(i);
471   }
472   return QSize(columnSize, 50);
473 }
474
475
476 // ****************************************
477 //  BufferViewDelgate
478 // ****************************************
479 class ColorsChangedEvent : public QEvent {
480 public:
481   ColorsChangedEvent() : QEvent(QEvent::User) {};
482 };
483
484 BufferViewDelegate::BufferViewDelegate(QObject *parent)
485   : QStyledItemDelegate(parent)
486 {
487 }
488
489 void BufferViewDelegate::customEvent(QEvent *event) {
490   if(event->type() != QEvent::User)
491     return;
492
493   event->accept();
494 }
495
496 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
497   if(event->type() != QEvent::MouseButtonRelease)
498     return QStyledItemDelegate::editorEvent(event, model, option, index);
499
500   if(!(model->flags(index) & Qt::ItemIsUserCheckable))
501     return QStyledItemDelegate::editorEvent(event, model, option, index);
502
503   QVariant value = index.data(Qt::CheckStateRole);
504   if(!value.isValid())
505     return QStyledItemDelegate::editorEvent(event, model, option, index);
506
507   QStyleOptionViewItemV4 viewOpt(option);
508   initStyleOption(&viewOpt, index);
509
510   QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
511   QMouseEvent *me = static_cast<QMouseEvent*>(event);
512
513   if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
514     return QStyledItemDelegate::editorEvent(event, model, option, index);
515
516   Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
517   if(state == Qt::Unchecked)
518     state = Qt::PartiallyChecked;
519   else if(state == Qt::PartiallyChecked)
520     state = Qt::Checked;
521   else
522     state = Qt::Unchecked;
523   model->setData(index, state, Qt::CheckStateRole);
524   return true;
525 }
526
527 // ==============================
528 //  BufferView Dock
529 // ==============================
530 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
531   : QDockWidget(config->bufferViewName(), parent)
532 {
533   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
534   toggleViewAction()->setData(config->bufferViewId());
535   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
536   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
537 }
538
539 void BufferViewDock::bufferViewRenamed(const QString &newName) {
540   setWindowTitle(newName);
541   toggleViewAction()->setText(newName);
542 }
543
544 int BufferViewDock::bufferViewId() const {
545   BufferView *view = bufferView();
546   if(!view)
547     return 0;
548
549   if(view->config())
550     return view->config()->bufferViewId();
551   else
552     return 0;
553 }
554
555 BufferViewConfig *BufferViewDock::config() const {
556   BufferView *view = bufferView();
557   if(!view)
558     return 0;
559   else
560     return view->config();
561 }