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