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