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