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>
34 #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)
61 ChatLine* ChatItem::chatLine() const
66 ChatScene* ChatItem::chatScene() const
68 return chatLine()->chatScene();
71 ChatView* ChatItem::chatView() const
73 return chatScene()->chatView();
76 const QAbstractItemModel* ChatItem::model() const
78 return chatLine()->model();
81 int ChatItem::row() const
83 return chatLine()->row();
86 QPointF ChatItem::mapToLine(const QPointF& p) const
91 QPointF ChatItem::mapFromLine(const QPointF& p) const
96 // relative to the ChatLine
97 QPointF ChatItem::mapToScene(const QPointF& p) const
99 return chatLine()->mapToScene(p /* + pos() */);
102 QPointF ChatItem::mapFromScene(const QPointF& p) const
104 return chatLine()->mapFromScene(p) /* - pos() */;
107 QVariant ChatItem::data(int role) const
109 QModelIndex index = model()->index(row(), column());
110 if (!index.isValid()) {
111 qWarning() << "ChatItem::data(): model index is invalid!" << index;
114 return model()->data(index, role);
117 QTextLayout* ChatItem::layout() const
120 return _cachedLayout;
122 _cachedLayout = new QTextLayout;
123 initLayout(_cachedLayout);
124 chatView()->setHasCache(chatLine());
125 return _cachedLayout;
128 void ChatItem::clearCache()
130 delete _cachedLayout;
131 _cachedLayout = nullptr;
134 void ChatItem::initLayoutHelper(QTextLayout* layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const
138 layout->setText(data(MessageModel::DisplayRole).toString());
141 option.setWrapMode(wrapMode);
142 option.setAlignment(alignment);
143 layout->setTextOption(option);
145 QList<QTextLayout::FormatRange> formatRanges = QtUi::style()
146 ->toTextLayoutList(formatList(),
147 layout->text().length(),
148 data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>());
149 layout->setAdditionalFormats(formatRanges);
152 void ChatItem::initLayout(QTextLayout* layout) const
154 initLayoutHelper(layout, QTextOption::NoWrap);
158 void ChatItem::doLayout(QTextLayout* layout) const
160 layout->beginLayout();
161 QTextLine line = layout->createLine();
162 if (line.isValid()) {
163 line.setLineWidth(width());
164 line.setPosition(QPointF(0, 0));
169 UiStyle::FormatList ChatItem::formatList() const
171 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
174 qint16 ChatItem::posToCursor(const QPointF& posInLine) const
176 QPointF pos = mapFromLine(posInLine);
177 if (pos.y() > height())
178 return data(MessageModel::DisplayRole).toString().length();
182 for (int l = layout()->lineCount() - 1; l >= 0; l--) {
183 QTextLine line = layout()->lineAt(l);
184 if (pos.y() >= line.y()) {
185 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
191 void ChatItem::paintBackground(QPainter* painter)
194 if (_selectionMode == FullSelection)
195 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
197 bgBrush = data(ChatLineModel::BackgroundRole);
198 if (bgBrush.isValid())
199 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
202 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
203 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
204 void ChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
209 painter->setClipRect(boundingRect());
210 paintBackground(painter);
212 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
214 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
217 // uncomment partially or all of the following stuff:
219 // 0) alternativ painter color for debug stuff
221 // painter->setPen(Qt::red);
223 // painter->setPen(Qt::blue);
224 // 1) draw wordwrap points in the first line
225 // if(column() == 2) {
226 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
227 // foreach(ChatLineModel::Word word, wrapList) {
228 // if(word.endX > width())
230 // painter->drawLine(word.endX, 0, word.endX, height());
233 // 2) draw MsgId over the time column
234 // if(column() == 0) {
235 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toLongLong());
236 // QPointF bottomPoint = boundingRect().bottomLeft();
237 // bottomPoint.ry() -= 2;
238 // painter->drawText(bottomPoint, msgIdString);
240 // 3) draw bounding rect
241 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
246 void ChatItem::overlayFormat(UiStyle::FormatList& fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const
248 for (size_t i = 0; i < fmtList.size(); i++) {
249 int fmtStart = fmtList.at(i).first;
250 int fmtEnd = (i < fmtList.size() - 1 ? fmtList.at(i + 1).first : data(MessageModel::DisplayRole).toString().length());
257 // split the format if necessary
258 if (fmtStart < start) {
259 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
260 fmtList[++i].first = start;
263 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
264 fmtList[i + 1].first = end;
267 fmtList[i].second.type |= overlayFmt;
271 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const
273 // Calculate formats to overlay (only) if there's a selection, and/or a hovered clickable
274 if (!hasSelection() && !hasActiveClickable()) {
278 using Label = UiStyle::MessageLabel;
279 using Format = UiStyle::Format;
281 auto itemLabel = data(ChatLineModel::MsgLabelRole).value<Label>();
282 const auto& fmtList = formatList();
291 // Transform formatList() into an extended list of LabelFormats
292 std::vector<LabelFormat> labelFmtList;
293 std::transform(fmtList.cbegin(), fmtList.cend(), std::back_inserter(labelFmtList), [itemLabel](const std::pair<quint16, Format>& f) {
294 return LabelFormat{f.first, f.second, itemLabel};
296 // Append dummy element to avoid special-casing handling the last real format
297 labelFmtList.push_back(LabelFormat{quint16(data(MessageModel::DisplayRole).toString().length()), Format(), itemLabel});
299 // Apply the given label to the given range in the format list, splitting formats as necessary
300 auto applyLabel = [&labelFmtList](quint16 start, quint16 end, Label label) {
303 // Skip unaffected formats
304 for (; i < labelFmtList.size() - 1; ++i) {
305 if (labelFmtList[i + 1].offset > start)
308 // Range start doesn't align; split affected format and let the index point to the newly inserted copy
309 if (labelFmtList[i].offset < start) {
310 labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
311 labelFmtList[++i].offset = start;
314 // Apply label to formats fully affected
315 for (; i < labelFmtList.size() - 1; ++i) {
316 if (labelFmtList[i + 1].offset <= end) {
317 labelFmtList[i].label |= label;
320 // Last affected format, split if end of range doesn't align
321 if (labelFmtList[i + 1].offset > end) {
322 labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
323 labelFmtList[i].label |= label;
324 labelFmtList[i + 1].offset = end;
330 // Apply selection label
331 if (hasSelection()) {
333 if (_selectionMode == FullSelection) {
335 end = data(MessageModel::DisplayRole).toString().length();
338 start = qMin(_selectionStart, _selectionEnd);
339 end = qMax(_selectionStart, _selectionEnd);
341 applyLabel(start, end, Label::Selected);
344 // Apply hovered label
345 if (hasActiveClickable()) {
346 applyLabel(activeClickableRange().first, activeClickableRange().second, Label::Hovered);
349 // Add all formats that have an extra label to the additionalFormats list
350 QList<QTextLayout::FormatRange> additionalFormats;
351 for (size_t i = 0; i < labelFmtList.size() - 1; ++i) {
352 if (labelFmtList[i].label != itemLabel) {
353 additionalFormats << QtUi::style()->toTextLayoutList({std::make_pair(labelFmtList[i].offset, labelFmtList[i].format)},
354 labelFmtList[i + 1].offset,
355 labelFmtList[i].label);
359 return additionalFormats.toVector();
362 bool ChatItem::hasSelection() const
364 if (_selectionMode == NoSelection)
366 if (_selectionMode == FullSelection)
369 return _selectionStart != _selectionEnd;
372 QString ChatItem::selection() const
374 if (_selectionMode == FullSelection)
375 return data(MessageModel::DisplayRole).toString();
376 if (_selectionMode == PartialSelection)
377 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
381 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end)
383 _selectionMode = mode;
384 _selectionStart = start;
386 chatLine()->update();
389 void ChatItem::setFullSelection()
391 if (_selectionMode != FullSelection) {
392 _selectionMode = FullSelection;
393 chatLine()->update();
397 void ChatItem::clearSelection()
399 if (_selectionMode != NoSelection) {
400 _selectionMode = NoSelection;
401 chatLine()->update();
405 void ChatItem::continueSelecting(const QPointF& pos)
407 _selectionMode = PartialSelection;
408 _selectionEnd = posToCursor(pos);
409 chatLine()->update();
412 bool ChatItem::isPosOverSelection(const QPointF& pos) const
414 if (_selectionMode == FullSelection)
416 if (_selectionMode == PartialSelection) {
417 int cursor = posToCursor(pos);
418 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
423 bool ChatItem::hasActiveClickable() const
428 std::pair<quint16, quint16> ChatItem::activeClickableRange() const
433 QList<QRectF> ChatItem::findWords(const QString& searchWord, Qt::CaseSensitivity caseSensitive)
435 QList<QRectF> resultList;
436 const QAbstractItemModel* model_ = model();
440 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
441 QList<int> indexList;
442 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
443 while (searchIdx != -1) {
444 indexList << searchIdx;
445 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
448 foreach (int idx, indexList) {
449 QTextLine line = layout()->lineForTextPosition(idx);
450 qreal x = line.cursorToX(idx);
451 qreal width = line.cursorToX(idx + searchWord.count()) - x;
452 qreal height = line.height();
453 qreal y = height * line.lineNumber();
454 resultList << QRectF(x, y, width, height);
460 void ChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
462 // single clicks are already handled by the scene (for clearing the selection)
463 if (clickMode == ChatScene::DragStartClick) {
464 chatScene()->setSelectingItem(this);
465 _selectionStart = _selectionEnd = posToCursor(pos);
466 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
467 chatLine()->update();
471 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
473 if (event->buttons() == Qt::LeftButton) {
474 if (boundingRect().contains(event->pos())) {
475 qint16 end = posToCursor(event->pos());
476 if (end != _selectionEnd) {
478 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
479 chatLine()->update();
484 chatScene()->startGlobalSelection(this, event->pos());
493 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
495 if (event->buttons() == Qt::LeftButton)
501 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
503 if (_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
504 chatScene()->selectionToClipboard(QClipboard::Selection);
511 void ChatItem::addActionsToMenu(QMenu* menu, const QPointF& pos)
515 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
518 // ************************************************************
520 // ************************************************************
522 void SenderChatItem::initLayout(QTextLayout* layout) const
524 initLayoutHelper(layout, QTextOption::ManualWrap, Qt::AlignRight);
528 void SenderChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
533 painter->setClipRect(boundingRect());
534 paintBackground(painter);
536 qreal layoutWidth = layout()->minimumWidth();
538 if (chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
539 offset = qMin(width() - layoutWidth, (qreal)0);
541 offset = qMax(layoutWidth - width(), (qreal)0);
543 if (layoutWidth > width()) {
544 // Draw a nice gradient for longer items
545 // Qt's text drawing with a gradient brush sucks, so we use compositing instead
546 QPixmap pixmap(layout()->boundingRect().toRect().size());
547 pixmap.fill(Qt::transparent);
549 QPainter pixPainter(&pixmap);
550 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
552 // Create alpha channel mask
553 QLinearGradient gradient;
555 gradient.setStart(0, 0);
556 gradient.setFinalStop(12, 0);
557 gradient.setColorAt(0, Qt::transparent);
558 gradient.setColorAt(1, Qt::white);
561 gradient.setStart(width() - 10, 0);
562 gradient.setFinalStop(width(), 0);
563 gradient.setColorAt(0, Qt::white);
564 gradient.setColorAt(1, Qt::transparent);
566 pixPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn); // gradient's alpha gets applied to the pixmap
567 pixPainter.fillRect(pixmap.rect(), gradient);
568 painter->drawPixmap(pos(), pixmap);
571 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
576 void SenderChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
578 if (clickMode == ChatScene::DoubleClick) {
579 BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
580 QString nick = data(MessageModel::EditRole).toString();
581 // check if the nick is a valid ircUser
582 if (!nick.isEmpty() && Client::network(curBufInfo.networkId())->ircUser(nick))
583 Client::bufferModel()->switchToOrStartQuery(curBufInfo.networkId(), nick);
586 ChatItem::handleClick(pos, clickMode);
589 // ************************************************************
591 // ************************************************************
593 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
595 ContentsChatItem::ContentsChatItem(const QPointF& pos, const qreal& width, ChatLine* parent)
596 : ChatItem(QRectF(pos, QSizeF(width, 0)), parent)
600 setGeometryByWidth(width);
603 QFontMetricsF* ContentsChatItem::fontMetrics() const
605 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second.type,
606 UiStyle::MessageLabel::None);
609 ContentsChatItem::~ContentsChatItem()
614 void ContentsChatItem::clearCache()
618 ChatItem::clearCache();
621 ContentsChatItemPrivate* ContentsChatItem::privateData() const
624 auto* that = const_cast<ContentsChatItem*>(this);
625 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
630 qreal ContentsChatItem::setGeometryByWidth(qreal w)
632 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
636 WrapColumnFinder finder(this);
637 while (finder.nextWrapColumn(w) > 0)
639 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
640 qreal h = lines * spacing;
644 if (w != width() || h != height())
650 void ContentsChatItem::initLayout(QTextLayout* layout) const
652 initLayoutHelper(layout, QTextOption::WrapAtWordBoundaryOrAnywhere);
656 void ContentsChatItem::doLayout(QTextLayout* layout) const
658 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
659 if (!wrapList.count())
660 return; // empty chatitem
663 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
664 WrapColumnFinder finder(this);
665 layout->beginLayout();
668 QTextLine line = layout->createLine();
672 int col = finder.nextWrapColumn(width());
674 col = layout->text().length();
675 int num = col - line.textStart();
677 line.setNumColumns(num);
679 // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
680 // We verify this and try setting the width again, making it shorter each time until the lengths match.
681 // Dead fugly, but seems to work…
682 for (int i = line.textLength() - 1; i >= 0 && line.textLength() > num; i--) {
683 line.setNumColumns(i);
685 if (num != line.textLength()) {
686 qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
687 // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
690 line.setPosition(QPointF(0, h));
696 bool ContentsChatItem::hasActiveClickable() const
698 return privateData()->currentClickable.isValid();
701 std::pair<quint16, quint16> ContentsChatItem::activeClickableRange() const
703 const auto& clickable = privateData()->currentClickable;
704 if (clickable.isValid()) {
705 return {clickable.start(), clickable.start() + clickable.length()};
710 Clickable ContentsChatItem::clickableAt(const QPointF& pos) const
712 return privateData()->clickables.atCursorPos(posToCursor(pos));
715 UiStyle::FormatList ContentsChatItem::formatList() const
717 UiStyle::FormatList fmtList = ChatItem::formatList();
718 for (size_t i = 0; i < privateData()->clickables.size(); i++) {
719 Clickable click = privateData()->clickables.at(i);
720 if (click.type() == Clickable::Url) {
721 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::FormatType::Url);
727 void ContentsChatItem::endHoverMode()
730 if (privateData()->currentClickable.isValid()) {
731 chatLine()->unsetCursor();
732 privateData()->currentClickable = Clickable();
735 chatLine()->update();
739 void ContentsChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
741 if (clickMode == ChatScene::SingleClick) {
742 qint16 idx = posToCursor(pos);
743 Clickable foo = privateData()->clickables.atCursorPos(idx);
745 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
746 QString text = data(ChatLineModel::DisplayRole).toString();
747 foo.activate(networkId, text);
750 else if (clickMode == ChatScene::DoubleClick) {
751 chatScene()->setSelectingItem(this);
752 setSelectionMode(PartialSelection);
753 Clickable click = clickableAt(pos);
754 if (click.isValid()) {
755 setSelectionStart(click.start());
756 setSelectionEnd(click.start() + click.length());
759 // find word boundary
760 QString str = data(ChatLineModel::DisplayRole).toString();
761 qint16 cursor = posToCursor(pos);
762 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
763 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
766 setSelectionStart(start);
767 setSelectionEnd(end);
769 chatLine()->update();
771 else if (clickMode == ChatScene::TripleClick) {
772 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
774 ChatItem::handleClick(pos, clickMode);
777 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
779 // mouse move events always mean we're not hovering anymore...
781 ChatItem::mouseMoveEvent(event);
784 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
790 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
792 bool onClickable = false;
793 Clickable click = clickableAt(event->pos());
794 if (click.isValid()) {
795 if (click.type() == Clickable::Url) {
797 showWebPreview(click);
799 else if (click.type() == Clickable::Channel) {
800 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
801 // don't make clickable if it's our own name
802 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
803 if (Client::networkModel()->bufferName(myId) != name)
807 chatLine()->setCursor(Qt::PointingHandCursor);
808 privateData()->currentClickable = click;
809 chatLine()->update();
818 void ContentsChatItem::addActionsToMenu(QMenu* menu, const QPointF& pos)
820 if (privateData()->currentClickable.isValid()) {
821 Clickable click = privateData()->currentClickable;
822 switch (click.type()) {
823 case Clickable::Url: {
824 privateData()->activeClickable = click;
825 auto action = new Action{icon::get("edit-copy"), tr("Copy Link Address"), menu, &_actionProxy, &ActionProxy::copyLinkToClipboard};
826 action->setData(QVariant::fromValue<void*>(this));
827 menu->addAction(action);
830 case Clickable::Channel: {
831 // Remove existing menu actions, they confuse us when right-clicking on a clickable
833 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
834 GraphicalUi::contextMenuActionProvider()->addActions(menu,
835 chatScene()->filter(),
836 data(MessageModel::BufferIdRole).value<BufferId>(),
845 // Buffer-specific actions
846 ChatItem::addActionsToMenu(menu, pos);
850 void ContentsChatItem::copyLinkToClipboard()
852 Clickable click = privateData()->activeClickable;
853 if (click.isValid() && click.type() == Clickable::Url) {
854 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
855 if (!url.contains("://"))
856 url = "http://" + url;
857 chatScene()->stringToClipboard(url);
861 /******** WEB PREVIEW *****************************************************************************/
863 void ContentsChatItem::showWebPreview(const Clickable& click)
865 #if !defined HAVE_WEBKIT && !defined HAVE_WEBENGINE
868 QTextLine line = layout()->lineForTextPosition(click.start());
869 qreal x = line.cursorToX(click.start());
870 qreal width = line.cursorToX(click.start() + click.length()) - x;
871 qreal height = line.height();
872 qreal y = height * line.lineNumber();
874 QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
875 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
877 QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
878 if (!urlstr.contains("://"))
879 urlstr = "http://" + urlstr;
880 QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
881 chatScene()->loadWebPreview(this, url, urlRect);
885 void ContentsChatItem::clearWebPreview()
887 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
888 chatScene()->clearWebPreview(this);
892 /*************************************************************************************************/
894 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem* _item)
896 , wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>())
902 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width)
904 if (wordidx >= wrapList.count())
908 qreal targetWidth = lineCount * width + choppedTrailing;
910 qint16 start = wordidx;
911 qint16 end = wrapList.count() - 1;
913 // check if the whole line fits
914 if (wrapList.at(end).endX <= targetWidth) // || start == end)
917 // check if we have a very long word that needs inter word wrap
918 if (wrapList.at(start).endX > targetWidth) {
919 if (!line.isValid()) {
920 item->initLayoutHelper(&layout, QTextOption::NoWrap);
921 layout.beginLayout();
922 line = layout.createLine();
925 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
929 if (start + 1 == end) {
931 const ChatLineModel::Word& lastWord = wrapList.at(start); // the last word we were able to squeeze in
933 // both cases should be cought preliminary
934 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
935 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
937 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
938 return wrapList.at(wordidx).start;
941 qint16 pivot = (end + start) / 2;
942 if (wrapList.at(pivot).endX > targetWidth) {
953 /*************************************************************************************************/