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