giving the chatscene more control over the webpreview thus making it less crashy
[quassel.git] / src / qtui / chatitem.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 <QDesktopServices>
24 #include <QFontMetrics>
25 #include <QGraphicsSceneMouseEvent>
26 #include <QPainter>
27 #include <QPalette>
28 #include <QTextLayout>
29
30 #include "chatitem.h"
31 #include "chatlinemodel.h"
32 #include "qtui.h"
33 #include "qtuistyle.h"
34
35 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
36   : QGraphicsItem(parent),
37     _data(0),
38     _boundingRect(0, 0, width, height),
39     _selectionMode(NoSelection),
40     _selectionStart(-1)
41 {
42   setAcceptHoverEvents(true);
43   setZValue(20);
44   setPos(pos);
45 }
46
47 ChatItem::~ChatItem() {
48   delete _data;
49 }
50
51 QVariant ChatItem::data(int role) const {
52   QModelIndex index = model()->index(row(), column());
53   if(!index.isValid()) {
54     qWarning() << "ChatItem::data(): model index is invalid!" << index;
55     return QVariant();
56   }
57   return model()->data(index, role);
58 }
59
60 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
61   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
62
63   QTextOption option;
64   option.setWrapMode(wrapMode);
65   option.setAlignment(alignment);
66   layout->setTextOption(option);
67
68   QList<QTextLayout::FormatRange> formatRanges
69          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
70   layout->setAdditionalFormats(formatRanges);
71   return layout;
72 }
73
74 void ChatItem::updateLayout() {
75   if(!privateData()) {
76     setPrivateData(new ChatItemPrivate(createLayout()));
77   }
78   QTextLayout *layout_ = layout();
79   layout_->beginLayout();
80   QTextLine line = layout_->createLine();
81   if(line.isValid()) {
82     line.setLineWidth(width());
83     line.setPosition(QPointF(0,0));
84   }
85   layout_->endLayout();
86 }
87
88 void ChatItem::clearLayout() {
89   delete _data;
90   _data = 0;
91 }
92
93 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
94 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
95 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
96   Q_UNUSED(option); Q_UNUSED(widget);
97   if(!hasLayout())
98     updateLayout();
99   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
100   //if(_selectionMode == FullSelection) {
101     //painter->save();
102     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
103     //painter->restore();
104   //}
105   QVector<QTextLayout::FormatRange> formats = additionalFormats();
106   if(_selectionMode != NoSelection) {
107     QTextLayout::FormatRange selectFmt;
108     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
109     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
110     if(_selectionMode == PartialSelection) {
111       selectFmt.start = qMin(_selectionStart, _selectionEnd);
112       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
113     } else { // FullSelection
114       selectFmt.start = 0;
115       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
116     }
117     formats.append(selectFmt);
118   }
119   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
120
121   // Debuging Stuff
122   // uncomment the following lines to draw the bounding rect and the row number in alternating colors
123 //   if(row() % 2)
124 //     painter->setPen(Qt::red);
125 //   else
126 //     painter->setPen(Qt::blue);
127 //   QString rowString = QString::number(row());
128 //   QRect rowRect = painter->fontMetrics().boundingRect(rowString);
129 //   QPointF topPoint = _boundingRect.topLeft();
130 //   topPoint.ry() += rowRect.height();
131 //   painter->drawText(topPoint, rowString);
132 //   QPointF bottomPoint = _boundingRect.bottomRight();
133 //   bottomPoint.rx() -= rowRect.width();
134 //   painter->drawText(bottomPoint, rowString);
135 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
136 }
137
138 qint16 ChatItem::posToCursor(const QPointF &pos) {
139   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
140   if(pos.y() < 0) return 0;
141   if(!hasLayout())
142     updateLayout();
143   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
144     QTextLine line = layout()->lineAt(l);
145     if(pos.y() >= line.y()) {
146       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
147     }
148   }
149   return 0;
150 }
151
152 void ChatItem::setFullSelection() {
153   if(_selectionMode != FullSelection) {
154     _selectionMode = FullSelection;
155     update();
156   }
157 }
158
159 void ChatItem::clearSelection() {
160   _selectionMode = NoSelection;
161   update();
162 }
163
164 void ChatItem::continueSelecting(const QPointF &pos) {
165   _selectionMode = PartialSelection;
166   _selectionEnd = posToCursor(pos);
167   update();
168 }
169
170 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
171   QList<QRectF> resultList;
172   const QAbstractItemModel *model_ = model();
173   if(!model_)
174     return resultList;
175
176   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
177   QList<int> indexList;
178   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
179   while(searchIdx != -1) {
180     indexList << searchIdx;
181     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
182   }
183
184   bool hadLayout = hasLayout();
185   if(!hadLayout)
186     updateLayout();
187
188   foreach(int idx, indexList) {
189     QTextLine line = layout()->lineForTextPosition(idx);
190     qreal x = line.cursorToX(idx);
191     qreal width = line.cursorToX(idx + searchWord.count()) - x;
192     qreal height = line.height();
193     qreal y = height * line.lineNumber();
194     resultList << QRectF(x, y, width, height);
195   }
196
197   if(!hadLayout)
198     clearLayout();
199   return resultList;
200 }
201
202 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
203   if(event->buttons() == Qt::LeftButton) {
204     chatScene()->setSelectingItem(this);
205     _selectionStart = _selectionEnd = posToCursor(event->pos());
206     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
207     update();
208     event->accept();
209   } else {
210     event->ignore();
211   }
212 }
213
214 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
215   if(event->buttons() == Qt::LeftButton) {
216     if(contains(event->pos())) {
217       qint16 end = posToCursor(event->pos());
218       if(end != _selectionEnd) {
219         _selectionEnd = end;
220         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
221         update();
222       }
223     } else {
224       setFullSelection();
225       chatScene()->startGlobalSelection(this, event->pos());
226     }
227     event->accept();
228   } else {
229     event->ignore();
230   }
231 }
232
233 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
234   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
235     _selectionEnd = posToCursor(event->pos());
236     QString selection
237         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
238     chatScene()->putToClipboard(selection);
239     event->accept();
240   } else {
241     event->ignore();
242   }
243 }
244
245 // ************************************************************
246 // SenderChatItem
247 // ************************************************************
248
249 // ************************************************************
250 // ContentsChatItem
251 // ************************************************************
252 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
253   : ChatItem(0, 0, pos, parent)
254 {
255   const QAbstractItemModel *model_ = model();
256   QModelIndex index = model_->index(row(), column());
257   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
258
259   setGeometryByWidth(width);
260 }
261
262 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
263   if(w != width()) {
264     setWidth(w);
265     // compute height
266     int lines = 1;
267     WrapColumnFinder finder(this);
268     while(finder.nextWrapColumn() > 0)
269       lines++;
270     setHeight(lines * fontMetrics()->lineSpacing());
271   }
272   return height();
273 }
274
275 void ContentsChatItem::updateLayout() {
276   if(!privateData()) {
277     ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere), findClickables(), this);
278     setPrivateData(data);
279   }
280
281   // Now layout
282   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
283   if(!wrapList.count()) return; // empty chatitem
284
285   qreal h = 0;
286   WrapColumnFinder finder(this);
287   layout()->beginLayout();
288   forever {
289     QTextLine line = layout()->createLine();
290     if(!line.isValid())
291       break;
292
293     int col = finder.nextWrapColumn();
294     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
295     line.setPosition(QPointF(0, h));
296     h += fontMetrics()->lineSpacing();
297   }
298   layout()->endLayout();
299 }
300
301 // NOTE: This method is not threadsafe and not reentrant!
302 //       (RegExps are not constant while matching, and they are static here for efficiency)
303 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
304   // For matching URLs
305   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
306   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
307
308   static QRegExp regExp[] = {
309     // URL
310     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
311     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
312
313     // Channel name
314     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
315     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
316
317     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
318   };
319
320   static const int regExpCount = 2;  // number of regexps in the array above
321
322   qint16 matches[] = { 0, 0, 0 };
323   qint16 matchEnd[] = { 0, 0, 0 };
324
325   QString str = data(ChatLineModel::DisplayRole).toString();
326
327   QList<Clickable> result;
328   qint16 idx = 0;
329   qint16 minidx;
330   int type = -1;
331
332   do {
333     type = -1;
334     minidx = str.length();
335     for(int i = 0; i < regExpCount; i++) {
336       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
337       if(idx >= matchEnd[i]) {
338         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
339         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
340       }
341       if(matches[i] >= 0 && matches[i] < minidx) {
342         minidx = matches[i];
343         type = i;
344       }
345     }
346     if(type >= 0) {
347       idx = matchEnd[type];
348       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
349         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
350       }
351       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
352     }
353   } while(type >= 0);
354
355   /* testing
356   if(!result.isEmpty()) qDebug() << str;
357   foreach(Clickable click, result) {
358     qDebug() << str.mid(click.start, click.length);
359   }
360   */
361   return result;
362 }
363
364 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
365   // mark a clickable if hovered upon
366   QVector<QTextLayout::FormatRange> fmt;
367   if(privateData()->currentClickable.isValid()) {
368     Clickable click = privateData()->currentClickable;
369     QTextLayout::FormatRange f;
370     f.start = click.start;
371     f.length = click.length;
372     f.format.setFontUnderline(true);
373     fmt.append(f);
374   }
375   return fmt;
376 }
377
378 void ContentsChatItem::endHoverMode() {
379   if(hasLayout()) {
380     if(privateData()->currentClickable.isValid()) {
381       setCursor(Qt::ArrowCursor);
382       privateData()->currentClickable = Clickable();
383     }
384     clearWebPreview();
385     update();
386   }
387 }
388
389 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
390   privateData()->hasDragged = false;
391   ChatItem::mousePressEvent(event);
392 }
393
394 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
395   if(!event->buttons() && !privateData()->hasDragged) {
396     // got a click
397     Clickable click = privateData()->currentClickable;
398     if(click.isValid()) {
399       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
400       switch(click.type) {
401         case Clickable::Url:
402           if(!str.contains("://"))
403             str = "http://" + str;
404           QDesktopServices::openUrl(str);
405           break;
406         case Clickable::Channel:
407           // TODO join or whatever...
408           break;
409         default:
410           break;
411       }
412     }
413   }
414   ChatItem::mouseReleaseEvent(event);
415 }
416
417 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
418   // mouse move events always mean we're not hovering anymore...
419   endHoverMode();
420   // also, check if we have dragged the mouse
421   if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
422     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
423     privateData()->hasDragged = true;
424   ChatItem::mouseMoveEvent(event);
425 }
426
427 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
428   endHoverMode();
429   event->accept();
430 }
431
432 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
433   bool onClickable = false;
434   qint16 idx = posToCursor(event->pos());
435   for(int i = 0; i < privateData()->clickables.count(); i++) {
436     Clickable click = privateData()->clickables.at(i);
437     if(idx >= click.start && idx < click.start + click.length) {
438       if(click.type == Clickable::Url) {
439         onClickable = true;
440         showWebPreview(click);
441       } else if(click.type == Clickable::Channel) {
442         // TODO: don't make clickable if it's our own name
443         //onClickable = true; //FIXME disabled for now
444       }
445       if(onClickable) {
446         setCursor(Qt::PointingHandCursor);
447         privateData()->currentClickable = click;
448         update();
449         break;
450       }
451     }
452   }
453   if(!onClickable) endHoverMode();
454   event->accept();
455 }
456
457 void ContentsChatItem::showWebPreview(const Clickable &click) {
458 #ifdef HAVE_WEBKIT
459   if(!hasLayout())
460     updateLayout();
461
462   QTextLine line = layout()->lineForTextPosition(click.start);
463   qreal x = line.cursorToX(click.start);
464   qreal width = line.cursorToX(click.start + click.length) - x;
465   qreal height = line.height();
466   qreal y = height * line.lineNumber();
467
468   QPointF topLeft = scenePos() + QPointF(x, y);
469   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
470
471   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
472   if(!url.contains("://"))
473     url = "http://" + url;
474   chatScene()->loadWebPreview(this, url, urlRect);
475 #endif
476 }
477
478 void ContentsChatItem::clearWebPreview() {
479 #ifdef HAVE_WEBKIT
480   chatScene()->clearWebPreview(this);
481 #endif
482 }
483
484 /*************************************************************************************************/
485
486 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
487   : item(_item),
488     layout(0),
489     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
490     wordidx(0),
491     lineCount(0),
492     choppedTrailing(0)
493 {
494 }
495
496 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
497   delete layout;
498 }
499
500 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
501   if(wordidx >= wrapList.count())
502     return -1;
503
504   lineCount++;
505   qreal targetWidth = lineCount * item->width() + choppedTrailing;
506
507   qint16 start = wordidx;
508   qint16 end = wrapList.count() - 1;
509
510   // check if the whole line fits
511   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
512     return -1;
513
514   // check if we have a very long word that needs inter word wrap
515   if(wrapList.at(start).endX > targetWidth) {
516     if(!line.isValid()) {
517       layout = item->createLayout(QTextOption::NoWrap);
518       layout->beginLayout();
519       line = layout->createLine();
520       layout->endLayout();
521     }
522     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
523   }
524
525   while(true) {
526     if(start + 1 == end) {
527       wordidx = end;
528       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
529
530       // both cases should be cought preliminary
531       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
532       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
533
534       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
535       return wrapList.at(wordidx).start;
536     }
537
538     qint16 pivot = (end + start) / 2;
539     if(wrapList.at(pivot).endX > targetWidth) {
540       end = pivot;
541     } else {
542       start = pivot;
543     }
544   }
545   Q_ASSERT(false);
546   return -1;
547 }
548