1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
26 #include <QApplication>
28 #include <QDesktopServices>
29 #include <QFontMetrics>
30 #include <QGraphicsSceneMouseEvent>
33 #include <QTextLayout>
37 #include "buffermodel.h"
38 #include "bufferview.h"
40 #include "chatlinemodel.h"
42 #include "contextmenuactionprovider.h"
46 #include "qtuistyle.h"
48 ChatItem::ChatItem(const QRectF &boundingRect, ChatLine *parent)
50 _boundingRect(boundingRect),
51 _selectionMode(NoSelection),
53 _cachedLayout(nullptr)
64 ChatLine *ChatItem::chatLine() const
70 ChatScene *ChatItem::chatScene() const
72 return chatLine()->chatScene();
76 ChatView *ChatItem::chatView() const
78 return chatScene()->chatView();
82 const QAbstractItemModel *ChatItem::model() const
84 return chatLine()->model();
88 int ChatItem::row() const
90 return chatLine()->row();
94 QPointF ChatItem::mapToLine(const QPointF &p) const
100 QPointF ChatItem::mapFromLine(const QPointF &p) const
106 // relative to the ChatLine
107 QPointF ChatItem::mapToScene(const QPointF &p) const
109 return chatLine()->mapToScene(p /* + pos() */);
113 QPointF ChatItem::mapFromScene(const QPointF &p) const
115 return chatLine()->mapFromScene(p) /* - pos() */;
119 QVariant ChatItem::data(int role) const
121 QModelIndex index = model()->index(row(), column());
122 if (!index.isValid()) {
123 qWarning() << "ChatItem::data(): model index is invalid!" << index;
126 return model()->data(index, role);
130 QTextLayout *ChatItem::layout() const
133 return _cachedLayout;
135 _cachedLayout = new QTextLayout;
136 initLayout(_cachedLayout);
137 chatView()->setHasCache(chatLine());
138 return _cachedLayout;
142 void ChatItem::clearCache()
144 delete _cachedLayout;
145 _cachedLayout = nullptr;
149 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const
153 layout->setText(data(MessageModel::DisplayRole).toString());
156 option.setWrapMode(wrapMode);
157 option.setAlignment(alignment);
158 layout->setTextOption(option);
160 QList<QTextLayout::FormatRange> formatRanges
161 = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>());
162 layout->setAdditionalFormats(formatRanges);
166 void ChatItem::initLayout(QTextLayout *layout) const
168 initLayoutHelper(layout, QTextOption::NoWrap);
173 void ChatItem::doLayout(QTextLayout *layout) const
175 layout->beginLayout();
176 QTextLine line = layout->createLine();
177 if (line.isValid()) {
178 line.setLineWidth(width());
179 line.setPosition(QPointF(0, 0));
185 UiStyle::FormatList ChatItem::formatList() const
187 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
191 qint16 ChatItem::posToCursor(const QPointF &posInLine) const
193 QPointF pos = mapFromLine(posInLine);
194 if (pos.y() > height())
195 return data(MessageModel::DisplayRole).toString().length();
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);
209 void ChatItem::paintBackground(QPainter *painter)
212 if (_selectionMode == FullSelection)
213 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
215 bgBrush = data(ChatLineModel::BackgroundRole);
216 if (bgBrush.isValid())
217 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
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)
225 Q_UNUSED(option); Q_UNUSED(widget);
227 painter->setClipRect(boundingRect());
228 paintBackground(painter);
230 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
232 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
235 // uncomment partially or all of the following stuff:
237 // 0) alternativ painter color for debug stuff
239 // painter->setPen(Qt::red);
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())
248 // painter->drawLine(word.endX, 0, word.endX, height());
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);
258 // 3) draw bounding rect
259 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
265 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const
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());
276 // split the format if necessary
277 if (fmtStart < start) {
278 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
279 fmtList[++i].first = start;
282 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
283 fmtList[i+1].first = end;
286 fmtList[i].second.type |= overlayFmt;
291 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const
293 // Calculate formats to overlay (only) if there's a selection, and/or a hovered clickable
294 if (!hasSelection() && !hasActiveClickable()) {
298 using Label = UiStyle::MessageLabel;
299 using Format = UiStyle::Format;
301 auto itemLabel = data(ChatLineModel::MsgLabelRole).value<Label>();
302 const auto &fmtList = formatList();
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};
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});
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) {
322 // Skip unaffected formats
323 for (; i < labelFmtList.size() - 1; ++i) {
324 if (labelFmtList[i+1].offset > start)
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;
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;
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;
349 // Apply selection label
350 if (hasSelection()) {
352 if (_selectionMode == FullSelection) {
354 end = data(MessageModel::DisplayRole).toString().length();
357 start = qMin(_selectionStart, _selectionEnd);
358 end = qMax(_selectionStart, _selectionEnd);
360 applyLabel(start, end, Label::Selected);
363 // Apply hovered label
364 if (hasActiveClickable()) {
365 applyLabel(activeClickableRange().first, activeClickableRange().second, Label::Hovered);
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);
378 return additionalFormats.toVector();
382 bool ChatItem::hasSelection() const
384 if (_selectionMode == NoSelection)
386 if (_selectionMode == FullSelection)
389 return _selectionStart != _selectionEnd;
393 QString ChatItem::selection() const
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));
403 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end)
405 _selectionMode = mode;
406 _selectionStart = start;
408 chatLine()->update();
412 void ChatItem::setFullSelection()
414 if (_selectionMode != FullSelection) {
415 _selectionMode = FullSelection;
416 chatLine()->update();
421 void ChatItem::clearSelection()
423 if (_selectionMode != NoSelection) {
424 _selectionMode = NoSelection;
425 chatLine()->update();
430 void ChatItem::continueSelecting(const QPointF &pos)
432 _selectionMode = PartialSelection;
433 _selectionEnd = posToCursor(pos);
434 chatLine()->update();
438 bool ChatItem::isPosOverSelection(const QPointF &pos) const
440 if (_selectionMode == FullSelection)
442 if (_selectionMode == PartialSelection) {
443 int cursor = posToCursor(pos);
444 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
450 bool ChatItem::hasActiveClickable() const
456 std::pair<quint16, quint16> ChatItem::activeClickableRange() const
462 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive)
464 QList<QRectF> resultList;
465 const QAbstractItemModel *model_ = model();
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);
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);
490 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
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();
502 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
504 if (event->buttons() == Qt::LeftButton) {
505 if (boundingRect().contains(event->pos())) {
506 qint16 end = posToCursor(event->pos());
507 if (end != _selectionEnd) {
509 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
510 chatLine()->update();
515 chatScene()->startGlobalSelection(this, event->pos());
525 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
527 if (event->buttons() == Qt::LeftButton)
534 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
536 if (_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
537 chatScene()->selectionToClipboard(QClipboard::Selection);
545 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos)
549 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
553 // ************************************************************
555 // ************************************************************
557 void SenderChatItem::initLayout(QTextLayout *layout) const
559 initLayoutHelper(layout, QTextOption::ManualWrap, Qt::AlignRight);
564 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
566 Q_UNUSED(option); Q_UNUSED(widget);
568 painter->setClipRect(boundingRect());
569 paintBackground(painter);
571 qreal layoutWidth = layout()->minimumWidth();
573 if (chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
574 offset = qMin(width() - layoutWidth, (qreal)0);
576 offset = qMax(layoutWidth - width(), (qreal)0);
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);
584 QPainter pixPainter(&pixmap);
585 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
587 // Create alpha channel mask
588 QLinearGradient gradient;
590 gradient.setStart(0, 0);
591 gradient.setFinalStop(12, 0);
592 gradient.setColorAt(0, Qt::transparent);
593 gradient.setColorAt(1, Qt::white);
596 gradient.setStart(width()-10, 0);
597 gradient.setFinalStop(width(), 0);
598 gradient.setColorAt(0, Qt::white);
599 gradient.setColorAt(1, Qt::transparent);
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);
606 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
612 void SenderChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
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);
622 ChatItem::handleClick(pos, clickMode);
626 // ************************************************************
628 // ************************************************************
630 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
632 ContentsChatItem::ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent)
633 : ChatItem(QRectF(pos, QSizeF(width, 0)), parent),
637 setGeometryByWidth(width);
641 QFontMetricsF *ContentsChatItem::fontMetrics() const
643 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second.type, UiStyle::MessageLabel::None);
647 ContentsChatItem::~ContentsChatItem()
653 void ContentsChatItem::clearCache()
657 ChatItem::clearCache();
661 ContentsChatItemPrivate *ContentsChatItem::privateData() const
664 auto *that = const_cast<ContentsChatItem *>(this);
665 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
671 qreal ContentsChatItem::setGeometryByWidth(qreal w)
673 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
677 WrapColumnFinder finder(this);
678 while (finder.nextWrapColumn(w) > 0)
680 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
681 qreal h = lines * spacing;
685 if (w != width() || h != height())
692 void ContentsChatItem::initLayout(QTextLayout *layout) const
694 initLayoutHelper(layout, QTextOption::WrapAtWordBoundaryOrAnywhere);
699 void ContentsChatItem::doLayout(QTextLayout *layout) const
701 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
702 if (!wrapList.count()) return; // empty chatitem
705 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
706 WrapColumnFinder finder(this);
707 layout->beginLayout();
709 QTextLine line = layout->createLine();
713 int col = finder.nextWrapColumn(width());
715 col = layout->text().length();
716 int num = col - line.textStart();
718 line.setNumColumns(num);
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);
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());
731 line.setPosition(QPointF(0, h));
738 bool ContentsChatItem::hasActiveClickable() const
740 return privateData()->currentClickable.isValid();
744 std::pair<quint16, quint16> ContentsChatItem::activeClickableRange() const
746 const auto &clickable = privateData()->currentClickable;
747 if (clickable.isValid()) {
748 return {clickable.start(), clickable.start() + clickable.length()};
754 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const
756 return privateData()->clickables.atCursorPos(posToCursor(pos));
760 UiStyle::FormatList ContentsChatItem::formatList() const
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);
773 void ContentsChatItem::endHoverMode()
776 if (privateData()->currentClickable.isValid()) {
777 chatLine()->unsetCursor();
778 privateData()->currentClickable = Clickable();
781 chatLine()->update();
786 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
788 if (clickMode == ChatScene::SingleClick) {
789 qint16 idx = posToCursor(pos);
790 Clickable foo = privateData()->clickables.atCursorPos(idx);
792 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
793 QString text = data(ChatLineModel::DisplayRole).toString();
794 foo.activate(networkId, text);
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());
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);
815 chatLine()->update();
817 else if (clickMode == ChatScene::TripleClick) {
818 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
820 ChatItem::handleClick(pos, clickMode);
824 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
826 // mouse move events always mean we're not hovering anymore...
828 ChatItem::mouseMoveEvent(event);
832 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
839 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
841 bool onClickable = false;
842 Clickable click = clickableAt(event->pos());
843 if (click.isValid()) {
844 if (click.type() == Clickable::Url) {
846 showWebPreview(click);
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)
856 chatLine()->setCursor(Qt::PointingHandCursor);
857 privateData()->currentClickable = click;
858 chatLine()->update();
862 if (!onClickable) endHoverMode();
867 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos)
869 if (privateData()->currentClickable.isValid()) {
870 Clickable click = privateData()->currentClickable;
871 switch (click.type()) {
874 privateData()->activeClickable = click;
875 auto action = new Action{icon::get("edit-copy"), tr("Copy Link Address"), menu, &_actionProxy, SLOT(copyLinkToClipboard())};
876 action->setData(QVariant::fromValue<void *>(this));
877 menu->addAction(action);
880 case Clickable::Channel:
882 // Remove existing menu actions, they confuse us when right-clicking on a clickable
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);
893 // Buffer-specific actions
894 ChatItem::addActionsToMenu(menu, pos);
899 void ContentsChatItem::copyLinkToClipboard()
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);
911 /******** WEB PREVIEW *****************************************************************************/
913 void ContentsChatItem::showWebPreview(const Clickable &click)
915 #if !defined HAVE_WEBKIT && !defined HAVE_WEBENGINE
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();
924 QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
925 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
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);
936 void ContentsChatItem::clearWebPreview()
938 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
939 chatScene()->clearWebPreview(this);
944 /*************************************************************************************************/
946 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
948 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
956 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width)
958 if (wordidx >= wrapList.count())
962 qreal targetWidth = lineCount * width + choppedTrailing;
964 qint16 start = wordidx;
965 qint16 end = wrapList.count() - 1;
967 // check if the whole line fits
968 if (wrapList.at(end).endX <= targetWidth) // || start == end)
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();
979 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
983 if (start + 1 == end) {
985 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
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
991 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
992 return wrapList.at(wordidx).start;
995 qint16 pivot = (end + start) / 2;
996 if (wrapList.at(pivot).endX > targetWidth) {
1008 /*************************************************************************************************/