10ef5d8f7069c143e0b45d47840153097dba77a2
[quassel.git] / src / qtui / chatscene.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 <QApplication>
22 #include <QClipboard>
23 #include <QGraphicsSceneMouseEvent>
24 #include <QPersistentModelIndex>
25
26 #include "chatitem.h"
27 #include "chatline.h"
28 #include "chatlinemodelitem.h"
29 #include "chatscene.h"
30 #include "client.h"
31 #include "clientbacklogmanager.h"
32 #include "columnhandleitem.h"
33 #include "messagefilter.h"
34 #include "qtui.h"
35 #include "qtuistyle.h"
36 #include "chatviewsettings.h"
37 #include "webpreviewitem.h"
38
39 const qreal minContentsWidth = 200;
40
41 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
42   : QGraphicsScene(0, 0, width, 0, parent),
43     _idString(idString),
44     _model(model),
45     _singleBufferScene(false),
46     _sceneRect(0, 0, width, 0),
47     _viewportHeight(0),
48     _selectingItem(0),
49     _selectionStart(-1),
50     _isSelecting(false),
51     _lastBacklogSize(0)
52 {
53   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
54   if(filter) {
55     _singleBufferScene = filter->isSingleBufferFilter();
56   }
57
58   ChatViewSettings defaultSettings;
59   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
60   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
61
62   ChatViewSettings viewSettings(this);
63   firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
64   secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
65
66   firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
67   addItem(firstColHandle);
68   firstColHandle->setXPos(firstColHandlePos);
69   connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
70   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
71
72   secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
73   addItem(secondColHandle);
74   secondColHandle->setXPos(secondColHandlePos);
75   connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
76   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
77
78   setHandleXLimits();
79
80   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
81           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
82   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
83           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
84
85   if(model->rowCount() > 0)
86     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
87 }
88
89 ChatScene::~ChatScene() {
90 }
91
92 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
93   Q_UNUSED(index);
94
95   clearWebPreview();
96
97 //   QModelIndex sidx = model()->index(start, 0);
98 //   QModelIndex eidx = model()->index(end, 0);
99 //   qDebug() << "rowsInserted" << start << end << "-" << sidx.data(MessageModel::MsgIdRole).value<MsgId>() << eidx.data(MessageModel::MsgIdRole).value<MsgId>();
100
101   qreal h = 0;
102   qreal y = _sceneRect.y();
103   qreal width = _sceneRect.width();
104   bool atTop = true;
105   bool atBottom = false;
106   bool moveTop = false;
107
108   if(start > 0 && start < _lines.count()) {
109     y = _lines.value(start)->y();
110     atTop = false;
111   }
112   if(start == _lines.count()) {
113     y = _sceneRect.bottom();
114     atTop = false;
115     atBottom = true;
116   }
117
118   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
119   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
120   qreal timestampWidth = firstColumnHandle()->sceneLeft();
121   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
122   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
123
124   for(int i = start; i <= end; i++) {
125     ChatLine *line = new ChatLine(i, model(),
126                                   width,
127                                   timestampWidth, senderWidth, contentsWidth,
128                                   senderPos, contentsPos);
129     line->setPos(0, y+h);
130     h += line->height();
131     _lines.insert(i, line);
132     addItem(line);
133   }
134
135   // update existing items
136   for(int i = end+1; i < _lines.count(); i++) {
137     _lines[i]->setRow(i);
138   }
139
140   // update selection
141   if(_selectionStart >= 0) {
142     int offset = end - start + 1;
143     if(_selectionStart >= start) _selectionStart += offset;
144     if(_selectionEnd >= start) _selectionEnd += offset;
145     if(_firstSelectionRow >= start) _firstSelectionRow += offset;
146     if(_lastSelectionRow >= start) _lastSelectionRow += offset;
147   }
148
149   // neither pre- or append means we have to do dirty work: move items...
150   if(!(atTop || atBottom)) {
151     qreal offset = h;
152     int moveStart = 0;
153     int moveEnd = _lines.count() - 1;
154     // move top means: moving 0 to end (aka: end + 1)
155     // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
156     if(end + 1 < _lines.count() - end - 1) {
157       // move top part
158       moveTop = true;
159       offset = -offset;
160       moveEnd = end;
161     } else {
162       // move bottom part
163       moveStart = start;
164     }
165     ChatLine *line = 0;
166     for(int i = moveStart; i <= moveEnd; i++) {
167       line = _lines.at(i);
168       line->setPos(0, line->pos().y() + offset);
169     }
170   }
171
172   // update sceneRect
173   if(atTop || moveTop) {
174     updateSceneRect(_sceneRect.adjusted(0, -h, 0, 0));
175   } else {
176     updateSceneRect(_sceneRect.adjusted(0, 0, 0, h));
177     emit lastLineChanged(_lines.last());
178   }
179
180 }
181
182 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
183   Q_UNUSED(parent);
184
185   clearWebPreview();
186
187   qreal h = 0; // total height of removed items;
188
189   bool atTop = (start == 0);
190   bool atBottom = (end == _lines.count() - 1);
191   bool moveTop = false;
192
193   // remove items from scene
194   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
195   int lineCount = start;
196   while(lineIter != _lines.end() && lineCount <= end) {
197     h += (*lineIter)->height();
198     delete *lineIter;
199     lineIter = _lines.erase(lineIter);
200     lineCount++;
201   }
202
203   // update rows of remaining chatlines
204   for(int i = start; i < _lines.count(); i++) {
205     _lines.at(i)->setRow(i);
206   }
207
208   // update selection
209   if(_selectionStart >= 0) {
210     int offset = end - start + 1;
211     if(_selectionStart >= start)
212       _selectionStart -= offset;
213     if(_selectionEnd >= start)
214       _selectionEnd -= offset;
215     if(_firstSelectionRow >= start)
216       _firstSelectionRow -= offset;
217     if(_lastSelectionRow >= start)
218       _lastSelectionRow -= offset;
219   }
220
221   // neither removing at bottom or top means we have to move items...
222   if(!(atTop || atBottom)) {
223     qreal offset = h;
224     int moveStart = 0;
225     int moveEnd = _lines.count() - 1;
226     if(start < _lines.count() - start) {
227       // move top part
228       moveTop = true;
229       moveEnd = start - 1;
230     } else {
231       // move bottom part
232       moveStart = start;
233       offset = -offset;
234     }
235     ChatLine *line = 0;
236     for(int i = moveStart; i <= moveEnd; i++) {
237       line = _lines.at(i);
238       line->setPos(0, line->pos().y() + offset);
239     }
240   }
241
242   // update sceneRect
243   if(atTop || moveTop) {
244     updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
245   } else {
246     updateSceneRect(_sceneRect.adjusted(0, 0, 0, -h));
247   }
248 }
249
250 void ChatScene::updateForViewport(qreal width, qreal height) {
251   _viewportHeight = height;
252   setWidth(width);
253 }
254
255 // setWidth is used for 2 things:
256 //  a) updating the scene to fit the width of the corresponding view
257 //  b) to update the positions of the items if a columhandle has changed it's position
258 // forceReposition is true in the second case
259 // this method features some codeduplication for the sake of performance
260 void ChatScene::setWidth(qreal width, bool forceReposition) {
261   if(width == _sceneRect.width() && !forceReposition)
262     return;
263
264 //   clock_t startT = clock();
265
266   qreal linePos = _sceneRect.y() + _sceneRect.height();
267   qreal yBottom = linePos;
268   QList<ChatLine *>::iterator lineIter = _lines.end();
269   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
270   ChatLine *line = 0;
271   qreal lineHeight = 0;
272   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
273
274   if(forceReposition) {
275     qreal timestampWidth = firstColumnHandle()->sceneLeft();
276     qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
277     QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
278     QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
279     while(lineIter != lineIterBegin) {
280       lineIter--;
281       line = *lineIter;
282       lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
283       linePos -= lineHeight;
284       line->setPos(0, linePos);
285     }
286   } else {
287     while(lineIter != lineIterBegin) {
288       lineIter--;
289       line = *lineIter;
290       lineHeight = line->setGeometryByWidth(width, contentsWidth);
291       linePos -= lineHeight;
292       line->setPos(0, linePos);
293     }
294   }
295
296   updateSceneRect(QRectF(0, linePos, width, yBottom - linePos));
297   setHandleXLimits();
298
299 //   clock_t endT = clock();
300 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
301 }
302
303 void ChatScene::handlePositionChanged(qreal xpos) {
304   bool first = (sender() == firstColHandle);
305   qreal oldx;
306   if(first) {
307     oldx = firstColHandlePos;
308     firstColHandlePos = xpos;
309   } else {
310     oldx = secondColHandlePos;
311     secondColHandlePos = xpos;
312   }
313
314   ChatViewSettings viewSettings(this);
315   viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
316   viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
317
318   ChatViewSettings defaultSettings;
319   defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
320   defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
321
322   setWidth(width(), true);  // readjust all chatlines
323   // we get ugly redraw errors if we don't update this explicitly... :(
324   // width() should be the same for both handles, so just use firstColHandle regardless
325   //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
326 }
327
328 void ChatScene::setHandleXLimits() {
329   firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
330   secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
331 }
332
333 void ChatScene::setSelectingItem(ChatItem *item) {
334   if(_selectingItem) _selectingItem->clearSelection();
335   _selectingItem = item;
336 }
337
338 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
339   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
340   _selectionStartCol = _selectionMinCol = item->column();
341   _isSelecting = true;
342   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
343   updateSelection(item->mapToScene(itemPos));
344 }
345
346 void ChatScene::updateSelection(const QPointF &pos) {
347   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
348   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
349   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
350   if(!contentItem) return;
351
352   int curRow = contentItem->row();
353   int curColumn;
354   if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
355   else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
356   else curColumn = ChatLineModel::TimestampColumn;
357
358   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
359   if(minColumn != _selectionMinCol) {
360     _selectionMinCol = minColumn;
361     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
362       _lines[l]->setSelected(true, minColumn);
363     }
364   }
365   int newstart = qMin(curRow, _firstSelectionRow);
366   int newend = qMax(curRow, _firstSelectionRow);
367   if(newstart < _selectionStart) {
368     for(int l = newstart; l < _selectionStart; l++)
369       _lines[l]->setSelected(true, minColumn);
370   }
371   if(newstart > _selectionStart) {
372     for(int l = _selectionStart; l < newstart; l++)
373       _lines[l]->setSelected(false);
374   }
375   if(newend > _selectionEnd) {
376     for(int l = _selectionEnd+1; l <= newend; l++)
377       _lines[l]->setSelected(true, minColumn);
378   }
379   if(newend < _selectionEnd) {
380     for(int l = newend+1; l <= _selectionEnd; l++)
381       _lines[l]->setSelected(false);
382   }
383
384   _selectionStart = newstart;
385   _selectionEnd = newend;
386   _lastSelectionRow = curRow;
387
388   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
389     if(!_selectingItem) {
390       qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
391       return;
392     }
393     _lines[curRow]->setSelected(false);
394     _isSelecting = false;
395     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
396   }
397 }
398
399 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
400   if(_isSelecting && event->buttons() == Qt::LeftButton) {
401     updateSelection(event->scenePos());
402     event->accept();
403   } else {
404     QGraphicsScene::mouseMoveEvent(event);
405   }
406 }
407
408 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
409   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
410     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
411       _lines[l]->setSelected(false);
412     }
413     _selectionStart = -1;
414     QGraphicsScene::mousePressEvent(event);  // so we can start a new local selection
415   } else {
416     QGraphicsScene::mousePressEvent(event);
417   }
418 }
419
420 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
421   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
422     putToClipboard(selectionToString());
423     _isSelecting = false;
424     event->accept();
425   } else {
426     QGraphicsScene::mouseReleaseEvent(event);
427   }
428 }
429
430 void ChatScene::putToClipboard(const QString &selection) {
431   // TODO Configure clipboards
432 #   ifdef Q_WS_X11
433   QApplication::clipboard()->setText(selection, QClipboard::Selection);
434 #   endif
435 //# else
436   QApplication::clipboard()->setText(selection);
437 //# endif
438 }
439
440 //!\brief Convert current selection to human-readable string.
441 QString ChatScene::selectionToString() const {
442   //TODO Make selection format configurable!
443   if(!_isSelecting) return QString();
444   int start = qMin(_selectionStart, _selectionEnd);
445   int end = qMax(_selectionStart, _selectionEnd);
446   if(start < 0 || end >= _lines.count()) {
447     qDebug() << "Invalid selection range:" << start << end;
448     return QString();
449   }
450   QString result;
451   for(int l = start; l <= end; l++) {
452     if(_selectionMinCol == ChatLineModel::TimestampColumn)
453       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
454     if(_selectionMinCol <= ChatLineModel::SenderColumn)
455       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
456     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
457   }
458   return result;
459 }
460
461 void ChatScene::requestBacklog() {
462   static const int REQUEST_COUNT = 500;
463   int backlogSize = model()->rowCount();
464   if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
465     QModelIndex msgIdx = model()->index(0, 0);
466     MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
467     BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
468     _lastBacklogSize = backlogSize;
469     Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
470   }
471 }
472
473 int ChatScene::sectionByScenePos(int x) {
474   if(x < firstColHandle->x())
475     return ChatLineModel::TimestampColumn;
476   if(x < secondColHandle->x())
477     return ChatLineModel::SenderColumn;
478
479   return ChatLineModel::ContentsColumn;
480 }
481
482 void ChatScene::updateSceneRect(const QRectF &rect) {
483   _sceneRect = rect;
484   setSceneRect(rect);
485 }
486
487
488 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
489 #ifndef HAVE_WEBKIT
490   Q_UNUSED(parentItem)
491   Q_UNUSED(url)
492   Q_UNUSED(urlRect)
493 #else
494   if(webPreview.parentItem != parentItem)
495     webPreview.parentItem = parentItem;
496
497   if(webPreview.url != url) {
498     webPreview.url = url;
499     // load a new web view and delete the old one (if exists)
500     if(webPreview.previewItem) {
501       removeItem(webPreview.previewItem);
502       delete webPreview.previewItem;
503     }
504     webPreview.previewItem = new WebPreviewItem(url);
505     addItem(webPreview.previewItem);
506   }
507   if(webPreview.urlRect != urlRect) {
508     webPreview.urlRect = urlRect;
509     qreal previewY = urlRect.bottom();
510     qreal previewX = urlRect.x();
511     if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
512       previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
513
514     if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
515       previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
516
517     webPreview.previewItem->setPos(previewX, previewY);
518   }
519 #endif
520 }
521
522 void ChatScene::clearWebPreview(ChatItem *parentItem) {
523 #ifndef HAVE_WEBKIT
524   Q_UNUSED(parentItem)
525 #else
526   if(parentItem == 0 || webPreview.parentItem == parentItem) {
527     if(webPreview.previewItem) {
528       removeItem(webPreview.previewItem);
529       delete webPreview.previewItem;
530       webPreview.previewItem = 0;
531     }
532     webPreview.parentItem = 0;
533     webPreview.url = QString();
534     webPreview.urlRect = QRectF();
535   }
536 #endif
537 }