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