Make tabcompletion key configurable via shortcuts. fixes 1018
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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::nextBuffer() {
432   changeBuffer(Forward);
433 }
434
435 void BufferView::previousBuffer() {
436   changeBuffer(Backward);
437 }
438
439 void BufferView::changeBuffer(Direction direction) {
440   QModelIndex currentIndex = selectionModel()->currentIndex();
441   QModelIndex resultingIndex;
442   if(model()->hasIndex(  currentIndex.row() + direction, currentIndex.column(), currentIndex.parent()))
443     resultingIndex = currentIndex.sibling(currentIndex.row() + direction, currentIndex.column());
444
445   else {
446     //if we scroll into a the parent node...
447     QModelIndex parent = currentIndex.parent();
448     QModelIndex aunt = parent.sibling(parent.row() + direction, parent.column());
449     if(direction == Backward)
450       resultingIndex = aunt.child(model()->rowCount(aunt) - 1, 0);
451     else
452       resultingIndex = aunt.child(0, 0);
453     if(!resultingIndex.isValid())
454       return;
455   }
456   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
457   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
458 }
459
460 void BufferView::wheelEvent(QWheelEvent* event) {
461   if(ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
462     return QTreeView::wheelEvent(event);
463
464   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
465   changeBuffer((Direction)rowDelta);
466 }
467
468 QSize BufferView::sizeHint() const {
469   return QTreeView::sizeHint();
470
471   if(!model())
472     return QTreeView::sizeHint();
473
474   if(model()->rowCount() == 0)
475     return QSize(120, 50);
476
477   int columnSize = 0;
478   for(int i = 0; i < model()->columnCount(); i++) {
479     if(!isColumnHidden(i))
480       columnSize += sizeHintForColumn(i);
481   }
482   return QSize(columnSize, 50);
483 }
484
485
486 // ****************************************
487 //  BufferViewDelgate
488 // ****************************************
489 class ColorsChangedEvent : public QEvent {
490 public:
491   ColorsChangedEvent() : QEvent(QEvent::User) {};
492 };
493
494 BufferViewDelegate::BufferViewDelegate(QObject *parent)
495   : QStyledItemDelegate(parent)
496 {
497 }
498
499 void BufferViewDelegate::customEvent(QEvent *event) {
500   if(event->type() != QEvent::User)
501     return;
502
503   event->accept();
504 }
505
506 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
507   if(event->type() != QEvent::MouseButtonRelease)
508     return QStyledItemDelegate::editorEvent(event, model, option, index);
509
510   if(!(model->flags(index) & Qt::ItemIsUserCheckable))
511     return QStyledItemDelegate::editorEvent(event, model, option, index);
512
513   QVariant value = index.data(Qt::CheckStateRole);
514   if(!value.isValid())
515     return QStyledItemDelegate::editorEvent(event, model, option, index);
516
517   QStyleOptionViewItemV4 viewOpt(option);
518   initStyleOption(&viewOpt, index);
519
520   QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
521   QMouseEvent *me = static_cast<QMouseEvent*>(event);
522
523   if(me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
524     return QStyledItemDelegate::editorEvent(event, model, option, index);
525
526   Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
527   if(state == Qt::Unchecked)
528     state = Qt::PartiallyChecked;
529   else if(state == Qt::PartiallyChecked)
530     state = Qt::Checked;
531   else
532     state = Qt::Unchecked;
533   model->setData(index, state, Qt::CheckStateRole);
534   return true;
535 }
536
537 // ==============================
538 //  BufferView Dock
539 // ==============================
540 BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
541   : QDockWidget(parent),
542     _active(false),
543     _title(config->bufferViewName())
544 {
545   setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
546   toggleViewAction()->setData(config->bufferViewId());
547   setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
548   connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
549   updateTitle();
550 }
551
552 void BufferViewDock::updateTitle() {
553   QString title = _title;
554   if(isActive())
555     title.prepend(QString::fromUtf8("• "));
556   setWindowTitle(title);
557 }
558
559 void BufferViewDock::setActive(bool active) {
560   if(active != isActive()) {
561     _active = active;
562     updateTitle();
563     if(active)
564       raise(); // for tabbed docks
565   }
566 }
567
568 void BufferViewDock::bufferViewRenamed(const QString &newName) {
569   _title = newName;
570   updateTitle();
571   toggleViewAction()->setText(newName);
572 }
573
574 int BufferViewDock::bufferViewId() const {
575   BufferView *view = bufferView();
576   if(!view)
577     return 0;
578
579   if(view->config())
580     return view->config()->bufferViewId();
581   else
582     return 0;
583 }
584
585 BufferViewConfig *BufferViewDock::config() const {
586   BufferView *view = bufferView();
587   if(!view)
588     return 0;
589   else
590     return view->config();
591 }