Making channel names clickable
[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 #include <QMenu>
30
31 #include "bufferview.h"
32 #include "chatitem.h"
33 #include "chatlinemodel.h"
34 #include "iconloader.h"
35 #include "mainwin.h"
36 #include "qtui.h"
37 #include "qtuistyle.h"
38
39 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
40   : QGraphicsItem(parent),
41     _data(0),
42     _boundingRect(0, 0, width, height),
43     _selectionMode(NoSelection),
44     _selectionStart(-1)
45 {
46   setAcceptHoverEvents(true);
47   setZValue(20);
48   setPos(pos);
49 }
50
51 ChatItem::~ChatItem() {
52   delete _data;
53 }
54
55 QVariant ChatItem::data(int role) const {
56   QModelIndex index = model()->index(row(), column());
57   if(!index.isValid()) {
58     qWarning() << "ChatItem::data(): model index is invalid!" << index;
59     return QVariant();
60   }
61   return model()->data(index, role);
62 }
63
64 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
65   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
66
67   QTextOption option;
68   option.setWrapMode(wrapMode);
69   option.setAlignment(alignment);
70   layout->setTextOption(option);
71
72   QList<QTextLayout::FormatRange> formatRanges
73          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
74   layout->setAdditionalFormats(formatRanges);
75   return layout;
76 }
77
78 void ChatItem::doLayout() {
79   QTextLayout *layout_ = layout();
80   layout_->beginLayout();
81   QTextLine line = layout_->createLine();
82   if(line.isValid()) {
83     line.setLineWidth(width());
84     line.setPosition(QPointF(0,0));
85   }
86   layout_->endLayout();
87 }
88
89 void ChatItem::clearLayout() {
90   delete _data;
91   _data = 0;
92 }
93
94 ChatItemPrivate *ChatItem::privateData() const {
95   if(!_data) {
96     ChatItem *that = const_cast<ChatItem *>(this);
97     that->_data = that->newPrivateData();
98     that->doLayout();
99   }
100   return _data;
101 }
102
103 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
104 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
105 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
106   Q_UNUSED(option); Q_UNUSED(widget);
107   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
108   QVector<QTextLayout::FormatRange> formats = additionalFormats();
109   QTextLayout::FormatRange selectFmt = selectionFormat();
110   if(selectFmt.format.isValid()) formats.append(selectFmt);
111   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
112
113   // Debuging Stuff
114   // uncomment partially or all of the following stuff:
115   //
116   // 0) alternativ painter color for debug stuff
117 //   if(row() % 2)
118 //     painter->setPen(Qt::red);
119 //   else
120 //     painter->setPen(Qt::blue);
121   // 1) draw wordwrap points in the first line
122 //   if(column() == 2) {
123 //     ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
124 //     foreach(ChatLineModel::Word word, wrapList) {
125 //       if(word.endX > width())
126 //      break;
127 //       painter->drawLine(word.endX, 0, word.endX, height());
128 //     }
129 //   }
130   // 2) draw MsgId over the time column
131 //   if(column() == 0) {
132 //     QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
133 //     QPointF bottomPoint = boundingRect().bottomLeft();
134 //     bottomPoint.ry() -= 2;
135 //     painter->drawText(bottomPoint, msgIdString);
136 //   }
137   // 3) draw bounding rect
138 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
139 }
140
141 qint16 ChatItem::posToCursor(const QPointF &pos) const {
142   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
143   if(pos.y() < 0) return 0;
144   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
145     QTextLine line = layout()->lineAt(l);
146     if(pos.y() >= line.y()) {
147       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
148     }
149   }
150   return 0;
151 }
152
153 bool ChatItem::hasSelection() const {
154   if(_selectionMode == NoSelection)
155     return false;
156   if(_selectionMode == FullSelection)
157     return true;
158   // partial
159   return _selectionStart != _selectionEnd;
160 }
161
162 QString ChatItem::selection() const {
163   if(_selectionMode == FullSelection)
164     return data(MessageModel::DisplayRole).toString();
165   if(_selectionMode == PartialSelection)
166     return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
167   return QString();
168 }
169
170 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
171   _selectionMode = mode;
172   _selectionStart = start;
173   _selectionEnd = end;
174   update();
175 }
176
177 void ChatItem::setFullSelection() {
178   if(_selectionMode != FullSelection) {
179     _selectionMode = FullSelection;
180     update();
181   }
182 }
183
184 void ChatItem::clearSelection() {
185   if(_selectionMode != NoSelection) {
186     _selectionMode = NoSelection;
187     update();
188   }
189 }
190
191 void ChatItem::continueSelecting(const QPointF &pos) {
192   _selectionMode = PartialSelection;
193   _selectionEnd = posToCursor(pos);
194   update();
195 }
196
197 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
198   if(_selectionMode == FullSelection)
199     return true;
200   if(_selectionMode == PartialSelection) {
201     int cursor = posToCursor(pos);
202     return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
203   }
204   return false;
205 }
206
207 QTextLayout::FormatRange ChatItem::selectionFormat() const {
208   QTextLayout::FormatRange selectFmt;
209   if(_selectionMode != NoSelection) {
210     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
211     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
212     if(_selectionMode == PartialSelection) {
213       selectFmt.start = qMin(_selectionStart, _selectionEnd);
214       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
215     } else { // FullSelection
216       selectFmt.start = 0;
217       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
218     }
219   } else {
220     selectFmt.start = -1;
221     selectFmt.length = 0;
222   }
223   return selectFmt;
224 }
225
226 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
227   QList<QRectF> resultList;
228   const QAbstractItemModel *model_ = model();
229   if(!model_)
230     return resultList;
231
232   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
233   QList<int> indexList;
234   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
235   while(searchIdx != -1) {
236     indexList << searchIdx;
237     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
238   }
239
240   bool hadPrivateData = hasPrivateData();
241
242   foreach(int idx, indexList) {
243     QTextLine line = layout()->lineForTextPosition(idx);
244     qreal x = line.cursorToX(idx);
245     qreal width = line.cursorToX(idx + searchWord.count()) - x;
246     qreal height = line.height();
247     qreal y = height * line.lineNumber();
248     resultList << QRectF(x, y, width, height);
249   }
250
251   if(!hadPrivateData)
252     clearLayout();
253   return resultList;
254 }
255
256 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
257   // single clicks are already handled by the scene (for clearing the selection)
258   if(clickMode == ChatScene::DragStartClick) {
259     chatScene()->setSelectingItem(this);
260     _selectionStart = _selectionEnd = posToCursor(pos);
261     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
262     update();
263   }
264 }
265
266 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
267   if(event->buttons() == Qt::LeftButton) {
268     if(contains(event->pos())) {
269       qint16 end = posToCursor(event->pos());
270       if(end != _selectionEnd) {
271         _selectionEnd = end;
272         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
273         update();
274       }
275     } else {
276       setFullSelection();
277       chatScene()->startGlobalSelection(this, event->pos());
278     }
279     event->accept();
280   } else {
281     event->ignore();
282   }
283 }
284
285 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
286   if(event->buttons() == Qt::LeftButton)
287     event->accept();
288   else
289     event->ignore();
290 }
291
292 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
293   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
294     chatScene()->selectionToClipboard(QClipboard::Selection);
295     event->accept();
296   } else
297     event->ignore();
298 }
299
300 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
301   Q_UNUSED(menu);
302   Q_UNUSED(pos);
303
304 }
305
306 // ************************************************************
307 // SenderChatItem
308 // ************************************************************
309
310 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
311   Q_UNUSED(option); Q_UNUSED(widget);
312
313   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
314   qreal layoutWidth = layout()->minimumWidth();
315   qreal offset = 0;
316   if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
317     offset = qMin(width() - layoutWidth, (qreal)0);
318   else
319     offset = qMax(layoutWidth - width(), (qreal)0);
320
321   QTextLayout::FormatRange selectFmt = selectionFormat();
322
323   if(layoutWidth > width()) {
324     // Draw a nice gradient for longer items
325     // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
326     QPixmap pixmap(layout()->boundingRect().toRect().size());
327     pixmap.fill(Qt::transparent);
328     QPainter pixPainter(&pixmap);
329     layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
330     pixPainter.end();
331
332     // Create alpha channel mask
333     QPixmap mask(pixmap.size());
334     QPainter maskPainter(&mask);
335     QLinearGradient gradient;
336     if(offset < 0) {
337       gradient.setStart(0, 0);
338       gradient.setFinalStop(12, 0);
339       gradient.setColorAt(0, Qt::black);
340       gradient.setColorAt(1, Qt::white);
341     } else {
342       gradient.setStart(width()-10, 0);
343       gradient.setFinalStop(width(), 0);
344       gradient.setColorAt(0, Qt::white);
345       gradient.setColorAt(1, Qt::black);
346     }
347     maskPainter.fillRect(boundingRect(), gradient);
348     pixmap.setAlphaChannel(mask);
349     painter->drawPixmap(0, 0, pixmap);
350   } else {
351     layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
352   }
353 }
354
355 // ************************************************************
356 // ContentsChatItem
357 // ************************************************************
358
359 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
360
361 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
362   : ChatItem(0, 0, pos, parent)
363 {
364   const QAbstractItemModel *model_ = model();
365   QModelIndex index = model_->index(row(), column());
366   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
367
368   setGeometryByWidth(width);
369 }
370
371 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
372   if(w != width()) {
373     prepareGeometryChange();
374     setWidth(w);
375     // compute height
376     int lines = 1;
377     WrapColumnFinder finder(this);
378     while(finder.nextWrapColumn() > 0)
379       lines++;
380     setHeight(lines * fontMetrics()->lineSpacing());
381   }
382   return height();
383 }
384
385 void ContentsChatItem::doLayout() {
386   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
387   if(!wrapList.count()) return; // empty chatitem
388
389   qreal h = 0;
390   WrapColumnFinder finder(this);
391   layout()->beginLayout();
392   forever {
393     QTextLine line = layout()->createLine();
394     if(!line.isValid())
395       break;
396
397     int col = finder.nextWrapColumn();
398     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
399     line.setPosition(QPointF(0, h));
400     h += fontMetrics()->lineSpacing();
401   }
402   layout()->endLayout();
403 }
404
405 // NOTE: This method is not threadsafe and not reentrant!
406 //       (RegExps are not constant while matching, and they are static here for efficiency)
407 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
408   // For matching URLs
409   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
410   static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]])");
411
412   static QRegExp regExp[] = {
413     // URL
414     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
415     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|gopher://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
416
417     // Channel name
418     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
419     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
420
421     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
422   };
423
424   static const int regExpCount = 2;  // number of regexps in the array above
425
426   qint16 matches[] = { 0, 0, 0 };
427   qint16 matchEnd[] = { 0, 0, 0 };
428
429   QString str = data(ChatLineModel::DisplayRole).toString();
430
431   QList<Clickable> result;
432   qint16 idx = 0;
433   qint16 minidx;
434   int type = -1;
435
436   do {
437     type = -1;
438     minidx = str.length();
439     for(int i = 0; i < regExpCount; i++) {
440       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
441       if(idx >= matchEnd[i]) {
442         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
443         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
444       }
445       if(matches[i] >= 0 && matches[i] < minidx) {
446         minidx = matches[i];
447         type = i;
448       }
449     }
450     if(type >= 0) {
451       idx = matchEnd[type];
452       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
453         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
454       }
455       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
456     }
457   } while(type >= 0);
458
459   /* testing
460   if(!result.isEmpty()) qDebug() << str;
461   foreach(Clickable click, result) {
462     qDebug() << str.mid(click.start, click.length);
463   }
464   */
465   return result;
466 }
467
468 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
469   qint16 idx = posToCursor(pos);
470   for(int i = 0; i < privateData()->clickables.count(); i++) {
471     Clickable click = privateData()->clickables.at(i);
472     if(idx >= click.start && idx < click.start + click.length)
473       return click;
474   }
475   return Clickable();
476 }
477
478 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
479   // mark a clickable if hovered upon
480   QVector<QTextLayout::FormatRange> fmt;
481   if(privateData()->currentClickable.isValid()) {
482     Clickable click = privateData()->currentClickable;
483     QTextLayout::FormatRange f;
484     f.start = click.start;
485     f.length = click.length;
486     f.format.setFontUnderline(true);
487     fmt.append(f);
488   }
489   return fmt;
490 }
491
492 void ContentsChatItem::endHoverMode() {
493   if(hasPrivateData()) {
494     if(privateData()->currentClickable.isValid()) {
495       setCursor(Qt::ArrowCursor);
496       privateData()->currentClickable = Clickable();
497     }
498     clearWebPreview();
499     update();
500   }
501 }
502
503 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
504   if(clickMode == ChatScene::SingleClick) {
505     Clickable click = clickableAt(pos);
506     if(click.isValid()) {
507       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
508       switch(click.type) {
509         case Clickable::Url:
510           if(!str.contains("://"))
511             str = "http://" + str;
512           QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
513           break;
514         case Clickable::Channel:
515           // TODO join or whatever...
516           break;
517         default:
518           break;
519       }
520     }
521   } else if(clickMode == ChatScene::DoubleClick) {
522     chatScene()->setSelectingItem(this);
523     setSelectionMode(PartialSelection);
524     Clickable click = clickableAt(pos);
525     if(click.isValid()) {
526       setSelectionStart(click.start);
527       setSelectionEnd(click.start + click.length);
528     } else {
529       // find word boundary
530       QString str = data(ChatLineModel::DisplayRole).toString();
531       qint16 cursor = posToCursor(pos);
532       qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
533       qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
534       if(end < 0) end = str.length();
535       setSelectionStart(start);
536       setSelectionEnd(end);
537     }
538     update();
539   } else if(clickMode == ChatScene::TripleClick) {
540     setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
541   }
542   ChatItem::handleClick(pos, clickMode);
543 }
544
545 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
546   // mouse move events always mean we're not hovering anymore...
547   endHoverMode();
548   ChatItem::mouseMoveEvent(event);
549 }
550
551 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
552   endHoverMode();
553   event->accept();
554 }
555
556 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
557   bool onClickable = false;
558   Clickable click = clickableAt(event->pos());
559   if(click.isValid()) {
560     if(click.type == Clickable::Url) {
561       onClickable = true;
562       showWebPreview(click);
563     } else if(click.type == Clickable::Channel) {
564       // don't make clickable if it's our own name
565       QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
566       BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
567       if(Client::networkModel()->bufferName(myId) != name)
568         onClickable = true;
569     }
570     if(onClickable) {
571       setCursor(Qt::PointingHandCursor);
572       privateData()->currentClickable = click;
573       update();
574       return;
575     }
576   }
577   if(!onClickable) endHoverMode();
578   event->accept();
579 }
580
581 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
582   Q_UNUSED(pos); // we assume that the current mouse cursor pos is the point of invocation
583
584   if(privateData()->currentClickable.isValid()) {
585     Clickable click = privateData()->currentClickable;
586     switch(click.type) {
587       case Clickable::Url:
588         privateData()->activeClickable = click;
589         menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
590                          &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
591         break;
592       case Clickable::Channel: {
593         // Hide existing menu actions, they confuse us when right-clicking on a clickable
594         foreach(QAction *action, menu->actions())
595           action->setVisible(false);
596         QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
597         Client::mainUi()->actionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
598         break;
599       }
600       default:
601         break;
602     }
603   } else {
604
605     // Buffer-specific actions
606     Client::mainUi()->actionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
607   }
608 }
609
610 void ContentsChatItem::copyLinkToClipboard() {
611   Clickable click = privateData()->activeClickable;
612   if(click.isValid() && click.type == Clickable::Url) {
613     QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
614     if(!url.contains("://"))
615       url = "http://" + url;
616     chatScene()->stringToClipboard(url);
617   }
618 }
619
620 /******** WEB PREVIEW *****************************************************************************/
621
622 void ContentsChatItem::showWebPreview(const Clickable &click) {
623 #ifndef HAVE_WEBKIT
624   Q_UNUSED(click);
625 #else
626   QTextLine line = layout()->lineForTextPosition(click.start);
627   qreal x = line.cursorToX(click.start);
628   qreal width = line.cursorToX(click.start + click.length) - x;
629   qreal height = line.height();
630   qreal y = height * line.lineNumber();
631
632   QPointF topLeft = scenePos() + QPointF(x, y);
633   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
634
635   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
636   if(!url.contains("://"))
637     url = "http://" + url;
638   chatScene()->loadWebPreview(this, url, urlRect);
639 #endif
640 }
641
642 void ContentsChatItem::clearWebPreview() {
643 #ifdef HAVE_WEBKIT
644   chatScene()->clearWebPreview(this);
645 #endif
646 }
647
648 /*************************************************************************************************/
649
650 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
651   : item(_item),
652     layout(0),
653     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
654     wordidx(0),
655     lineCount(0),
656     choppedTrailing(0)
657 {
658 }
659
660 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
661   delete layout;
662 }
663
664 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
665   if(wordidx >= wrapList.count())
666     return -1;
667
668   lineCount++;
669   qreal targetWidth = lineCount * item->width() + choppedTrailing;
670
671   qint16 start = wordidx;
672   qint16 end = wrapList.count() - 1;
673
674   // check if the whole line fits
675   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
676     return -1;
677
678   // check if we have a very long word that needs inter word wrap
679   if(wrapList.at(start).endX > targetWidth) {
680     if(!line.isValid()) {
681       layout = item->createLayout(QTextOption::NoWrap);
682       layout->beginLayout();
683       line = layout->createLine();
684       layout->endLayout();
685     }
686     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
687   }
688
689   while(true) {
690     if(start + 1 == end) {
691       wordidx = end;
692       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
693
694       // both cases should be cought preliminary
695       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
696       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
697
698       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
699       return wrapList.at(wordidx).start;
700     }
701
702     qint16 pivot = (end + start) / 2;
703     if(wrapList.at(pivot).endX > targetWidth) {
704       end = pivot;
705     } else {
706       start = pivot;
707     }
708   }
709   Q_ASSERT(false);
710   return -1;
711 }
712
713 /*************************************************************************************************/
714