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 ***************************************************************************/
21 #include "chatscene.h"
25 #include <QApplication>
27 #include <QDesktopServices>
29 #include <QGraphicsSceneMouseEvent>
33 #include <QPersistentModelIndex>
37 # include <QWebEngineView>
38 #elif defined HAVE_WEBKIT
44 #include "chatlinemodelitem.h"
46 #include "chatviewsettings.h"
48 #include "clientbacklogmanager.h"
49 #include "columnhandleitem.h"
50 #include "contextmenuactionprovider.h"
53 #include "markerlineitem.h"
54 #include "messagefilter.h"
56 #include "qtuistyle.h"
57 #include "webpreviewitem.h"
59 const qreal minContentsWidth = 200;
61 ChatScene::ChatScene(QAbstractItemModel *model, QString idString, qreal width, ChatView *parent)
62 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
64 _idString(std::move(idString)),
66 _singleBufferId(BufferId()),
67 _sceneRect(0, 0, width, 0),
70 _markerLine(new MarkerLineItem(width)),
71 _markerLineVisible(false),
72 _markerLineValid(false),
73 _markerLineJumpPending(false),
74 _cutoffMode(CutoffRight),
75 _alwaysBracketSender(false),
76 _selectingItem(nullptr),
81 _leftButtonPressed(false)
83 auto *filter = qobject_cast<MessageFilter *>(model);
84 if (filter && filter->isSingleBufferFilter()) {
85 _singleBufferId = filter->singleBufferId();
89 connect(this, &QGraphicsScene::sceneRectChanged, _markerLine, &MarkerLineItem::sceneRectChanged);
91 ChatViewSettings defaultSettings;
92 _defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
93 _defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
95 ChatViewSettings viewSettings(this);
96 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", _defaultFirstColHandlePos).toInt();
97 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", _defaultSecondColHandlePos).toInt();
99 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
100 addItem(_firstColHandle);
101 _firstColHandle->setXPos(_firstColHandlePos);
102 connect(_firstColHandle, &ColumnHandleItem::positionChanged, this, &ChatScene::firstHandlePositionChanged);
103 connect(this, &QGraphicsScene::sceneRectChanged, _firstColHandle, &ColumnHandleItem::sceneRectChanged);
105 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
106 addItem(_secondColHandle);
107 _secondColHandle->setXPos(_secondColHandlePos);
108 connect(_secondColHandle, &ColumnHandleItem::positionChanged, this, &ChatScene::secondHandlePositionChanged);
110 connect(this, &QGraphicsScene::sceneRectChanged, _secondColHandle, &ColumnHandleItem::sceneRectChanged);
114 if (model->rowCount() > 0)
115 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
117 connect(model, &QAbstractItemModel::rowsInserted,
118 this, &ChatScene::rowsInserted);
119 connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
120 this, &ChatScene::rowsAboutToBeRemoved);
121 connect(model, &QAbstractItemModel::rowsRemoved,
122 this, &ChatScene::rowsRemoved);
123 connect(model, &QAbstractItemModel::dataChanged, this, &ChatScene::dataChanged);
125 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
126 webPreview.timer.setSingleShot(true);
127 connect(&webPreview.timer, &QTimer::timeout, this, &ChatScene::webPreviewNextStep);
129 _showWebPreview = defaultSettings.showWebPreview();
130 defaultSettings.notify("ShowWebPreview", this, &ChatScene::showWebPreviewChanged);
132 _showSenderBrackets = defaultSettings.showSenderBrackets();
133 defaultSettings.notify("ShowSenderBrackets", this, &ChatScene::showSenderBracketsChanged);
135 _useCustomTimestampFormat = defaultSettings.useCustomTimestampFormat();
136 defaultSettings.notify("UseCustomTimestampFormat", this, &ChatScene::useCustomTimestampFormatChanged);
138 _timestampFormatString = defaultSettings.timestampFormatString();
139 defaultSettings.notify("TimestampFormat", this, &ChatScene::timestampFormatStringChanged);
140 updateTimestampHasBrackets();
142 _clickTimer.setInterval(QApplication::doubleClickInterval());
143 _clickTimer.setSingleShot(true);
144 connect(&_clickTimer, &QTimer::timeout, this, &ChatScene::clickTimeout);
146 setItemIndexMethod(QGraphicsScene::NoIndex);
150 ChatView *ChatScene::chatView() const
156 ColumnHandleItem *ChatScene::firstColumnHandle() const
158 return _firstColHandle;
162 ColumnHandleItem *ChatScene::secondColumnHandle() const
164 return _secondColHandle;
167 void ChatScene::resetColumnWidths()
169 //make sure first column is at least 80 px wide, second 120 px
170 int firstColHandlePos = qMax(_defaultFirstColHandlePos,
172 int secondColHandlePos = qMax(_defaultSecondColHandlePos,
173 firstColHandlePos + 120);
175 _firstColHandle->setXPos(firstColHandlePos);
176 _secondColHandle->setXPos(secondColHandlePos);
179 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
184 QList<ChatLine *>::ConstIterator start = _lines.begin();
185 QList<ChatLine *>::ConstIterator end = _lines.end();
186 QList<ChatLine *>::ConstIterator middle;
188 auto n = int(end - start);
193 middle = start + half;
194 if ((*middle)->msgId() < msgId) {
203 if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
209 if (start == _lines.begin()) // not (yet?) in our scene
212 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
214 if (start == end) { // higher than last element
215 if (!ignoreDayChange)
216 return _lines.last();
218 for (int i = _lines.count() -1; i >= 0; i--) {
219 if (_lines.at(i)->msgType() != Message::DayChange)
225 // return the next-lower line
226 if (!ignoreDayChange)
230 if ((*(--start))->msgType() != Message::DayChange)
233 while (start != _lines.begin());
238 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
240 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
241 auto *line = qgraphicsitem_cast<ChatLine *>(item);
243 return line->itemAt(line->mapFromScene(scenePos));
249 bool ChatScene::containsBuffer(const BufferId &id) const
251 auto *filter = qobject_cast<MessageFilter *>(model());
253 return filter->containsBuffer(id);
259 void ChatScene::setMarkerLineVisible(bool visible)
261 _markerLineVisible = visible;
262 if (visible && _markerLineValid)
263 markerLine()->setVisible(true);
265 markerLine()->setVisible(false);
269 void ChatScene::setMarkerLine(MsgId msgId)
271 if (!isSingleBufferScene())
274 if (!msgId.isValid())
275 msgId = Client::markerLine(singleBufferId());
277 if (msgId.isValid()) {
278 ChatLine *line = chatLine(msgId, false, true);
280 markerLine()->setChatLine(line);
281 // if this was the last line, we won't see it because it's outside the sceneRect
282 // .. which is exactly what we want :)
283 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
285 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
286 if (markerLine()->pos().y() >= sceneRect().y()) {
287 _markerLineValid = true;
288 if (_markerLineVisible)
289 markerLine()->setVisible(true);
290 if (_markerLineJumpPending) {
291 _markerLineJumpPending = false;
292 if (markerLine()->isVisible()) {
293 markerLine()->ensureVisible(QRectF(), 50, 50);
300 _markerLineValid = false;
301 markerLine()->setVisible(false);
305 void ChatScene::jumpToMarkerLine(bool requestBacklog)
307 if (!isSingleBufferScene())
310 if (markerLine()->isVisible()) {
311 markerLine()->ensureVisible(QRectF(), 50, 50);
314 if (!_markerLineValid && requestBacklog) {
315 MsgId msgId = Client::markerLine(singleBufferId());
316 if (msgId.isValid()) {
317 _markerLineJumpPending = true;
318 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
320 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
321 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
322 // jump tries will eventually cause enough backlog to be fetched.
323 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
324 this->requestBacklog();
330 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
334 // QModelIndex sidx = model()->index(start, 2);
335 // QModelIndex eidx = model()->index(end, 2);
336 // qDebug() << "rowsInserted:";
338 // QModelIndex ssidx = model()->index(start - 1, 2);
339 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
340 // << ssidx.data(Qt::DisplayRole).toString();
342 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
343 // << sidx.data(Qt::DisplayRole).toString();
344 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
345 // << eidx.data(Qt::DisplayRole).toString();
346 // if(end + 1 < model()->rowCount()) {
347 // QModelIndex eeidx = model()->index(end + 1, 2);
348 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
349 // << eeidx.data(Qt::DisplayRole).toString();
354 qreal width = _sceneRect.width();
355 bool atBottom = (start == _lines.count());
356 bool atTop = !atBottom && (start == 0);
358 if (start < _lines.count()) {
359 y = _lines.value(start)->y();
361 else if (atBottom && !_lines.isEmpty()) {
362 y = _lines.last()->y() + _lines.last()->height();
365 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
366 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
367 qreal timestampWidth = firstColumnHandle()->sceneLeft();
368 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
369 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
372 for (int i = end; i >= start; i--) {
373 auto *line = new ChatLine(i, model(),
375 timestampWidth, senderWidth, contentsWidth,
376 senderPos, contentsPos);
378 line->setPos(0, y-h);
379 _lines.insert(start, line);
384 for (int i = start; i <= end; i++) {
385 auto *line = new ChatLine(i, model(),
387 timestampWidth, senderWidth, contentsWidth,
388 senderPos, contentsPos);
389 line->setPos(0, y+h);
391 _lines.insert(i, line);
396 // update existing items
397 for (int i = end+1; i < _lines.count(); i++) {
398 _lines[i]->setRow(i);
402 if (_selectionStart >= 0) {
403 int offset = end - start + 1;
404 int oldStart = _selectionStart;
405 if (_selectionStart >= start)
406 _selectionStart += offset;
407 if (_selectionEnd >= start) {
408 _selectionEnd += offset;
409 if (_selectionStart == oldStart)
410 for (int i = start; i < start + offset; i++)
411 _lines[i]->setSelected(true);
413 if (_firstSelectionRow >= start)
414 _firstSelectionRow += offset;
417 // neither pre- or append means we have to do dirty work: move items...
418 if (!(atTop || atBottom)) {
419 ChatLine *line = nullptr;
420 for (int i = 0; i <= end; i++) {
422 line->setPos(0, line->pos().y() - h);
423 if (line == markerLine()->chatLine())
424 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
428 // check if all went right
429 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
431 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
432 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
433 // qDebug() << "line[start - 1]:" << _lines.at(start - 1)->pos().y() << "+" << _lines.at(start - 1)->height() << "=" << _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height();
434 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
435 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
439 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
440 // if(end + 1 < _lines.count()) {
441 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
442 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
443 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
444 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
445 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
451 if (start < _firstLineRow) {
452 int prevFirstLineRow = _firstLineRow + (end - start + 1);
453 for (int i = end + 1; i < prevFirstLineRow; i++) {
454 _lines.at(i)->show();
457 // force new search for first proper line
462 emit lastLineChanged(_lines.last(), h);
465 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
466 if (!_markerLineValid)
471 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
475 qreal h = 0; // total height of removed items;
477 bool atTop = (start == 0);
478 bool atBottom = (end == _lines.count() - 1);
481 if (_selectingItem) {
482 int row = _selectingItem->row();
483 if (row >= start && row <= end)
484 setSelectingItem(nullptr);
487 // remove items from scene
488 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
489 int lineCount = start;
490 while (lineIter != _lines.end() && lineCount <= end) {
491 if ((*lineIter) == markerLine()->chatLine())
492 markerLine()->setChatLine(nullptr);
493 h += (*lineIter)->height();
495 lineIter = _lines.erase(lineIter);
499 // update rows of remaining chatlines
500 for (int i = start; i < _lines.count(); i++) {
501 _lines.at(i)->setRow(i);
505 if (_selectionStart >= 0) {
506 int offset = end - start + 1;
507 if (_selectionStart >= start)
508 _selectionStart = qMax(_selectionStart - offset, start);
509 if (_selectionEnd >= start)
510 _selectionEnd -= offset;
511 if (_firstSelectionRow >= start)
512 _firstSelectionRow -= offset;
514 if (_selectionEnd < _selectionStart) {
515 _isSelecting = false;
516 _selectionStart = -1;
520 // neither removing at bottom or top means we have to move items...
521 if (!(atTop || atBottom)) {
524 int moveEnd = _lines.count() - 1;
525 if (start < _lines.count() - start) {
534 ChatLine *line = nullptr;
535 for (int i = moveStart; i <= moveEnd; i++) {
537 line->setPos(0, line->pos().y() + offset);
541 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
544 // when searching for the first non-date-line we have to take into account that our
545 // model still contains the just removed lines so we cannot simply call updateSceneRect()
546 int numRows = model()->rowCount();
547 QModelIndex firstLineIdx;
549 bool needOffset = false;
552 if (_firstLineRow >= start && _firstLineRow <= end) {
553 _firstLineRow = end + 1;
556 firstLineIdx = model()->index(_firstLineRow, 0);
558 while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
561 _firstLineRow -= end - start + 1;
566 void ChatScene::rowsRemoved()
568 // move the marker line if necessary
573 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
575 layout(tl.row(), br.row(), _sceneRect.width());
579 void ChatScene::updateForViewport(qreal width, qreal height)
581 _viewportHeight = height;
586 void ChatScene::setWidth(qreal width)
588 if (width == _sceneRect.width())
590 layout(0, _lines.count()-1, width);
594 void ChatScene::layout(int start, int end, qreal width)
596 // clock_t startT = clock();
598 // disabling the index while doing this complex updates is about
599 // 2 to 10 times faster!
600 //setItemIndexMethod(QGraphicsScene::NoIndex);
604 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
605 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
606 while (row >= start) {
607 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
611 // remaining items don't need geometry changes, but maybe repositioning?
612 ChatLine *line = _lines.at(row);
613 qreal offset = linePos - (line->scenePos().y() + line->height());
616 line = _lines.at(row--);
617 line->setPos(0, line->scenePos().y() + offset);
623 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
625 updateSceneRect(width);
628 emit layoutChanged();
630 // clock_t endT = clock();
631 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
635 void ChatScene::firstHandlePositionChanged(qreal xpos)
637 if (_firstColHandlePos == xpos)
640 _firstColHandlePos = xpos >= 0 ? xpos : 0;
641 ChatViewSettings viewSettings(this);
642 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
643 ChatViewSettings defaultSettings;
644 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
646 // clock_t startT = clock();
648 // disabling the index while doing this complex updates is about
649 // 2 to 10 times faster!
650 //setItemIndexMethod(QGraphicsScene::NoIndex);
652 QList<ChatLine *>::iterator lineIter = _lines.end();
653 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
654 qreal timestampWidth = firstColumnHandle()->sceneLeft();
655 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
656 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
658 while (lineIter != lineIterBegin) {
660 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
662 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
666 // clock_t endT = clock();
667 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
671 void ChatScene::secondHandlePositionChanged(qreal xpos)
673 if (_secondColHandlePos == xpos)
676 _secondColHandlePos = xpos;
677 ChatViewSettings viewSettings(this);
678 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
679 ChatViewSettings defaultSettings;
680 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
682 // clock_t startT = clock();
684 // disabling the index while doing this complex updates is about
685 // 2 to 10 times faster!
686 //setItemIndexMethod(QGraphicsScene::NoIndex);
688 QList<ChatLine *>::iterator lineIter = _lines.end();
689 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
690 qreal linePos = _sceneRect.y() + _sceneRect.height();
691 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
692 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
693 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
694 while (lineIter != lineIterBegin) {
696 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
698 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
702 emit layoutChanged();
704 // clock_t endT = clock();
705 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
709 void ChatScene::setHandleXLimits()
711 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
712 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
717 void ChatScene::setSelectingItem(ChatItem *item)
719 if (_selectingItem) _selectingItem->clearSelection();
720 _selectingItem = item;
724 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
726 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
727 _selectionStartCol = _selectionMinCol = item->column();
729 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
730 updateSelection(item->mapToScene(itemPos));
734 void ChatScene::updateSelection(const QPointF &pos)
736 int curRow = rowByScenePos(pos);
737 if (curRow < 0) return;
738 auto curColumn = (int)columnByScenePos(pos);
739 auto minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
740 if (minColumn != _selectionMinCol) {
741 _selectionMinCol = minColumn;
742 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
743 _lines[l]->setSelected(true, minColumn);
746 int newstart = qMin(curRow, _firstSelectionRow);
747 int newend = qMax(curRow, _firstSelectionRow);
748 if (newstart < _selectionStart) {
749 for (int l = newstart; l < _selectionStart; l++)
750 _lines[l]->setSelected(true, minColumn);
752 if (newstart > _selectionStart) {
753 for (int l = _selectionStart; l < newstart; l++)
754 _lines[l]->setSelected(false);
756 if (newend > _selectionEnd) {
757 for (int l = _selectionEnd+1; l <= newend; l++)
758 _lines[l]->setSelected(true, minColumn);
760 if (newend < _selectionEnd) {
761 for (int l = newend+1; l <= _selectionEnd; l++)
762 _lines[l]->setSelected(false);
765 _selectionStart = newstart;
766 _selectionEnd = newend;
768 if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
769 if (!_selectingItem) {
770 // _selectingItem has been removed already
773 _lines[curRow]->setSelected(false);
774 _isSelecting = false;
775 _selectionStart = -1;
776 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
781 bool ChatScene::isPosOverSelection(const QPointF &pos) const
783 ChatItem *chatItem = chatItemAt(pos);
786 if (hasGlobalSelection()) {
787 int row = chatItem->row();
788 if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
789 return columnByScenePos(pos) >= _selectionMinCol;
792 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
798 bool ChatScene::isScrollingAllowed() const
803 // TODO: Handle clicks and single-item selections too
809 /******** MOUSE HANDLING **************************************************************************/
811 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
813 QPointF pos = event->scenePos();
816 // zoom actions and similar
817 chatView()->addActionsToMenu(&menu, pos);
820 // item-specific options (select link etc)
821 ChatItem *item = chatItemAt(pos);
823 item->addActionsToMenu(&menu, item->mapFromScene(pos));
825 // no item -> default scene actions
826 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
828 // If we have text selected, insert the Copy Selection as first item
829 if (isPosOverSelection(pos)) {
830 QAction *sep = menu.insertSeparator(menu.actions().first());
831 QAction *act = new Action(icon::get("edit-copy"), tr("Copy Selection"), &menu, this, [this]() { selectionToClipboard(); }, QKeySequence::Copy);
832 menu.insertAction(sep, act);
834 QString searchSelectionText = selection();
835 if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
836 searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
837 searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
839 QAction *webSearchAction = new Action(icon::get("edit-find"), searchSelectionText, &menu, this, &ChatScene::webSearchOnSelection);
840 menu.insertAction(sep, webSearchAction);
843 if (QtUi::mainWindow()->menuBar()->isHidden())
844 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
846 // show column reset action if columns have been resized in this session or there is at least one very narrow column
847 if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
848 (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
849 menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, &ChatScene::resetColumnWidths));
851 menu.exec(event->screenPos());
855 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
857 if (event->buttons() == Qt::LeftButton) {
858 if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
859 if (_clickTimer.isActive())
861 if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
862 initiateDrag(event->widget());
864 _clickMode = DragStartClick;
865 handleClick(Qt::LeftButton, _clickPos);
867 _clickMode = NoClick;
870 updateSelection(event->scenePos());
871 emit mouseMoveWhileSelecting(event->scenePos());
874 else if (_clickHandled && _clickMode < DoubleClick)
875 QGraphicsScene::mouseMoveEvent(event);
878 QGraphicsScene::mouseMoveEvent(event);
882 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
884 if (event->buttons() == Qt::LeftButton) {
885 _leftButtonPressed = true;
886 _clickHandled = false;
887 if (!isPosOverSelection(event->scenePos())) {
888 // immediately clear selection if clicked outside; otherwise, wait for potential drag
891 if (_clickMode != NoClick && _clickTimer.isActive()) {
892 switch (_clickMode) {
894 _clickMode = SingleClick; break;
896 _clickMode = DoubleClick; break;
898 _clickMode = TripleClick; break;
900 _clickMode = DoubleClick; break;
904 handleClick(Qt::LeftButton, _clickPos);
907 _clickMode = SingleClick;
908 _clickPos = event->scenePos();
912 if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
913 QGraphicsScene::mouseDoubleClickEvent(event);
915 QGraphicsScene::mousePressEvent(event);
919 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
921 // we check for doubleclick ourselves, so just call press handler
922 mousePressEvent(event);
926 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
928 if (event->button() == Qt::LeftButton && _leftButtonPressed) {
929 _leftButtonPressed = false;
930 if (_clickMode != NoClick) {
931 if (_clickMode == SingleClick)
934 if (!_clickTimer.isActive())
935 handleClick(Qt::LeftButton, _clickPos);
938 // no click -> drag or selection move
939 if (isGloballySelecting()) {
940 selectionToClipboard(QClipboard::Selection);
941 _isSelecting = false;
947 QGraphicsScene::mouseReleaseEvent(event);
951 void ChatScene::clickTimeout()
953 if (!_leftButtonPressed && _clickMode == SingleClick)
954 handleClick(Qt::LeftButton, _clickPos);
958 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
960 if (button == Qt::LeftButton) {
963 // Now send click down to items
964 ChatItem *chatItem = chatItemAt(scenePos);
966 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
968 _clickHandled = true;
973 void ChatScene::initiateDrag(QWidget *source)
975 auto *drag = new QDrag(source);
976 auto *mimeData = new QMimeData;
977 mimeData->setText(selection());
978 drag->setMimeData(mimeData);
980 drag->exec(Qt::CopyAction);
984 /******** SELECTIONS ******************************************************************************/
986 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
991 stringToClipboard(selection(), mode);
995 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
998 // remove trailing linefeeds
999 if (str.endsWith('\n'))
1003 case QClipboard::Clipboard:
1004 QApplication::clipboard()->setText(str);
1006 case QClipboard::Selection:
1007 if (QApplication::clipboard()->supportsSelection())
1008 QApplication::clipboard()->setText(str, QClipboard::Selection);
1016 //!\brief Convert current selection to human-readable string.
1017 QString ChatScene::selection() const
1019 //TODO Make selection format configurable!
1020 if (hasGlobalSelection()) {
1021 int start = qMin(_selectionStart, _selectionEnd);
1022 int end = qMax(_selectionStart, _selectionEnd);
1023 if (start < 0 || end >= _lines.count()) {
1024 qDebug() << "Invalid selection range:" << start << end;
1029 for (int l = start; l <= end; l++) {
1030 if (_selectionMinCol == ChatLineModel::TimestampColumn) {
1031 ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
1032 if (!_showSenderBrackets && !_timestampHasBrackets) {
1033 // Only re-add brackets if the current timestamp format does not include them
1034 // -and- sender brackets are disabled. Don't filter on Message::Plain as
1035 // timestamp brackets affect all types of messages.
1036 // Remove any spaces before and after, otherwise it may look weird.
1037 result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
1038 .toString().trimmed());
1040 result += item->data(MessageModel::DisplayRole).toString() + " ";
1043 if (_selectionMinCol <= ChatLineModel::SenderColumn) {
1044 ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
1045 if (!_showSenderBrackets && (_alwaysBracketSender
1046 || item->chatLine()->msgType() == Message::Plain)) {
1047 // Copying to plain-text. Re-add the sender brackets if they're normally hidden
1050 // * All messages in the Chat Monitor
1052 // The Chat Monitor sets alwaysBracketSender() to true.
1053 result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
1056 result += item->data(MessageModel::DisplayRole).toString() + " ";
1059 result += _lines[l]->item(ChatLineModel::ContentsColumn)
1060 ->data(MessageModel::DisplayRole).toString() + "\n";
1064 else if (selectingItem())
1065 return selectingItem()->selection();
1070 bool ChatScene::hasSelection() const
1072 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1076 bool ChatScene::hasGlobalSelection() const
1078 return _selectionStart >= 0;
1082 bool ChatScene::isGloballySelecting() const
1084 return _isSelecting;
1088 void ChatScene::clearGlobalSelection()
1090 if (hasGlobalSelection()) {
1091 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
1092 _lines[l]->setSelected(false);
1093 _isSelecting = false;
1094 _selectionStart = -1;
1099 void ChatScene::clearSelection()
1101 clearGlobalSelection();
1102 if (selectingItem())
1103 selectingItem()->clearSelection();
1107 /******** *************************************************************************************/
1109 void ChatScene::webSearchOnSelection()
1111 if (!hasSelection())
1114 ChatViewSettings settings;
1115 QString webSearchBaseUrl = settings.webSearchUrlFormatString();
1116 QString webSearchUrl = webSearchBaseUrl.replace(QString("%s"), selection());
1117 QUrl url = QUrl::fromUserInput(webSearchUrl);
1118 QDesktopServices::openUrl(url);
1122 /******** *************************************************************************************/
1124 void ChatScene::requestBacklog()
1126 auto *filter = qobject_cast<MessageFilter *>(model());
1128 return filter->requestBacklog();
1133 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1135 if (x < _firstColHandle->x())
1136 return ChatLineModel::TimestampColumn;
1137 if (x < _secondColHandle->x())
1138 return ChatLineModel::SenderColumn;
1140 return ChatLineModel::ContentsColumn;
1144 int ChatScene::rowByScenePos(qreal y) const
1146 QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1148 // ChatLine should be at the bottom of the list
1149 for (int i = itemList.count()-1; i >= 0; i--) {
1150 auto *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
1158 void ChatScene::updateSceneRect(qreal width)
1160 if (_lines.isEmpty()) {
1161 updateSceneRect(QRectF(0, 0, width, 0));
1165 // we hide day change messages at the top by making the scene rect smaller
1166 // and by calling QGraphicsItem::hide() on all leading day change messages
1167 // the first one is needed to ensure proper scrollbar ranges
1168 // the second for cases where the viewport is larger then the set scenerect
1169 // (in this case the items are shown anyways)
1170 if (_firstLineRow == -1) {
1171 int numRows = model()->rowCount();
1173 QModelIndex firstLineIdx;
1174 while (_firstLineRow < numRows) {
1175 firstLineIdx = model()->index(_firstLineRow, 0);
1176 if ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
1178 _lines.at(_firstLineRow)->hide();
1183 // the following call should be safe. If it crashes something went wrong during insert/remove
1184 if (_firstLineRow < _lines.count()) {
1185 ChatLine *firstLine = _lines.at(_firstLineRow);
1186 ChatLine *lastLine = _lines.last();
1187 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1191 updateSceneRect(QRectF(0, 0, width, 0));
1196 void ChatScene::updateSceneRect(const QRectF &rect)
1204 // ========================================
1205 // Webkit/WebEngine Only stuff
1206 // ========================================
1207 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
1208 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
1210 if (!_showWebPreview)
1213 if (webPreview.urlRect != urlRect)
1214 webPreview.urlRect = urlRect;
1216 if (webPreview.parentItem != parentItem)
1217 webPreview.parentItem = parentItem;
1219 if (webPreview.url != url) {
1220 webPreview.url = url;
1221 // prepare to load a different URL
1222 if (webPreview.previewItem) {
1223 if (webPreview.previewItem->scene())
1224 removeItem(webPreview.previewItem);
1225 delete webPreview.previewItem;
1226 webPreview.previewItem = nullptr;
1228 webPreview.previewState = WebPreview::NoPreview;
1231 if (webPreview.url.isEmpty())
1234 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1235 switch (webPreview.previewState) {
1236 case WebPreview::NoPreview:
1237 webPreview.previewState = WebPreview::NewPreview;
1238 webPreview.timer.start(500);
1240 case WebPreview::NewPreview:
1241 case WebPreview::DelayPreview:
1242 case WebPreview::ShowPreview:
1243 // we're already waiting for the next step or showing the preview
1245 case WebPreview::HidePreview:
1246 // we still have a valid preview
1247 webPreview.previewState = WebPreview::DelayPreview;
1248 webPreview.timer.start(1000);
1251 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1255 void ChatScene::webPreviewNextStep()
1257 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1258 switch (webPreview.previewState) {
1259 case WebPreview::NoPreview:
1261 case WebPreview::NewPreview:
1262 Q_ASSERT(!webPreview.previewItem);
1263 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1264 webPreview.previewState = WebPreview::DelayPreview;
1265 webPreview.timer.start(1000);
1267 case WebPreview::DelayPreview:
1268 Q_ASSERT(webPreview.previewItem);
1269 // calc position and show
1271 qreal previewY = webPreview.urlRect.bottom();
1272 qreal previewX = webPreview.urlRect.x();
1273 if (previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1274 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1276 if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1277 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1279 webPreview.previewItem->setPos(previewX, previewY);
1281 addItem(webPreview.previewItem);
1282 webPreview.previewState = WebPreview::ShowPreview;
1284 case WebPreview::ShowPreview:
1285 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1286 qWarning() << "removing preview";
1287 if (webPreview.previewItem && webPreview.previewItem->scene()) {
1288 removeItem(webPreview.previewItem);
1291 // Intentional fallthrough
1293 case WebPreview::HidePreview:
1294 if (webPreview.previewItem) {
1295 delete webPreview.previewItem;
1296 webPreview.previewItem = nullptr;
1298 webPreview.parentItem = nullptr;
1299 webPreview.url = QUrl();
1300 webPreview.urlRect = QRectF();
1301 webPreview.previewState = WebPreview::NoPreview;
1303 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1307 void ChatScene::clearWebPreview(ChatItem *parentItem)
1309 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1310 switch (webPreview.previewState) {
1311 case WebPreview::NewPreview:
1312 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1314 case WebPreview::ShowPreview:
1315 if (parentItem == nullptr || webPreview.parentItem == parentItem) {
1316 if (webPreview.previewItem && webPreview.previewItem->scene())
1317 removeItem(webPreview.previewItem);
1320 // Intentional fallthrough
1322 case WebPreview::DelayPreview:
1323 // we're just loading, so haven't shown the preview yet.
1324 webPreview.previewState = WebPreview::HidePreview;
1325 webPreview.timer.start(5000);
1327 case WebPreview::NoPreview:
1328 case WebPreview::HidePreview:
1331 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1337 // ========================================
1338 // end of webkit only
1339 // ========================================
1341 // Local configuration caching
1342 void ChatScene::showWebPreviewChanged()
1344 ChatViewSettings settings;
1345 _showWebPreview = settings.showWebPreview();
1348 void ChatScene::showSenderBracketsChanged()
1350 ChatViewSettings settings;
1351 _showSenderBrackets = settings.showSenderBrackets();
1354 void ChatScene::useCustomTimestampFormatChanged()
1356 ChatViewSettings settings;
1357 _useCustomTimestampFormat = settings.useCustomTimestampFormat();
1358 updateTimestampHasBrackets();
1361 void ChatScene::timestampFormatStringChanged()
1363 ChatViewSettings settings;
1364 _timestampFormatString = settings.timestampFormatString();
1365 updateTimestampHasBrackets();
1368 void ChatScene::updateTimestampHasBrackets()
1370 // Calculate these parameters only as needed, rather than on-demand
1372 if (!_useCustomTimestampFormat) {
1373 // The default timestamp format string does not have brackets, no need to check.
1374 // If UiStyle::updateSystemTimestampFormat() has brackets added, change this, too.
1375 _timestampHasBrackets = false;
1377 // Does the timestamp format contain brackets? For example:
1378 // Classic: "[hh:mm:ss]"
1379 // Modern: " hh:mm:ss"
1381 // Match groups of any opening or closing brackets - (), {}, [], <>, (>, {], etc:
1382 // ^\s*[({[<].+[)}\]>]\s*$
1383 // [...] is a character group containing ...
1384 // ^ matches start of string
1385 // \s* matches any amount of whitespace
1386 // [({[<] matches (, {, [, or <
1387 // .+ matches one or more characters
1388 // [)}\]>] matches ), }, ], or >, escaping the ]
1389 // $ matches end of string
1390 // Alternatively, if opening and closing brackets must be in pairs, use this:
1391 // (^\s*\(.+\)\s*$)|(^\s*\{.+\}\s*$)|(^\s*\[.+\]\s*$)|(^\s*<.+>\s*$)
1392 // Note that '\' must be escaped as '\\'
1393 // Helpful interactive website for debugging and explaining: https://regex101.com/
1394 const QRegExp regExpMatchBrackets(R"(^\s*[({[<].+[)}\]>]\s*$)");
1395 _timestampHasBrackets = regExpMatchBrackets.exactMatch(_timestampFormatString);