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"
23 #include <QApplication>
25 #include <QDesktopServices>
27 #include <QGraphicsSceneMouseEvent>
31 #include <QPersistentModelIndex>
41 # include <QWebEngineView>
42 #elif defined HAVE_WEBKIT
48 #include "chatlinemodelitem.h"
50 #include "chatviewsettings.h"
52 #include "clientbacklogmanager.h"
53 #include "columnhandleitem.h"
54 #include "contextmenuactionprovider.h"
57 #include "markerlineitem.h"
58 #include "messagefilter.h"
60 #include "qtuistyle.h"
61 #include "webpreviewitem.h"
63 const qreal minContentsWidth = 200;
65 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
66 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
70 _singleBufferId(BufferId()),
71 _sceneRect(0, 0, width, 0),
74 _markerLine(new MarkerLineItem(width)),
75 _markerLineVisible(false),
76 _markerLineValid(false),
77 _markerLineJumpPending(false),
78 _cutoffMode(CutoffRight),
79 _alwaysBracketSender(false),
85 _leftButtonPressed(false)
87 MessageFilter *filter = qobject_cast<MessageFilter *>(model);
88 if (filter && filter->isSingleBufferFilter()) {
89 _singleBufferId = filter->singleBufferId();
93 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
95 ChatViewSettings defaultSettings;
96 _defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
97 _defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
99 ChatViewSettings viewSettings(this);
100 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", _defaultFirstColHandlePos).toInt();
101 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", _defaultSecondColHandlePos).toInt();
103 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
104 addItem(_firstColHandle);
105 _firstColHandle->setXPos(_firstColHandlePos);
106 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
107 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
109 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
110 addItem(_secondColHandle);
111 _secondColHandle->setXPos(_secondColHandlePos);
112 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
114 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
118 if (model->rowCount() > 0)
119 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
121 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
122 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
123 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
124 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
125 connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
126 this, SLOT(rowsRemoved()));
127 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
129 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
130 webPreview.timer.setSingleShot(true);
131 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
133 _showWebPreview = defaultSettings.showWebPreview();
134 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
136 _showSenderBrackets = defaultSettings.showSenderBrackets();
137 defaultSettings.notify("ShowSenderBrackets", this, SLOT(showSenderBracketsChanged()));
139 _useCustomTimestampFormat = defaultSettings.useCustomTimestampFormat();
140 defaultSettings.notify("UseCustomTimestampFormat", this, SLOT(useCustomTimestampFormatChanged()));
142 _timestampFormatString = defaultSettings.timestampFormatString();
143 defaultSettings.notify("TimestampFormat", this, SLOT(timestampFormatStringChanged()));
144 updateTimestampHasBrackets();
146 _clickTimer.setInterval(QApplication::doubleClickInterval());
147 _clickTimer.setSingleShot(true);
148 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
150 setItemIndexMethod(QGraphicsScene::NoIndex);
154 ChatScene::~ChatScene()
159 ChatView *ChatScene::chatView() const
165 ColumnHandleItem *ChatScene::firstColumnHandle() const
167 return _firstColHandle;
171 ColumnHandleItem *ChatScene::secondColumnHandle() const
173 return _secondColHandle;
176 void ChatScene::resetColumnWidths()
178 //make sure first column is at least 80 px wide, second 120 px
179 int firstColHandlePos = qMax(_defaultFirstColHandlePos,
181 int secondColHandlePos = qMax(_defaultSecondColHandlePos,
182 firstColHandlePos + 120);
184 _firstColHandle->setXPos(firstColHandlePos);
185 _secondColHandle->setXPos(secondColHandlePos);
188 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
193 QList<ChatLine *>::ConstIterator start = _lines.begin();
194 QList<ChatLine *>::ConstIterator end = _lines.end();
195 QList<ChatLine *>::ConstIterator middle;
197 int n = int(end - start);
202 middle = start + half;
203 if ((*middle)->msgId() < msgId) {
212 if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
218 if (start == _lines.begin()) // not (yet?) in our scene
221 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
223 if (start == end) { // higher than last element
224 if (!ignoreDayChange)
225 return _lines.last();
227 for (int i = _lines.count() -1; i >= 0; i--) {
228 if (_lines.at(i)->msgType() != Message::DayChange)
234 // return the next-lower line
235 if (!ignoreDayChange)
239 if ((*(--start))->msgType() != Message::DayChange)
242 while (start != _lines.begin());
247 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
249 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
250 ChatLine *line = qgraphicsitem_cast<ChatLine *>(item);
252 return line->itemAt(line->mapFromScene(scenePos));
258 bool ChatScene::containsBuffer(const BufferId &id) const
260 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
262 return filter->containsBuffer(id);
268 void ChatScene::setMarkerLineVisible(bool visible)
270 _markerLineVisible = visible;
271 if (visible && _markerLineValid)
272 markerLine()->setVisible(true);
274 markerLine()->setVisible(false);
278 void ChatScene::setMarkerLine(MsgId msgId)
280 if (!isSingleBufferScene())
283 if (!msgId.isValid())
284 msgId = Client::markerLine(singleBufferId());
286 if (msgId.isValid()) {
287 ChatLine *line = chatLine(msgId, false, true);
289 markerLine()->setChatLine(line);
290 // if this was the last line, we won't see it because it's outside the sceneRect
291 // .. which is exactly what we want :)
292 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
294 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
295 if (markerLine()->pos().y() >= sceneRect().y()) {
296 _markerLineValid = true;
297 if (_markerLineVisible)
298 markerLine()->setVisible(true);
299 if (_markerLineJumpPending) {
300 _markerLineJumpPending = false;
301 if (markerLine()->isVisible()) {
302 markerLine()->ensureVisible(QRectF(), 50, 50);
309 _markerLineValid = false;
310 markerLine()->setVisible(false);
314 void ChatScene::jumpToMarkerLine(bool requestBacklog)
316 if (!isSingleBufferScene())
319 if (markerLine()->isVisible()) {
320 markerLine()->ensureVisible(QRectF(), 50, 50);
323 if (!_markerLineValid && requestBacklog) {
324 MsgId msgId = Client::markerLine(singleBufferId());
325 if (msgId.isValid()) {
326 _markerLineJumpPending = true;
327 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
329 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
330 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
331 // jump tries will eventually cause enough backlog to be fetched.
332 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
333 this->requestBacklog();
339 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
343 // QModelIndex sidx = model()->index(start, 2);
344 // QModelIndex eidx = model()->index(end, 2);
345 // qDebug() << "rowsInserted:";
347 // QModelIndex ssidx = model()->index(start - 1, 2);
348 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
349 // << ssidx.data(Qt::DisplayRole).toString();
351 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
352 // << sidx.data(Qt::DisplayRole).toString();
353 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
354 // << eidx.data(Qt::DisplayRole).toString();
355 // if(end + 1 < model()->rowCount()) {
356 // QModelIndex eeidx = model()->index(end + 1, 2);
357 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
358 // << eeidx.data(Qt::DisplayRole).toString();
363 qreal width = _sceneRect.width();
364 bool atBottom = (start == _lines.count());
365 bool atTop = !atBottom && (start == 0);
367 if (start < _lines.count()) {
368 y = _lines.value(start)->y();
370 else if (atBottom && !_lines.isEmpty()) {
371 y = _lines.last()->y() + _lines.last()->height();
374 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
375 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
376 qreal timestampWidth = firstColumnHandle()->sceneLeft();
377 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
378 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
381 for (int i = end; i >= start; i--) {
382 ChatLine *line = new ChatLine(i, model(),
384 timestampWidth, senderWidth, contentsWidth,
385 senderPos, contentsPos);
387 line->setPos(0, y-h);
388 _lines.insert(start, line);
393 for (int i = start; i <= end; i++) {
394 ChatLine *line = new ChatLine(i, model(),
396 timestampWidth, senderWidth, contentsWidth,
397 senderPos, contentsPos);
398 line->setPos(0, y+h);
400 _lines.insert(i, line);
405 // update existing items
406 for (int i = end+1; i < _lines.count(); i++) {
407 _lines[i]->setRow(i);
411 if (_selectionStart >= 0) {
412 int offset = end - start + 1;
413 int oldStart = _selectionStart;
414 if (_selectionStart >= start)
415 _selectionStart += offset;
416 if (_selectionEnd >= start) {
417 _selectionEnd += offset;
418 if (_selectionStart == oldStart)
419 for (int i = start; i < start + offset; i++)
420 _lines[i]->setSelected(true);
422 if (_firstSelectionRow >= start)
423 _firstSelectionRow += offset;
426 // neither pre- or append means we have to do dirty work: move items...
427 if (!(atTop || atBottom)) {
429 for (int i = 0; i <= end; i++) {
431 line->setPos(0, line->pos().y() - h);
432 if (line == markerLine()->chatLine())
433 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
437 // check if all went right
438 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
440 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
441 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
442 // 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();
443 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
444 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
448 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
449 // if(end + 1 < _lines.count()) {
450 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
451 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
452 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
453 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
454 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
460 if (start < _firstLineRow) {
461 int prevFirstLineRow = _firstLineRow + (end - start + 1);
462 for (int i = end + 1; i < prevFirstLineRow; i++) {
463 _lines.at(i)->show();
466 // force new search for first proper line
471 emit lastLineChanged(_lines.last(), h);
474 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
475 if (!_markerLineValid)
480 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
484 qreal h = 0; // total height of removed items;
486 bool atTop = (start == 0);
487 bool atBottom = (end == _lines.count() - 1);
490 if (_selectingItem) {
491 int row = _selectingItem->row();
492 if (row >= start && row <= end)
496 // remove items from scene
497 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
498 int lineCount = start;
499 while (lineIter != _lines.end() && lineCount <= end) {
500 if ((*lineIter) == markerLine()->chatLine())
501 markerLine()->setChatLine(0);
502 h += (*lineIter)->height();
504 lineIter = _lines.erase(lineIter);
508 // update rows of remaining chatlines
509 for (int i = start; i < _lines.count(); i++) {
510 _lines.at(i)->setRow(i);
514 if (_selectionStart >= 0) {
515 int offset = end - start + 1;
516 if (_selectionStart >= start)
517 _selectionStart = qMax(_selectionStart - offset, start);
518 if (_selectionEnd >= start)
519 _selectionEnd -= offset;
520 if (_firstSelectionRow >= start)
521 _firstSelectionRow -= offset;
523 if (_selectionEnd < _selectionStart) {
524 _isSelecting = false;
525 _selectionStart = -1;
529 // neither removing at bottom or top means we have to move items...
530 if (!(atTop || atBottom)) {
533 int moveEnd = _lines.count() - 1;
534 if (start < _lines.count() - start) {
544 for (int i = moveStart; i <= moveEnd; i++) {
546 line->setPos(0, line->pos().y() + offset);
550 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
553 // when searching for the first non-date-line we have to take into account that our
554 // model still contains the just removed lines so we cannot simply call updateSceneRect()
555 int numRows = model()->rowCount();
556 QModelIndex firstLineIdx;
558 bool needOffset = false;
561 if (_firstLineRow >= start && _firstLineRow <= end) {
562 _firstLineRow = end + 1;
565 firstLineIdx = model()->index(_firstLineRow, 0);
567 while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
570 _firstLineRow -= end - start + 1;
575 void ChatScene::rowsRemoved()
577 // move the marker line if necessary
582 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
584 layout(tl.row(), br.row(), _sceneRect.width());
588 void ChatScene::updateForViewport(qreal width, qreal height)
590 _viewportHeight = height;
595 void ChatScene::setWidth(qreal width)
597 if (width == _sceneRect.width())
599 layout(0, _lines.count()-1, width);
603 void ChatScene::layout(int start, int end, qreal width)
605 // clock_t startT = clock();
607 // disabling the index while doing this complex updates is about
608 // 2 to 10 times faster!
609 //setItemIndexMethod(QGraphicsScene::NoIndex);
613 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
614 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
615 while (row >= start) {
616 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
620 // remaining items don't need geometry changes, but maybe repositioning?
621 ChatLine *line = _lines.at(row);
622 qreal offset = linePos - (line->scenePos().y() + line->height());
625 line = _lines.at(row--);
626 line->setPos(0, line->scenePos().y() + offset);
632 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
634 updateSceneRect(width);
637 emit layoutChanged();
639 // clock_t endT = clock();
640 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
644 void ChatScene::firstHandlePositionChanged(qreal xpos)
646 if (_firstColHandlePos == xpos)
649 _firstColHandlePos = xpos >= 0 ? xpos : 0;
650 ChatViewSettings viewSettings(this);
651 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
652 ChatViewSettings defaultSettings;
653 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
655 // clock_t startT = clock();
657 // disabling the index while doing this complex updates is about
658 // 2 to 10 times faster!
659 //setItemIndexMethod(QGraphicsScene::NoIndex);
661 QList<ChatLine *>::iterator lineIter = _lines.end();
662 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
663 qreal timestampWidth = firstColumnHandle()->sceneLeft();
664 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
665 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
667 while (lineIter != lineIterBegin) {
669 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
671 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
675 // clock_t endT = clock();
676 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
680 void ChatScene::secondHandlePositionChanged(qreal xpos)
682 if (_secondColHandlePos == xpos)
685 _secondColHandlePos = xpos;
686 ChatViewSettings viewSettings(this);
687 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
688 ChatViewSettings defaultSettings;
689 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
691 // clock_t startT = clock();
693 // disabling the index while doing this complex updates is about
694 // 2 to 10 times faster!
695 //setItemIndexMethod(QGraphicsScene::NoIndex);
697 QList<ChatLine *>::iterator lineIter = _lines.end();
698 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
699 qreal linePos = _sceneRect.y() + _sceneRect.height();
700 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
701 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
702 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
703 while (lineIter != lineIterBegin) {
705 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
707 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
711 emit layoutChanged();
713 // clock_t endT = clock();
714 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
718 void ChatScene::setHandleXLimits()
720 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
721 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
726 void ChatScene::setSelectingItem(ChatItem *item)
728 if (_selectingItem) _selectingItem->clearSelection();
729 _selectingItem = item;
733 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
735 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
736 _selectionStartCol = _selectionMinCol = item->column();
738 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
739 updateSelection(item->mapToScene(itemPos));
743 void ChatScene::updateSelection(const QPointF &pos)
745 int curRow = rowByScenePos(pos);
746 if (curRow < 0) return;
747 int curColumn = (int)columnByScenePos(pos);
748 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
749 if (minColumn != _selectionMinCol) {
750 _selectionMinCol = minColumn;
751 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
752 _lines[l]->setSelected(true, minColumn);
755 int newstart = qMin(curRow, _firstSelectionRow);
756 int newend = qMax(curRow, _firstSelectionRow);
757 if (newstart < _selectionStart) {
758 for (int l = newstart; l < _selectionStart; l++)
759 _lines[l]->setSelected(true, minColumn);
761 if (newstart > _selectionStart) {
762 for (int l = _selectionStart; l < newstart; l++)
763 _lines[l]->setSelected(false);
765 if (newend > _selectionEnd) {
766 for (int l = _selectionEnd+1; l <= newend; l++)
767 _lines[l]->setSelected(true, minColumn);
769 if (newend < _selectionEnd) {
770 for (int l = newend+1; l <= _selectionEnd; l++)
771 _lines[l]->setSelected(false);
774 _selectionStart = newstart;
775 _selectionEnd = newend;
777 if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
778 if (!_selectingItem) {
779 // _selectingItem has been removed already
782 _lines[curRow]->setSelected(false);
783 _isSelecting = false;
784 _selectionStart = -1;
785 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
790 bool ChatScene::isPosOverSelection(const QPointF &pos) const
792 ChatItem *chatItem = chatItemAt(pos);
795 if (hasGlobalSelection()) {
796 int row = chatItem->row();
797 if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
798 return columnByScenePos(pos) >= _selectionMinCol;
801 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
807 bool ChatScene::isScrollingAllowed() const
812 // TODO: Handle clicks and single-item selections too
818 /******** MOUSE HANDLING **************************************************************************/
820 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
822 QPointF pos = event->scenePos();
825 // zoom actions and similar
826 chatView()->addActionsToMenu(&menu, pos);
829 // item-specific options (select link etc)
830 ChatItem *item = chatItemAt(pos);
832 item->addActionsToMenu(&menu, item->mapFromScene(pos));
834 // no item -> default scene actions
835 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
837 // If we have text selected, insert the Copy Selection as first item
838 if (isPosOverSelection(pos)) {
839 QAction *sep = menu.insertSeparator(menu.actions().first());
840 QAction *act = new Action(icon::get("edit-copy"), tr("Copy Selection"), &menu, this,
841 SLOT(selectionToClipboard()), QKeySequence::Copy);
842 menu.insertAction(sep, act);
844 QString searchSelectionText = selection();
845 if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
846 searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
847 searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
849 QAction *webSearchAction = new Action(icon::get("edit-find"), searchSelectionText, &menu, this, SLOT(webSearchOnSelection()));
850 menu.insertAction(sep, webSearchAction);
853 if (QtUi::mainWindow()->menuBar()->isHidden())
854 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
856 // show column reset action if columns have been resized in this session or there is at least one very narrow column
857 if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
858 (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
859 menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, SLOT(resetColumnWidths()), 0));
861 menu.exec(event->screenPos());
865 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
867 if (event->buttons() == Qt::LeftButton) {
868 if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
869 if (_clickTimer.isActive())
871 if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
872 initiateDrag(event->widget());
874 _clickMode = DragStartClick;
875 handleClick(Qt::LeftButton, _clickPos);
877 _clickMode = NoClick;
880 updateSelection(event->scenePos());
881 emit mouseMoveWhileSelecting(event->scenePos());
884 else if (_clickHandled && _clickMode < DoubleClick)
885 QGraphicsScene::mouseMoveEvent(event);
888 QGraphicsScene::mouseMoveEvent(event);
892 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
894 if (event->buttons() == Qt::LeftButton) {
895 _leftButtonPressed = true;
896 _clickHandled = false;
897 if (!isPosOverSelection(event->scenePos())) {
898 // immediately clear selection if clicked outside; otherwise, wait for potential drag
901 if (_clickMode != NoClick && _clickTimer.isActive()) {
902 switch (_clickMode) {
904 _clickMode = SingleClick; break;
906 _clickMode = DoubleClick; break;
908 _clickMode = TripleClick; break;
910 _clickMode = DoubleClick; break;
914 handleClick(Qt::LeftButton, _clickPos);
917 _clickMode = SingleClick;
918 _clickPos = event->scenePos();
922 if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
923 QGraphicsScene::mouseDoubleClickEvent(event);
925 QGraphicsScene::mousePressEvent(event);
929 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
931 // we check for doubleclick ourselves, so just call press handler
932 mousePressEvent(event);
936 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
938 if (event->button() == Qt::LeftButton && _leftButtonPressed) {
939 _leftButtonPressed = false;
940 if (_clickMode != NoClick) {
941 if (_clickMode == SingleClick)
944 if (!_clickTimer.isActive())
945 handleClick(Qt::LeftButton, _clickPos);
948 // no click -> drag or selection move
949 if (isGloballySelecting()) {
950 selectionToClipboard(QClipboard::Selection);
951 _isSelecting = false;
957 QGraphicsScene::mouseReleaseEvent(event);
961 void ChatScene::clickTimeout()
963 if (!_leftButtonPressed && _clickMode == SingleClick)
964 handleClick(Qt::LeftButton, _clickPos);
968 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
970 if (button == Qt::LeftButton) {
973 // Now send click down to items
974 ChatItem *chatItem = chatItemAt(scenePos);
976 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
978 _clickHandled = true;
983 void ChatScene::initiateDrag(QWidget *source)
985 QDrag *drag = new QDrag(source);
986 QMimeData *mimeData = new QMimeData;
987 mimeData->setText(selection());
988 drag->setMimeData(mimeData);
990 drag->exec(Qt::CopyAction);
994 /******** SELECTIONS ******************************************************************************/
996 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
1001 stringToClipboard(selection(), mode);
1005 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
1008 // remove trailing linefeeds
1009 if (str.endsWith('\n'))
1013 case QClipboard::Clipboard:
1014 QApplication::clipboard()->setText(str);
1016 case QClipboard::Selection:
1017 if (QApplication::clipboard()->supportsSelection())
1018 QApplication::clipboard()->setText(str, QClipboard::Selection);
1026 //!\brief Convert current selection to human-readable string.
1027 QString ChatScene::selection() const
1029 //TODO Make selection format configurable!
1030 if (hasGlobalSelection()) {
1031 int start = qMin(_selectionStart, _selectionEnd);
1032 int end = qMax(_selectionStart, _selectionEnd);
1033 if (start < 0 || end >= _lines.count()) {
1034 qDebug() << "Invalid selection range:" << start << end;
1039 for (int l = start; l <= end; l++) {
1040 if (_selectionMinCol == ChatLineModel::TimestampColumn) {
1041 ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
1042 if (!_showSenderBrackets && !_timestampHasBrackets) {
1043 // Only re-add brackets if the current timestamp format does not include them
1044 // -and- sender brackets are disabled. Don't filter on Message::Plain as
1045 // timestamp brackets affect all types of messages.
1046 // Remove any spaces before and after, otherwise it may look weird.
1047 result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
1048 .toString().trimmed());
1050 result += item->data(MessageModel::DisplayRole).toString() + " ";
1053 if (_selectionMinCol <= ChatLineModel::SenderColumn) {
1054 ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
1055 if (!_showSenderBrackets && (_alwaysBracketSender
1056 || item->chatLine()->msgType() == Message::Plain)) {
1057 // Copying to plain-text. Re-add the sender brackets if they're normally hidden
1060 // * All messages in the Chat Monitor
1062 // The Chat Monitor sets alwaysBracketSender() to true.
1063 result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
1066 result += item->data(MessageModel::DisplayRole).toString() + " ";
1069 result += _lines[l]->item(ChatLineModel::ContentsColumn)
1070 ->data(MessageModel::DisplayRole).toString() + "\n";
1074 else if (selectingItem())
1075 return selectingItem()->selection();
1080 bool ChatScene::hasSelection() const
1082 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1086 bool ChatScene::hasGlobalSelection() const
1088 return _selectionStart >= 0;
1092 bool ChatScene::isGloballySelecting() const
1094 return _isSelecting;
1098 void ChatScene::clearGlobalSelection()
1100 if (hasGlobalSelection()) {
1101 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
1102 _lines[l]->setSelected(false);
1103 _isSelecting = false;
1104 _selectionStart = -1;
1109 void ChatScene::clearSelection()
1111 clearGlobalSelection();
1112 if (selectingItem())
1113 selectingItem()->clearSelection();
1117 /******** *************************************************************************************/
1119 void ChatScene::webSearchOnSelection()
1121 if (!hasSelection())
1124 ChatViewSettings settings;
1125 QString webSearchBaseUrl = settings.webSearchUrlFormatString();
1126 QString webSearchUrl = webSearchBaseUrl.replace(QString("%s"), selection());
1127 QUrl url = QUrl::fromUserInput(webSearchUrl);
1128 QDesktopServices::openUrl(url);
1132 /******** *************************************************************************************/
1134 void ChatScene::requestBacklog()
1136 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
1138 return filter->requestBacklog();
1143 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1145 if (x < _firstColHandle->x())
1146 return ChatLineModel::TimestampColumn;
1147 if (x < _secondColHandle->x())
1148 return ChatLineModel::SenderColumn;
1150 return ChatLineModel::ContentsColumn;
1154 int ChatScene::rowByScenePos(qreal y) const
1156 QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1158 // ChatLine should be at the bottom of the list
1159 for (int i = itemList.count()-1; i >= 0; i--) {
1160 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
1168 void ChatScene::updateSceneRect(qreal width)
1170 if (_lines.isEmpty()) {
1171 updateSceneRect(QRectF(0, 0, width, 0));
1175 // we hide day change messages at the top by making the scene rect smaller
1176 // and by calling QGraphicsItem::hide() on all leading day change messages
1177 // the first one is needed to ensure proper scrollbar ranges
1178 // the second for cases where the viewport is larger then the set scenerect
1179 // (in this case the items are shown anyways)
1180 if (_firstLineRow == -1) {
1181 int numRows = model()->rowCount();
1183 QModelIndex firstLineIdx;
1184 while (_firstLineRow < numRows) {
1185 firstLineIdx = model()->index(_firstLineRow, 0);
1186 if ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
1188 _lines.at(_firstLineRow)->hide();
1193 // the following call should be safe. If it crashes something went wrong during insert/remove
1194 if (_firstLineRow < _lines.count()) {
1195 ChatLine *firstLine = _lines.at(_firstLineRow);
1196 ChatLine *lastLine = _lines.last();
1197 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1201 updateSceneRect(QRectF(0, 0, width, 0));
1206 void ChatScene::updateSceneRect(const QRectF &rect)
1214 // ========================================
1215 // Webkit/WebEngine Only stuff
1216 // ========================================
1217 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
1218 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
1220 if (!_showWebPreview)
1223 if (webPreview.urlRect != urlRect)
1224 webPreview.urlRect = urlRect;
1226 if (webPreview.parentItem != parentItem)
1227 webPreview.parentItem = parentItem;
1229 if (webPreview.url != url) {
1230 webPreview.url = url;
1231 // prepare to load a different URL
1232 if (webPreview.previewItem) {
1233 if (webPreview.previewItem->scene())
1234 removeItem(webPreview.previewItem);
1235 delete webPreview.previewItem;
1236 webPreview.previewItem = 0;
1238 webPreview.previewState = WebPreview::NoPreview;
1241 if (webPreview.url.isEmpty())
1244 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1245 switch (webPreview.previewState) {
1246 case WebPreview::NoPreview:
1247 webPreview.previewState = WebPreview::NewPreview;
1248 webPreview.timer.start(500);
1250 case WebPreview::NewPreview:
1251 case WebPreview::DelayPreview:
1252 case WebPreview::ShowPreview:
1253 // we're already waiting for the next step or showing the preview
1255 case WebPreview::HidePreview:
1256 // we still have a valid preview
1257 webPreview.previewState = WebPreview::DelayPreview;
1258 webPreview.timer.start(1000);
1261 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1265 void ChatScene::webPreviewNextStep()
1267 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1268 switch (webPreview.previewState) {
1269 case WebPreview::NoPreview:
1271 case WebPreview::NewPreview:
1272 Q_ASSERT(!webPreview.previewItem);
1273 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1274 webPreview.previewState = WebPreview::DelayPreview;
1275 webPreview.timer.start(1000);
1277 case WebPreview::DelayPreview:
1278 Q_ASSERT(webPreview.previewItem);
1279 // calc position and show
1281 qreal previewY = webPreview.urlRect.bottom();
1282 qreal previewX = webPreview.urlRect.x();
1283 if (previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1284 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1286 if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1287 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1289 webPreview.previewItem->setPos(previewX, previewY);
1291 addItem(webPreview.previewItem);
1292 webPreview.previewState = WebPreview::ShowPreview;
1294 case WebPreview::ShowPreview:
1295 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1296 qWarning() << "removing preview";
1297 if (webPreview.previewItem && webPreview.previewItem->scene())
1298 removeItem(webPreview.previewItem);
1299 // Fall through to deletion!
1300 case WebPreview::HidePreview:
1301 if (webPreview.previewItem) {
1302 delete webPreview.previewItem;
1303 webPreview.previewItem = 0;
1305 webPreview.parentItem = 0;
1306 webPreview.url = QUrl();
1307 webPreview.urlRect = QRectF();
1308 webPreview.previewState = WebPreview::NoPreview;
1310 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1314 void ChatScene::clearWebPreview(ChatItem *parentItem)
1316 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1317 switch (webPreview.previewState) {
1318 case WebPreview::NewPreview:
1319 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1321 case WebPreview::ShowPreview:
1322 if (parentItem == 0 || webPreview.parentItem == parentItem) {
1323 if (webPreview.previewItem && webPreview.previewItem->scene())
1324 removeItem(webPreview.previewItem);
1326 // fall through into to set hidden state
1327 case WebPreview::DelayPreview:
1328 // we're just loading, so haven't shown the preview yet.
1329 webPreview.previewState = WebPreview::HidePreview;
1330 webPreview.timer.start(5000);
1332 case WebPreview::NoPreview:
1333 case WebPreview::HidePreview:
1336 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1342 // ========================================
1343 // end of webkit only
1344 // ========================================
1346 // Local configuration caching
1347 void ChatScene::showWebPreviewChanged()
1349 ChatViewSettings settings;
1350 _showWebPreview = settings.showWebPreview();
1353 void ChatScene::showSenderBracketsChanged()
1355 ChatViewSettings settings;
1356 _showSenderBrackets = settings.showSenderBrackets();
1359 void ChatScene::useCustomTimestampFormatChanged()
1361 ChatViewSettings settings;
1362 _useCustomTimestampFormat = settings.useCustomTimestampFormat();
1363 updateTimestampHasBrackets();
1366 void ChatScene::timestampFormatStringChanged()
1368 ChatViewSettings settings;
1369 _timestampFormatString = settings.timestampFormatString();
1370 updateTimestampHasBrackets();
1373 void ChatScene::updateTimestampHasBrackets()
1375 // Calculate these parameters only as needed, rather than on-demand
1377 if (!_useCustomTimestampFormat) {
1378 // The default timestamp format string does not have brackets, no need to check.
1379 // If UiStyle::updateSystemTimestampFormat() has brackets added, change this, too.
1380 _timestampHasBrackets = false;
1382 // Does the timestamp format contain brackets? For example:
1383 // Classic: "[hh:mm:ss]"
1384 // Modern: " hh:mm:ss"
1386 // Match groups of any opening or closing brackets - (), {}, [], <>, (>, {], etc:
1387 // ^\s*[({[<].+[)}\]>]\s*$
1388 // [...] is a character group containing ...
1389 // ^ matches start of string
1390 // \s* matches any amount of whitespace
1391 // [({[<] matches (, {, [, or <
1392 // .+ matches one or more characters
1393 // [)}\]>] matches ), }, ], or >, escaping the ]
1394 // $ matches end of string
1395 // Alternatively, if opening and closing brackets must be in pairs, use this:
1396 // (^\s*\(.+\)\s*$)|(^\s*\{.+\}\s*$)|(^\s*\[.+\]\s*$)|(^\s*<.+>\s*$)
1397 // Note that '\' must be escaped as '\\'
1398 // Helpful interactive website for debugging and explaining: https://regex101.com/
1399 const QRegExp regExpMatchBrackets("^\\s*[({[<].+[)}\\]>]\\s*$");
1400 _timestampHasBrackets = regExpMatchBrackets.exactMatch(_timestampFormatString);