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