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