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