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