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