1 /***************************************************************************
2 * Copyright (C) 2005-2020 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 UiStyle::FormatContainer formatRanges = QtUi::style()->toTextLayoutList(
147 layout->text().length(),
148 data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>()
150 UiStyle::setTextLayoutFormats(*layout, formatRanges);
153 void ChatItem::initLayout(QTextLayout* layout) const
155 initLayoutHelper(layout, QTextOption::NoWrap);
159 void ChatItem::doLayout(QTextLayout* layout) const
161 layout->beginLayout();
162 QTextLine line = layout->createLine();
163 if (line.isValid()) {
164 line.setLineWidth(width());
165 line.setPosition(QPointF(0, 0));
170 UiStyle::FormatList ChatItem::formatList() const
172 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
175 qint16 ChatItem::posToCursor(const QPointF& posInLine) const
177 QPointF pos = mapFromLine(posInLine);
178 if (pos.y() > height())
179 return data(MessageModel::DisplayRole).toString().length();
183 for (int l = layout()->lineCount() - 1; l >= 0; l--) {
184 QTextLine line = layout()->lineAt(l);
185 if (pos.y() >= line.y()) {
186 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
192 void ChatItem::paintBackground(QPainter* painter)
195 if (_selectionMode == FullSelection)
196 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
198 bgBrush = data(ChatLineModel::BackgroundRole);
199 if (bgBrush.isValid())
200 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
203 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
204 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
205 void ChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
210 painter->setClipRect(boundingRect());
211 paintBackground(painter);
213 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
215 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
218 // uncomment partially or all of the following stuff:
220 // 0) alternativ painter color for debug stuff
222 // painter->setPen(Qt::red);
224 // painter->setPen(Qt::blue);
225 // 1) draw wordwrap points in the first line
226 // if(column() == 2) {
227 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
228 // foreach(ChatLineModel::Word word, wrapList) {
229 // if(word.endX > width())
231 // painter->drawLine(word.endX, 0, word.endX, height());
234 // 2) draw MsgId over the time column
235 // if(column() == 0) {
236 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toLongLong());
237 // QPointF bottomPoint = boundingRect().bottomLeft();
238 // bottomPoint.ry() -= 2;
239 // painter->drawText(bottomPoint, msgIdString);
241 // 3) draw bounding rect
242 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
247 void ChatItem::overlayFormat(UiStyle::FormatList& fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const
249 for (size_t i = 0; i < fmtList.size(); i++) {
250 int fmtStart = fmtList.at(i).first;
251 int fmtEnd = (i < fmtList.size() - 1 ? fmtList.at(i + 1).first : data(MessageModel::DisplayRole).toString().length());
258 // split the format if necessary
259 if (fmtStart < start) {
260 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
261 fmtList[++i].first = start;
264 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
265 fmtList[i + 1].first = end;
268 fmtList[i].second.type |= overlayFmt;
272 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const
274 // Calculate formats to overlay (only) if there's a selection, and/or a hovered clickable
275 if (!hasSelection() && !hasActiveClickable()) {
279 using Label = UiStyle::MessageLabel;
280 using Format = UiStyle::Format;
282 auto itemLabel = data(ChatLineModel::MsgLabelRole).value<Label>();
283 const auto& fmtList = formatList();
292 // Transform formatList() into an extended list of LabelFormats
293 std::vector<LabelFormat> labelFmtList;
294 std::transform(fmtList.cbegin(), fmtList.cend(), std::back_inserter(labelFmtList), [itemLabel](const std::pair<quint16, Format>& f) {
295 return LabelFormat{f.first, f.second, itemLabel};
297 // Append dummy element to avoid special-casing handling the last real format
298 labelFmtList.push_back(LabelFormat{quint16(data(MessageModel::DisplayRole).toString().length()), Format(), itemLabel});
300 // Apply the given label to the given range in the format list, splitting formats as necessary
301 auto applyLabel = [&labelFmtList](quint16 start, quint16 end, Label label) {
304 // Skip unaffected formats
305 for (; i < labelFmtList.size() - 1; ++i) {
306 if (labelFmtList[i + 1].offset > start)
309 // Range start doesn't align; split affected format and let the index point to the newly inserted copy
310 if (labelFmtList[i].offset < start) {
311 labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
312 labelFmtList[++i].offset = start;
315 // Apply label to formats fully affected
316 for (; i < labelFmtList.size() - 1; ++i) {
317 if (labelFmtList[i + 1].offset <= end) {
318 labelFmtList[i].label |= label;
321 // Last affected format, split if end of range doesn't align
322 if (labelFmtList[i + 1].offset > end) {
323 labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
324 labelFmtList[i].label |= label;
325 labelFmtList[i + 1].offset = end;
331 // Apply selection label
332 if (hasSelection()) {
334 if (_selectionMode == FullSelection) {
336 end = data(MessageModel::DisplayRole).toString().length();
339 start = qMin(_selectionStart, _selectionEnd);
340 end = qMax(_selectionStart, _selectionEnd);
342 applyLabel(start, end, Label::Selected);
345 // Apply hovered label
346 if (hasActiveClickable()) {
347 applyLabel(activeClickableRange().first, activeClickableRange().second, Label::Hovered);
350 // Add all formats that have an extra label to the additionalFormats list
351 UiStyle::FormatContainer additionalFormats;
352 for (size_t i = 0; i < labelFmtList.size() - 1; ++i) {
353 if (labelFmtList[i].label != itemLabel) {
354 additionalFormats << QtUi::style()->toTextLayoutList({std::make_pair(labelFmtList[i].offset, labelFmtList[i].format)},
355 labelFmtList[i + 1].offset,
356 labelFmtList[i].label);
360 return UiStyle::containerToVector(additionalFormats);
363 bool ChatItem::hasSelection() const
365 if (_selectionMode == NoSelection)
367 if (_selectionMode == FullSelection)
370 return _selectionStart != _selectionEnd;
373 QString ChatItem::selection() const
375 if (_selectionMode == FullSelection)
376 return data(MessageModel::DisplayRole).toString();
377 if (_selectionMode == PartialSelection)
378 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
382 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end)
384 _selectionMode = mode;
385 _selectionStart = start;
387 chatLine()->update();
390 void ChatItem::setFullSelection()
392 if (_selectionMode != FullSelection) {
393 _selectionMode = FullSelection;
394 chatLine()->update();
398 void ChatItem::clearSelection()
400 if (_selectionMode != NoSelection) {
401 _selectionMode = NoSelection;
402 chatLine()->update();
406 void ChatItem::continueSelecting(const QPointF& pos)
408 _selectionMode = PartialSelection;
409 _selectionEnd = posToCursor(pos);
410 chatLine()->update();
413 bool ChatItem::isPosOverSelection(const QPointF& pos) const
415 if (_selectionMode == FullSelection)
417 if (_selectionMode == PartialSelection) {
418 int cursor = posToCursor(pos);
419 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
424 bool ChatItem::hasActiveClickable() const
429 std::pair<quint16, quint16> ChatItem::activeClickableRange() const
434 QList<QRectF> ChatItem::findWords(const QString& searchWord, Qt::CaseSensitivity caseSensitive)
436 QList<QRectF> resultList;
437 const QAbstractItemModel* model_ = model();
441 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
442 QList<int> indexList;
443 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
444 while (searchIdx != -1) {
445 indexList << searchIdx;
446 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
449 foreach (int idx, indexList) {
450 QTextLine line = layout()->lineForTextPosition(idx);
451 qreal x = line.cursorToX(idx);
452 qreal width = line.cursorToX(idx + searchWord.count()) - x;
453 qreal height = line.height();
454 qreal y = height * line.lineNumber();
455 resultList << QRectF(x, y, width, height);
461 void ChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
463 // single clicks are already handled by the scene (for clearing the selection)
464 if (clickMode == ChatScene::DragStartClick) {
465 chatScene()->setSelectingItem(this);
466 _selectionStart = _selectionEnd = posToCursor(pos);
467 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
468 chatLine()->update();
472 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
474 if (event->buttons() == Qt::LeftButton) {
475 if (boundingRect().contains(event->pos())) {
476 qint16 end = posToCursor(event->pos());
477 if (end != _selectionEnd) {
479 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
480 chatLine()->update();
485 chatScene()->startGlobalSelection(this, event->pos());
494 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
496 if (event->buttons() == Qt::LeftButton)
502 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
504 if (_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
505 chatScene()->selectionToClipboard(QClipboard::Selection);
512 void ChatItem::addActionsToMenu(QMenu* menu, const QPointF& pos)
516 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
519 // ************************************************************
521 // ************************************************************
523 void SenderChatItem::initLayout(QTextLayout* layout) const
525 initLayoutHelper(layout, QTextOption::ManualWrap, Qt::AlignRight);
529 void SenderChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
534 painter->setClipRect(boundingRect());
535 paintBackground(painter);
537 qreal layoutWidth = layout()->minimumWidth();
539 if (chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
540 offset = qMin(width() - layoutWidth, (qreal)0);
542 offset = qMax(layoutWidth - width(), (qreal)0);
544 if (layoutWidth > width()) {
545 // Draw a nice gradient for longer items
546 // Qt's text drawing with a gradient brush sucks, so we use compositing instead
547 QPixmap pixmap(layout()->boundingRect().toRect().size());
548 pixmap.fill(Qt::transparent);
550 QPainter pixPainter(&pixmap);
551 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
553 // Create alpha channel mask
554 QLinearGradient gradient;
556 gradient.setStart(0, 0);
557 gradient.setFinalStop(12, 0);
558 gradient.setColorAt(0, Qt::transparent);
559 gradient.setColorAt(1, Qt::white);
562 gradient.setStart(width() - 10, 0);
563 gradient.setFinalStop(width(), 0);
564 gradient.setColorAt(0, Qt::white);
565 gradient.setColorAt(1, Qt::transparent);
567 pixPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn); // gradient's alpha gets applied to the pixmap
568 pixPainter.fillRect(pixmap.rect(), gradient);
569 painter->drawPixmap(pos(), pixmap);
572 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
577 void SenderChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
579 if (clickMode == ChatScene::DoubleClick) {
580 BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
581 QString nick = data(MessageModel::EditRole).toString();
582 // check if the nick is a valid ircUser
583 if (!nick.isEmpty() && Client::network(curBufInfo.networkId())->ircUser(nick))
584 Client::bufferModel()->switchToOrStartQuery(curBufInfo.networkId(), nick);
587 ChatItem::handleClick(pos, clickMode);
590 // ************************************************************
592 // ************************************************************
594 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
596 ContentsChatItem::ContentsChatItem(const QPointF& pos, const qreal& width, ChatLine* parent)
597 : ChatItem(QRectF(pos, QSizeF(width, 0)), parent)
601 setGeometryByWidth(width);
604 QFontMetricsF* ContentsChatItem::fontMetrics() const
606 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second.type,
607 UiStyle::MessageLabel::None);
610 ContentsChatItem::~ContentsChatItem()
615 void ContentsChatItem::clearCache()
619 ChatItem::clearCache();
622 ContentsChatItemPrivate* ContentsChatItem::privateData() const
625 auto* that = const_cast<ContentsChatItem*>(this);
626 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
631 qreal ContentsChatItem::setGeometryByWidth(qreal w)
633 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
637 WrapColumnFinder finder(this);
638 while (finder.nextWrapColumn(w) > 0)
640 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
641 qreal h = lines * spacing;
645 if (w != width() || h != height())
651 void ContentsChatItem::initLayout(QTextLayout* layout) const
653 initLayoutHelper(layout, QTextOption::WrapAtWordBoundaryOrAnywhere);
657 void ContentsChatItem::doLayout(QTextLayout* layout) const
659 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
660 if (!wrapList.count())
661 return; // empty chatitem
664 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
665 WrapColumnFinder finder(this);
666 layout->beginLayout();
669 QTextLine line = layout->createLine();
673 int col = finder.nextWrapColumn(width());
675 col = layout->text().length();
676 int num = col - line.textStart();
678 line.setNumColumns(num);
680 // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
681 // We verify this and try setting the width again, making it shorter each time until the lengths match.
682 // Dead fugly, but seems to work…
683 for (int i = line.textLength() - 1; i >= 0 && line.textLength() > num; i--) {
684 line.setNumColumns(i);
686 if (num != line.textLength()) {
687 qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
688 // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
691 line.setPosition(QPointF(0, h));
697 bool ContentsChatItem::hasActiveClickable() const
699 return privateData()->currentClickable.isValid();
702 std::pair<quint16, quint16> ContentsChatItem::activeClickableRange() const
704 const auto& clickable = privateData()->currentClickable;
705 if (clickable.isValid()) {
706 return {clickable.start(), clickable.start() + clickable.length()};
711 Clickable ContentsChatItem::clickableAt(const QPointF& pos) const
713 return privateData()->clickables.atCursorPos(posToCursor(pos));
716 UiStyle::FormatList ContentsChatItem::formatList() const
718 UiStyle::FormatList fmtList = ChatItem::formatList();
719 for (size_t i = 0; i < privateData()->clickables.size(); i++) {
720 Clickable click = privateData()->clickables.at(i);
721 if (click.type() == Clickable::Url) {
722 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::FormatType::Url);
728 void ContentsChatItem::endHoverMode()
731 if (privateData()->currentClickable.isValid()) {
732 chatLine()->unsetCursor();
733 privateData()->currentClickable = Clickable();
736 chatLine()->update();
740 void ContentsChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
742 if (clickMode == ChatScene::SingleClick) {
743 qint16 idx = posToCursor(pos);
744 Clickable foo = privateData()->clickables.atCursorPos(idx);
746 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
747 QString text = data(ChatLineModel::DisplayRole).toString();
748 foo.activate(networkId, text);
751 else if (clickMode == ChatScene::DoubleClick) {
752 chatScene()->setSelectingItem(this);
753 setSelectionMode(PartialSelection);
754 Clickable click = clickableAt(pos);
755 if (click.isValid()) {
756 setSelectionStart(click.start());
757 setSelectionEnd(click.start() + click.length());
760 // find word boundary
761 QString str = data(ChatLineModel::DisplayRole).toString();
762 qint16 cursor = posToCursor(pos);
763 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
764 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
767 setSelectionStart(start);
768 setSelectionEnd(end);
770 chatLine()->update();
772 else if (clickMode == ChatScene::TripleClick) {
773 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
775 ChatItem::handleClick(pos, clickMode);
778 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
780 // mouse move events always mean we're not hovering anymore...
782 ChatItem::mouseMoveEvent(event);
785 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
791 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
793 bool onClickable = false;
794 Clickable click = clickableAt(event->pos());
795 if (click.isValid()) {
796 if (click.type() == Clickable::Url) {
798 showWebPreview(click);
800 else if (click.type() == Clickable::Channel) {
801 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
802 // don't make clickable if it's our own name
803 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
804 if (Client::networkModel()->bufferName(myId) != name)
808 chatLine()->setCursor(Qt::PointingHandCursor);
809 privateData()->currentClickable = click;
810 chatLine()->update();
819 void ContentsChatItem::addActionsToMenu(QMenu* menu, const QPointF& pos)
821 if (privateData()->currentClickable.isValid()) {
822 Clickable click = privateData()->currentClickable;
823 switch (click.type()) {
824 case Clickable::Url: {
825 privateData()->activeClickable = click;
826 auto action = new Action{icon::get("edit-copy"), tr("Copy Link Address"), menu, &_actionProxy, &ActionProxy::copyLinkToClipboard};
827 action->setData(QVariant::fromValue(static_cast<void*>(this)));
828 menu->addAction(action);
831 case Clickable::Channel: {
832 // Remove existing menu actions, they confuse us when right-clicking on a clickable
834 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
835 GraphicalUi::contextMenuActionProvider()->addActions(menu,
836 chatScene()->filter(),
837 data(MessageModel::BufferIdRole).value<BufferId>(),
846 // Buffer-specific actions
847 ChatItem::addActionsToMenu(menu, pos);
851 void ContentsChatItem::copyLinkToClipboard()
853 Clickable click = privateData()->activeClickable;
854 if (click.isValid() && click.type() == Clickable::Url) {
855 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
856 if (!url.contains("://"))
857 url = "http://" + url;
858 chatScene()->stringToClipboard(url);
862 /******** WEB PREVIEW *****************************************************************************/
864 void ContentsChatItem::showWebPreview(const Clickable& click)
866 #if !defined HAVE_WEBKIT && !defined HAVE_WEBENGINE
869 QTextLine line = layout()->lineForTextPosition(click.start());
870 qreal x = line.cursorToX(click.start());
871 qreal width = line.cursorToX(click.start() + click.length()) - x;
872 qreal height = line.height();
873 qreal y = height * line.lineNumber();
875 QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
876 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
878 QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
879 if (!urlstr.contains("://"))
880 urlstr = "http://" + urlstr;
881 QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
882 chatScene()->loadWebPreview(this, url, urlRect);
886 void ContentsChatItem::clearWebPreview()
888 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
889 chatScene()->clearWebPreview(this);
893 /*************************************************************************************************/
895 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem* _item)
897 , wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>())
903 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width)
905 if (wordidx >= wrapList.count())
909 qreal targetWidth = lineCount * width + choppedTrailing;
911 qint16 start = wordidx;
912 qint16 end = wrapList.count() - 1;
914 // check if the whole line fits
915 if (wrapList.at(end).endX <= targetWidth) // || start == end)
918 // check if we have a very long word that needs inter word wrap
919 if (wrapList.at(start).endX > targetWidth) {
920 if (!line.isValid()) {
921 item->initLayoutHelper(&layout, QTextOption::NoWrap);
922 layout.beginLayout();
923 line = layout.createLine();
926 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
930 if (start + 1 == end) {
932 const ChatLineModel::Word& lastWord = wrapList.at(start); // the last word we were able to squeeze in
934 // both cases should be cought preliminary
935 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
936 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
938 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
939 return wrapList.at(wordidx).start;
942 qint16 pivot = (end + start) / 2;
943 if (wrapList.at(pivot).endX > targetWidth) {
954 /*************************************************************************************************/