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>
36 #include "buffermodel.h"
37 #include "bufferview.h"
39 #include "chatlinemodel.h"
41 #include "contextmenuactionprovider.h"
45 #include "qtuistyle.h"
47 ChatItem::ChatItem(const QRectF &boundingRect, ChatLine *parent)
49 _boundingRect(boundingRect),
50 _selectionMode(NoSelection),
63 ChatLine *ChatItem::chatLine() const
69 ChatScene *ChatItem::chatScene() const
71 return chatLine()->chatScene();
75 ChatView *ChatItem::chatView() const
77 return chatScene()->chatView();
81 const QAbstractItemModel *ChatItem::model() const
83 return chatLine()->model();
87 int ChatItem::row() const
89 return chatLine()->row();
93 QPointF ChatItem::mapToLine(const QPointF &p) const
99 QPointF ChatItem::mapFromLine(const QPointF &p) const
105 // relative to the ChatLine
106 QPointF ChatItem::mapToScene(const QPointF &p) const
108 return chatLine()->mapToScene(p /* + pos() */);
112 QPointF ChatItem::mapFromScene(const QPointF &p) const
114 return chatLine()->mapFromScene(p) /* - pos() */;
118 QVariant ChatItem::data(int role) const
120 QModelIndex index = model()->index(row(), column());
121 if (!index.isValid()) {
122 qWarning() << "ChatItem::data(): model index is invalid!" << index;
125 return model()->data(index, role);
129 QTextLayout *ChatItem::layout() const
132 return _cachedLayout;
134 _cachedLayout = new QTextLayout;
135 initLayout(_cachedLayout);
136 chatView()->setHasCache(chatLine());
137 return _cachedLayout;
141 void ChatItem::clearCache()
143 delete _cachedLayout;
148 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const
152 layout->setText(data(MessageModel::DisplayRole).toString());
155 option.setWrapMode(wrapMode);
156 option.setAlignment(alignment);
157 layout->setTextOption(option);
159 QList<QTextLayout::FormatRange> formatRanges
160 = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>());
161 layout->setAdditionalFormats(formatRanges);
165 void ChatItem::initLayout(QTextLayout *layout) const
167 initLayoutHelper(layout, QTextOption::NoWrap);
172 void ChatItem::doLayout(QTextLayout *layout) const
174 layout->beginLayout();
175 QTextLine line = layout->createLine();
176 if (line.isValid()) {
177 line.setLineWidth(width());
178 line.setPosition(QPointF(0, 0));
184 UiStyle::FormatList ChatItem::formatList() const
186 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
190 qint16 ChatItem::posToCursor(const QPointF &posInLine) const
192 QPointF pos = mapFromLine(posInLine);
193 if (pos.y() > height())
194 return data(MessageModel::DisplayRole).toString().length();
198 for (int l = layout()->lineCount() - 1; l >= 0; l--) {
199 QTextLine line = layout()->lineAt(l);
200 if (pos.y() >= line.y()) {
201 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
208 void ChatItem::paintBackground(QPainter *painter)
211 if (_selectionMode == FullSelection)
212 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
214 bgBrush = data(ChatLineModel::BackgroundRole);
215 if (bgBrush.isValid())
216 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
220 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
221 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
222 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
224 Q_UNUSED(option); Q_UNUSED(widget);
226 painter->setClipRect(boundingRect());
227 paintBackground(painter);
229 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
231 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
234 // uncomment partially or all of the following stuff:
236 // 0) alternativ painter color for debug stuff
238 // painter->setPen(Qt::red);
240 // painter->setPen(Qt::blue);
241 // 1) draw wordwrap points in the first line
242 // if(column() == 2) {
243 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
244 // foreach(ChatLineModel::Word word, wrapList) {
245 // if(word.endX > width())
247 // painter->drawLine(word.endX, 0, word.endX, height());
250 // 2) draw MsgId over the time column
251 // if(column() == 0) {
252 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toLongLong());
253 // QPointF bottomPoint = boundingRect().bottomLeft();
254 // bottomPoint.ry() -= 2;
255 // painter->drawText(bottomPoint, msgIdString);
257 // 3) draw bounding rect
258 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
264 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const
266 for (size_t i = 0; i < fmtList.size(); i++) {
267 int fmtStart = fmtList.at(i).first;
268 int fmtEnd = (i < fmtList.size()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
275 // split the format if necessary
276 if (fmtStart < start) {
277 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
278 fmtList[++i].first = start;
281 fmtList.insert(fmtList.begin() + i, fmtList.at(i));
282 fmtList[i+1].first = end;
285 fmtList[i].second.type |= overlayFmt;
290 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const
292 // Calculate formats to overlay (only) if there's a selection, and/or a hovered clickable
293 if (!hasSelection() && !hasActiveClickable()) {
297 using Label = UiStyle::MessageLabel;
298 using Format = UiStyle::Format;
300 Label itemLabel = data(ChatLineModel::MsgLabelRole).value<Label>();
301 const auto &fmtList = formatList();
309 // Transform formatList() into an extended list of LabelFormats
310 std::vector<LabelFormat> labelFmtList;
311 std::transform(fmtList.cbegin(), fmtList.cend(), std::back_inserter(labelFmtList), [itemLabel](const std::pair<quint16, Format> &f) {
312 return LabelFormat{f.first, f.second, itemLabel};
314 // Append dummy element to avoid special-casing handling the last real format
315 labelFmtList.push_back(LabelFormat{quint16(data(MessageModel::DisplayRole).toString().length()), {}, itemLabel});
317 // Apply the given label to the given range in the format list, splitting formats as necessary
318 auto applyLabel = [&labelFmtList](quint16 start, quint16 end, Label label) {
321 // Skip unaffected formats
322 for (; i < labelFmtList.size() - 1; ++i) {
323 if (labelFmtList[i+1].offset > start)
326 // Range start doesn't align; split affected format and let the index point to the newly inserted copy
327 if (labelFmtList[i].offset < start) {
328 labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
329 labelFmtList[++i].offset = start;
332 // Apply label to formats fully affected
333 for (; i < labelFmtList.size() - 1; ++i) {
334 if (labelFmtList[i+1].offset <= end) {
335 labelFmtList[i].label |= label;
338 // Last affected format, split if end of range doesn't align
339 if (labelFmtList[i+1].offset > end) {
340 labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
341 labelFmtList[i].label |= label;
342 labelFmtList[i+1].offset = end;
348 // Apply selection label
349 if (hasSelection()) {
351 if (_selectionMode == FullSelection) {
353 end = data(MessageModel::DisplayRole).toString().length();
356 start = qMin(_selectionStart, _selectionEnd);
357 end = qMax(_selectionStart, _selectionEnd);
359 applyLabel(start, end, Label::Selected);
362 // Apply hovered label
363 if (hasActiveClickable()) {
364 applyLabel(activeClickableRange().first, activeClickableRange().second, Label::Hovered);
367 // Add all formats that have an extra label to the additionalFormats list
368 QList<QTextLayout::FormatRange> additionalFormats;
369 for (size_t i = 0; i < labelFmtList.size() - 1; ++i) {
370 if (labelFmtList[i].label != itemLabel) {
371 additionalFormats << QtUi::style()->toTextLayoutList({std::make_pair(labelFmtList[i].offset, labelFmtList[i].format)},
372 labelFmtList[i+1].offset,
373 labelFmtList[i].label);
377 return additionalFormats.toVector();
381 bool ChatItem::hasSelection() const
383 if (_selectionMode == NoSelection)
385 if (_selectionMode == FullSelection)
388 return _selectionStart != _selectionEnd;
392 QString ChatItem::selection() const
394 if (_selectionMode == FullSelection)
395 return data(MessageModel::DisplayRole).toString();
396 if (_selectionMode == PartialSelection)
397 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
402 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end)
404 _selectionMode = mode;
405 _selectionStart = start;
407 chatLine()->update();
411 void ChatItem::setFullSelection()
413 if (_selectionMode != FullSelection) {
414 _selectionMode = FullSelection;
415 chatLine()->update();
420 void ChatItem::clearSelection()
422 if (_selectionMode != NoSelection) {
423 _selectionMode = NoSelection;
424 chatLine()->update();
429 void ChatItem::continueSelecting(const QPointF &pos)
431 _selectionMode = PartialSelection;
432 _selectionEnd = posToCursor(pos);
433 chatLine()->update();
437 bool ChatItem::isPosOverSelection(const QPointF &pos) const
439 if (_selectionMode == FullSelection)
441 if (_selectionMode == PartialSelection) {
442 int cursor = posToCursor(pos);
443 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
449 bool ChatItem::hasActiveClickable() const
455 std::pair<quint16, quint16> ChatItem::activeClickableRange() const
461 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive)
463 QList<QRectF> resultList;
464 const QAbstractItemModel *model_ = model();
468 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
469 QList<int> indexList;
470 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
471 while (searchIdx != -1) {
472 indexList << searchIdx;
473 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
476 foreach(int idx, indexList) {
477 QTextLine line = layout()->lineForTextPosition(idx);
478 qreal x = line.cursorToX(idx);
479 qreal width = line.cursorToX(idx + searchWord.count()) - x;
480 qreal height = line.height();
481 qreal y = height * line.lineNumber();
482 resultList << QRectF(x, y, width, height);
489 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
491 // single clicks are already handled by the scene (for clearing the selection)
492 if (clickMode == ChatScene::DragStartClick) {
493 chatScene()->setSelectingItem(this);
494 _selectionStart = _selectionEnd = posToCursor(pos);
495 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
496 chatLine()->update();
501 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
503 if (event->buttons() == Qt::LeftButton) {
504 if (boundingRect().contains(event->pos())) {
505 qint16 end = posToCursor(event->pos());
506 if (end != _selectionEnd) {
508 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
509 chatLine()->update();
514 chatScene()->startGlobalSelection(this, event->pos());
524 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
526 if (event->buttons() == Qt::LeftButton)
533 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
535 if (_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
536 chatScene()->selectionToClipboard(QClipboard::Selection);
544 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos)
548 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
552 // ************************************************************
554 // ************************************************************
556 void SenderChatItem::initLayout(QTextLayout *layout) const
558 initLayoutHelper(layout, QTextOption::ManualWrap, Qt::AlignRight);
563 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
565 Q_UNUSED(option); Q_UNUSED(widget);
567 painter->setClipRect(boundingRect());
568 paintBackground(painter);
570 qreal layoutWidth = layout()->minimumWidth();
572 if (chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
573 offset = qMin(width() - layoutWidth, (qreal)0);
575 offset = qMax(layoutWidth - width(), (qreal)0);
577 if (layoutWidth > width()) {
578 // Draw a nice gradient for longer items
579 // Qt's text drawing with a gradient brush sucks, so we use compositing instead
580 QPixmap pixmap(layout()->boundingRect().toRect().size());
581 pixmap.fill(Qt::transparent);
583 QPainter pixPainter(&pixmap);
584 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
586 // Create alpha channel mask
587 QLinearGradient gradient;
589 gradient.setStart(0, 0);
590 gradient.setFinalStop(12, 0);
591 gradient.setColorAt(0, Qt::transparent);
592 gradient.setColorAt(1, Qt::white);
595 gradient.setStart(width()-10, 0);
596 gradient.setFinalStop(width(), 0);
597 gradient.setColorAt(0, Qt::white);
598 gradient.setColorAt(1, Qt::transparent);
600 pixPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn); // gradient's alpha gets applied to the pixmap
601 pixPainter.fillRect(pixmap.rect(), gradient);
602 painter->drawPixmap(pos(), pixmap);
605 layout()->draw(painter, pos(), additionalFormats(), boundingRect());
611 void SenderChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
613 if (clickMode == ChatScene::DoubleClick) {
614 BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
615 QString nick = data(MessageModel::EditRole).toString();
616 // check if the nick is a valid ircUser
617 if (!nick.isEmpty() && Client::network(curBufInfo.networkId())->ircUser(nick))
618 Client::bufferModel()->switchToOrStartQuery(curBufInfo.networkId(), nick);
621 ChatItem::handleClick(pos, clickMode);
625 // ************************************************************
627 // ************************************************************
629 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
631 ContentsChatItem::ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent)
632 : ChatItem(QRectF(pos, QSizeF(width, 0)), parent),
636 setGeometryByWidth(width);
640 QFontMetricsF *ContentsChatItem::fontMetrics() const
642 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second.type, UiStyle::MessageLabel::None);
646 ContentsChatItem::~ContentsChatItem()
652 void ContentsChatItem::clearCache()
656 ChatItem::clearCache();
660 ContentsChatItemPrivate *ContentsChatItem::privateData() const
663 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
664 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
670 qreal ContentsChatItem::setGeometryByWidth(qreal w)
672 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
676 WrapColumnFinder finder(this);
677 while (finder.nextWrapColumn(w) > 0)
679 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
680 qreal h = lines * spacing;
684 if (w != width() || h != height())
691 void ContentsChatItem::initLayout(QTextLayout *layout) const
693 initLayoutHelper(layout, QTextOption::WrapAtWordBoundaryOrAnywhere);
698 void ContentsChatItem::doLayout(QTextLayout *layout) const
700 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
701 if (!wrapList.count()) return; // empty chatitem
704 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
705 WrapColumnFinder finder(this);
706 layout->beginLayout();
708 QTextLine line = layout->createLine();
712 int col = finder.nextWrapColumn(width());
714 col = layout->text().length();
715 int num = col - line.textStart();
717 line.setNumColumns(num);
719 // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
720 // We verify this and try setting the width again, making it shorter each time until the lengths match.
721 // Dead fugly, but seems to work…
722 for (int i = line.textLength()-1; i >= 0 && line.textLength() > num; i--) {
723 line.setNumColumns(i);
725 if (num != line.textLength()) {
726 qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
727 // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
730 line.setPosition(QPointF(0, h));
737 bool ContentsChatItem::hasActiveClickable() const
739 return privateData()->currentClickable.isValid();
743 std::pair<quint16, quint16> ContentsChatItem::activeClickableRange() const
745 const auto &clickable = privateData()->currentClickable;
746 if (clickable.isValid()) {
747 return {clickable.start(), clickable.start() + clickable.length()};
753 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const
755 return privateData()->clickables.atCursorPos(posToCursor(pos));
759 UiStyle::FormatList ContentsChatItem::formatList() const
761 UiStyle::FormatList fmtList = ChatItem::formatList();
762 for (int i = 0; i < privateData()->clickables.count(); i++) {
763 Clickable click = privateData()->clickables.at(i);
764 if (click.type() == Clickable::Url) {
765 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::FormatType::Url);
772 void ContentsChatItem::endHoverMode()
775 if (privateData()->currentClickable.isValid()) {
776 chatLine()->unsetCursor();
777 privateData()->currentClickable = Clickable();
780 chatLine()->update();
785 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
787 if (clickMode == ChatScene::SingleClick) {
788 qint16 idx = posToCursor(pos);
789 Clickable foo = privateData()->clickables.atCursorPos(idx);
791 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
792 QString text = data(ChatLineModel::DisplayRole).toString();
793 foo.activate(networkId, text);
796 else if (clickMode == ChatScene::DoubleClick) {
797 chatScene()->setSelectingItem(this);
798 setSelectionMode(PartialSelection);
799 Clickable click = clickableAt(pos);
800 if (click.isValid()) {
801 setSelectionStart(click.start());
802 setSelectionEnd(click.start() + click.length());
805 // find word boundary
806 QString str = data(ChatLineModel::DisplayRole).toString();
807 qint16 cursor = posToCursor(pos);
808 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
809 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
810 if (end < 0) end = str.length();
811 setSelectionStart(start);
812 setSelectionEnd(end);
814 chatLine()->update();
816 else if (clickMode == ChatScene::TripleClick) {
817 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
819 ChatItem::handleClick(pos, clickMode);
823 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
825 // mouse move events always mean we're not hovering anymore...
827 ChatItem::mouseMoveEvent(event);
831 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
838 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
840 bool onClickable = false;
841 Clickable click = clickableAt(event->pos());
842 if (click.isValid()) {
843 if (click.type() == Clickable::Url) {
845 showWebPreview(click);
847 else if (click.type() == Clickable::Channel) {
848 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
849 // don't make clickable if it's our own name
850 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
851 if (Client::networkModel()->bufferName(myId) != name)
855 chatLine()->setCursor(Qt::PointingHandCursor);
856 privateData()->currentClickable = click;
857 chatLine()->update();
861 if (!onClickable) endHoverMode();
866 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos)
868 if (privateData()->currentClickable.isValid()) {
869 Clickable click = privateData()->currentClickable;
870 switch (click.type()) {
872 privateData()->activeClickable = click;
873 menu->addAction(icon::get("edit-copy"), tr("Copy Link Address"),
874 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
876 case Clickable::Channel:
878 // Remove existing menu actions, they confuse us when right-clicking on a clickable
880 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
881 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
889 // Buffer-specific actions
890 ChatItem::addActionsToMenu(menu, pos);
895 void ContentsChatItem::copyLinkToClipboard()
897 Clickable click = privateData()->activeClickable;
898 if (click.isValid() && click.type() == Clickable::Url) {
899 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
900 if (!url.contains("://"))
901 url = "http://" + url;
902 chatScene()->stringToClipboard(url);
907 /******** WEB PREVIEW *****************************************************************************/
909 void ContentsChatItem::showWebPreview(const Clickable &click)
911 #if !defined HAVE_WEBKIT && !defined HAVE_WEBENGINE
914 QTextLine line = layout()->lineForTextPosition(click.start());
915 qreal x = line.cursorToX(click.start());
916 qreal width = line.cursorToX(click.start() + click.length()) - x;
917 qreal height = line.height();
918 qreal y = height * line.lineNumber();
920 QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
921 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
923 QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
924 if (!urlstr.contains("://"))
925 urlstr = "http://" + urlstr;
926 QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
927 chatScene()->loadWebPreview(this, url, urlRect);
932 void ContentsChatItem::clearWebPreview()
934 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
935 chatScene()->clearWebPreview(this);
940 /*************************************************************************************************/
942 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
944 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
952 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder()
957 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width)
959 if (wordidx >= wrapList.count())
963 qreal targetWidth = lineCount * width + choppedTrailing;
965 qint16 start = wordidx;
966 qint16 end = wrapList.count() - 1;
968 // check if the whole line fits
969 if (wrapList.at(end).endX <= targetWidth) // || start == end)
972 // check if we have a very long word that needs inter word wrap
973 if (wrapList.at(start).endX > targetWidth) {
974 if (!line.isValid()) {
975 item->initLayoutHelper(&layout, QTextOption::NoWrap);
976 layout.beginLayout();
977 line = layout.createLine();
980 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
984 if (start + 1 == end) {
986 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
988 // both cases should be cought preliminary
989 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
990 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
992 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
993 return wrapList.at(wordidx).start;
996 qint16 pivot = (end + start) / 2;
997 if (wrapList.at(pivot).endX > targetWidth) {
1009 /*************************************************************************************************/