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