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