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