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