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>
35 # include <QWebEngineView>
36 #elif defined HAVE_WEBKIT
42 #include "chatlinemodelitem.h"
44 #include "chatviewsettings.h"
46 #include "clientbacklogmanager.h"
47 #include "columnhandleitem.h"
48 #include "contextmenuactionprovider.h"
51 #include "markerlineitem.h"
52 #include "messagefilter.h"
54 #include "qtuistyle.h"
55 #include "webpreviewitem.h"
57 const qreal minContentsWidth = 200;
59 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
60 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
64 _singleBufferId(BufferId()),
65 _sceneRect(0, 0, width, 0),
68 _markerLine(new MarkerLineItem(width)),
69 _markerLineVisible(false),
70 _markerLineValid(false),
71 _markerLineJumpPending(false),
72 _cutoffMode(CutoffRight),
73 _alwaysBracketSender(false),
79 _leftButtonPressed(false)
81 MessageFilter *filter = qobject_cast<MessageFilter *>(model);
82 if (filter && filter->isSingleBufferFilter()) {
83 _singleBufferId = filter->singleBufferId();
87 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
89 ChatViewSettings defaultSettings;
90 _defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
91 _defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
93 ChatViewSettings viewSettings(this);
94 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", _defaultFirstColHandlePos).toInt();
95 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", _defaultSecondColHandlePos).toInt();
97 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
98 addItem(_firstColHandle);
99 _firstColHandle->setXPos(_firstColHandlePos);
100 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
101 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
103 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
104 addItem(_secondColHandle);
105 _secondColHandle->setXPos(_secondColHandlePos);
106 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
108 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
112 if (model->rowCount() > 0)
113 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
115 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
116 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
117 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
118 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
119 connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
120 this, SLOT(rowsRemoved()));
121 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
123 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
124 webPreview.timer.setSingleShot(true);
125 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
127 _showWebPreview = defaultSettings.showWebPreview();
128 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
130 _showSenderBrackets = defaultSettings.showSenderBrackets();
131 defaultSettings.notify("ShowSenderBrackets", this, SLOT(showSenderBracketsChanged()));
133 _useCustomTimestampFormat = defaultSettings.useCustomTimestampFormat();
134 defaultSettings.notify("UseCustomTimestampFormat", this, SLOT(useCustomTimestampFormatChanged()));
136 _timestampFormatString = defaultSettings.timestampFormatString();
137 defaultSettings.notify("TimestampFormat", this, SLOT(timestampFormatStringChanged()));
138 updateTimestampHasBrackets();
140 _clickTimer.setInterval(QApplication::doubleClickInterval());
141 _clickTimer.setSingleShot(true);
142 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
144 setItemIndexMethod(QGraphicsScene::NoIndex);
148 ChatScene::~ChatScene()
153 ChatView *ChatScene::chatView() const
159 ColumnHandleItem *ChatScene::firstColumnHandle() const
161 return _firstColHandle;
165 ColumnHandleItem *ChatScene::secondColumnHandle() const
167 return _secondColHandle;
170 void ChatScene::resetColumnWidths()
172 //make sure first column is at least 80 px wide, second 120 px
173 int firstColHandlePos = qMax(_defaultFirstColHandlePos,
175 int secondColHandlePos = qMax(_defaultSecondColHandlePos,
176 firstColHandlePos + 120);
178 _firstColHandle->setXPos(firstColHandlePos);
179 _secondColHandle->setXPos(secondColHandlePos);
182 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
187 QList<ChatLine *>::ConstIterator start = _lines.begin();
188 QList<ChatLine *>::ConstIterator end = _lines.end();
189 QList<ChatLine *>::ConstIterator middle;
191 int n = int(end - start);
196 middle = start + half;
197 if ((*middle)->msgId() < msgId) {
206 if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
212 if (start == _lines.begin()) // not (yet?) in our scene
215 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
217 if (start == end) { // higher than last element
218 if (!ignoreDayChange)
219 return _lines.last();
221 for (int i = _lines.count() -1; i >= 0; i--) {
222 if (_lines.at(i)->msgType() != Message::DayChange)
228 // return the next-lower line
229 if (!ignoreDayChange)
233 if ((*(--start))->msgType() != Message::DayChange)
236 while (start != _lines.begin());
241 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
243 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
244 ChatLine *line = qgraphicsitem_cast<ChatLine *>(item);
246 return line->itemAt(line->mapFromScene(scenePos));
252 bool ChatScene::containsBuffer(const BufferId &id) const
254 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
256 return filter->containsBuffer(id);
262 void ChatScene::setMarkerLineVisible(bool visible)
264 _markerLineVisible = visible;
265 if (visible && _markerLineValid)
266 markerLine()->setVisible(true);
268 markerLine()->setVisible(false);
272 void ChatScene::setMarkerLine(MsgId msgId)
274 if (!isSingleBufferScene())
277 if (!msgId.isValid())
278 msgId = Client::markerLine(singleBufferId());
280 if (msgId.isValid()) {
281 ChatLine *line = chatLine(msgId, false, true);
283 markerLine()->setChatLine(line);
284 // if this was the last line, we won't see it because it's outside the sceneRect
285 // .. which is exactly what we want :)
286 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
288 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
289 if (markerLine()->pos().y() >= sceneRect().y()) {
290 _markerLineValid = true;
291 if (_markerLineVisible)
292 markerLine()->setVisible(true);
293 if (_markerLineJumpPending) {
294 _markerLineJumpPending = false;
295 if (markerLine()->isVisible()) {
296 markerLine()->ensureVisible(QRectF(), 50, 50);
303 _markerLineValid = false;
304 markerLine()->setVisible(false);
308 void ChatScene::jumpToMarkerLine(bool requestBacklog)
310 if (!isSingleBufferScene())
313 if (markerLine()->isVisible()) {
314 markerLine()->ensureVisible(QRectF(), 50, 50);
317 if (!_markerLineValid && requestBacklog) {
318 MsgId msgId = Client::markerLine(singleBufferId());
319 if (msgId.isValid()) {
320 _markerLineJumpPending = true;
321 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
323 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
324 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
325 // jump tries will eventually cause enough backlog to be fetched.
326 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
327 this->requestBacklog();
333 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
337 // QModelIndex sidx = model()->index(start, 2);
338 // QModelIndex eidx = model()->index(end, 2);
339 // qDebug() << "rowsInserted:";
341 // QModelIndex ssidx = model()->index(start - 1, 2);
342 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
343 // << ssidx.data(Qt::DisplayRole).toString();
345 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
346 // << sidx.data(Qt::DisplayRole).toString();
347 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
348 // << eidx.data(Qt::DisplayRole).toString();
349 // if(end + 1 < model()->rowCount()) {
350 // QModelIndex eeidx = model()->index(end + 1, 2);
351 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
352 // << eeidx.data(Qt::DisplayRole).toString();
357 qreal width = _sceneRect.width();
358 bool atBottom = (start == _lines.count());
359 bool atTop = !atBottom && (start == 0);
361 if (start < _lines.count()) {
362 y = _lines.value(start)->y();
364 else if (atBottom && !_lines.isEmpty()) {
365 y = _lines.last()->y() + _lines.last()->height();
368 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
369 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
370 qreal timestampWidth = firstColumnHandle()->sceneLeft();
371 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
372 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
375 for (int i = end; i >= start; i--) {
376 ChatLine *line = new ChatLine(i, model(),
378 timestampWidth, senderWidth, contentsWidth,
379 senderPos, contentsPos);
381 line->setPos(0, y-h);
382 _lines.insert(start, line);
387 for (int i = start; i <= end; i++) {
388 ChatLine *line = new ChatLine(i, model(),
390 timestampWidth, senderWidth, contentsWidth,
391 senderPos, contentsPos);
392 line->setPos(0, y+h);
394 _lines.insert(i, line);
399 // update existing items
400 for (int i = end+1; i < _lines.count(); i++) {
401 _lines[i]->setRow(i);
405 if (_selectionStart >= 0) {
406 int offset = end - start + 1;
407 int oldStart = _selectionStart;
408 if (_selectionStart >= start)
409 _selectionStart += offset;
410 if (_selectionEnd >= start) {
411 _selectionEnd += offset;
412 if (_selectionStart == oldStart)
413 for (int i = start; i < start + offset; i++)
414 _lines[i]->setSelected(true);
416 if (_firstSelectionRow >= start)
417 _firstSelectionRow += offset;
420 // neither pre- or append means we have to do dirty work: move items...
421 if (!(atTop || atBottom)) {
423 for (int i = 0; i <= end; i++) {
425 line->setPos(0, line->pos().y() - h);
426 if (line == markerLine()->chatLine())
427 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
431 // check if all went right
432 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
434 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
435 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
436 // 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();
437 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
438 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
442 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
443 // if(end + 1 < _lines.count()) {
444 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
445 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
446 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
447 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
448 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
454 if (start < _firstLineRow) {
455 int prevFirstLineRow = _firstLineRow + (end - start + 1);
456 for (int i = end + 1; i < prevFirstLineRow; i++) {
457 _lines.at(i)->show();
460 // force new search for first proper line
465 emit lastLineChanged(_lines.last(), h);
468 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
469 if (!_markerLineValid)
474 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
478 qreal h = 0; // total height of removed items;
480 bool atTop = (start == 0);
481 bool atBottom = (end == _lines.count() - 1);
484 if (_selectingItem) {
485 int row = _selectingItem->row();
486 if (row >= start && row <= end)
490 // remove items from scene
491 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
492 int lineCount = start;
493 while (lineIter != _lines.end() && lineCount <= end) {
494 if ((*lineIter) == markerLine()->chatLine())
495 markerLine()->setChatLine(0);
496 h += (*lineIter)->height();
498 lineIter = _lines.erase(lineIter);
502 // update rows of remaining chatlines
503 for (int i = start; i < _lines.count(); i++) {
504 _lines.at(i)->setRow(i);
508 if (_selectionStart >= 0) {
509 int offset = end - start + 1;
510 if (_selectionStart >= start)
511 _selectionStart = qMax(_selectionStart - offset, start);
512 if (_selectionEnd >= start)
513 _selectionEnd -= offset;
514 if (_firstSelectionRow >= start)
515 _firstSelectionRow -= offset;
517 if (_selectionEnd < _selectionStart) {
518 _isSelecting = false;
519 _selectionStart = -1;
523 // neither removing at bottom or top means we have to move items...
524 if (!(atTop || atBottom)) {
527 int moveEnd = _lines.count() - 1;
528 if (start < _lines.count() - start) {
538 for (int i = moveStart; i <= moveEnd; i++) {
540 line->setPos(0, line->pos().y() + offset);
544 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
547 // when searching for the first non-date-line we have to take into account that our
548 // model still contains the just removed lines so we cannot simply call updateSceneRect()
549 int numRows = model()->rowCount();
550 QModelIndex firstLineIdx;
552 bool needOffset = false;
555 if (_firstLineRow >= start && _firstLineRow <= end) {
556 _firstLineRow = end + 1;
559 firstLineIdx = model()->index(_firstLineRow, 0);
561 while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
564 _firstLineRow -= end - start + 1;
569 void ChatScene::rowsRemoved()
571 // move the marker line if necessary
576 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
578 layout(tl.row(), br.row(), _sceneRect.width());
582 void ChatScene::updateForViewport(qreal width, qreal height)
584 _viewportHeight = height;
589 void ChatScene::setWidth(qreal width)
591 if (width == _sceneRect.width())
593 layout(0, _lines.count()-1, width);
597 void ChatScene::layout(int start, int end, qreal width)
599 // clock_t startT = clock();
601 // disabling the index while doing this complex updates is about
602 // 2 to 10 times faster!
603 //setItemIndexMethod(QGraphicsScene::NoIndex);
607 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
608 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
609 while (row >= start) {
610 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
614 // remaining items don't need geometry changes, but maybe repositioning?
615 ChatLine *line = _lines.at(row);
616 qreal offset = linePos - (line->scenePos().y() + line->height());
619 line = _lines.at(row--);
620 line->setPos(0, line->scenePos().y() + offset);
626 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
628 updateSceneRect(width);
631 emit layoutChanged();
633 // clock_t endT = clock();
634 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
638 void ChatScene::firstHandlePositionChanged(qreal xpos)
640 if (_firstColHandlePos == xpos)
643 _firstColHandlePos = xpos >= 0 ? xpos : 0;
644 ChatViewSettings viewSettings(this);
645 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
646 ChatViewSettings defaultSettings;
647 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
649 // clock_t startT = clock();
651 // disabling the index while doing this complex updates is about
652 // 2 to 10 times faster!
653 //setItemIndexMethod(QGraphicsScene::NoIndex);
655 QList<ChatLine *>::iterator lineIter = _lines.end();
656 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
657 qreal timestampWidth = firstColumnHandle()->sceneLeft();
658 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
659 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
661 while (lineIter != lineIterBegin) {
663 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
665 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
669 // clock_t endT = clock();
670 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
674 void ChatScene::secondHandlePositionChanged(qreal xpos)
676 if (_secondColHandlePos == xpos)
679 _secondColHandlePos = xpos;
680 ChatViewSettings viewSettings(this);
681 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
682 ChatViewSettings defaultSettings;
683 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
685 // clock_t startT = clock();
687 // disabling the index while doing this complex updates is about
688 // 2 to 10 times faster!
689 //setItemIndexMethod(QGraphicsScene::NoIndex);
691 QList<ChatLine *>::iterator lineIter = _lines.end();
692 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
693 qreal linePos = _sceneRect.y() + _sceneRect.height();
694 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
695 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
696 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
697 while (lineIter != lineIterBegin) {
699 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
701 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
705 emit layoutChanged();
707 // clock_t endT = clock();
708 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
712 void ChatScene::setHandleXLimits()
714 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
715 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
720 void ChatScene::setSelectingItem(ChatItem *item)
722 if (_selectingItem) _selectingItem->clearSelection();
723 _selectingItem = item;
727 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
729 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
730 _selectionStartCol = _selectionMinCol = item->column();
732 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
733 updateSelection(item->mapToScene(itemPos));
737 void ChatScene::updateSelection(const QPointF &pos)
739 int curRow = rowByScenePos(pos);
740 if (curRow < 0) return;
741 int curColumn = (int)columnByScenePos(pos);
742 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
743 if (minColumn != _selectionMinCol) {
744 _selectionMinCol = minColumn;
745 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
746 _lines[l]->setSelected(true, minColumn);
749 int newstart = qMin(curRow, _firstSelectionRow);
750 int newend = qMax(curRow, _firstSelectionRow);
751 if (newstart < _selectionStart) {
752 for (int l = newstart; l < _selectionStart; l++)
753 _lines[l]->setSelected(true, minColumn);
755 if (newstart > _selectionStart) {
756 for (int l = _selectionStart; l < newstart; l++)
757 _lines[l]->setSelected(false);
759 if (newend > _selectionEnd) {
760 for (int l = _selectionEnd+1; l <= newend; l++)
761 _lines[l]->setSelected(true, minColumn);
763 if (newend < _selectionEnd) {
764 for (int l = newend+1; l <= _selectionEnd; l++)
765 _lines[l]->setSelected(false);
768 _selectionStart = newstart;
769 _selectionEnd = newend;
771 if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
772 if (!_selectingItem) {
773 // _selectingItem has been removed already
776 _lines[curRow]->setSelected(false);
777 _isSelecting = false;
778 _selectionStart = -1;
779 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
784 bool ChatScene::isPosOverSelection(const QPointF &pos) const
786 ChatItem *chatItem = chatItemAt(pos);
789 if (hasGlobalSelection()) {
790 int row = chatItem->row();
791 if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
792 return columnByScenePos(pos) >= _selectionMinCol;
795 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
801 bool ChatScene::isScrollingAllowed() const
806 // TODO: Handle clicks and single-item selections too
812 /******** MOUSE HANDLING **************************************************************************/
814 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
816 QPointF pos = event->scenePos();
819 // zoom actions and similar
820 chatView()->addActionsToMenu(&menu, pos);
823 // item-specific options (select link etc)
824 ChatItem *item = chatItemAt(pos);
826 item->addActionsToMenu(&menu, item->mapFromScene(pos));
828 // no item -> default scene actions
829 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
831 // If we have text selected, insert the Copy Selection as first item
832 if (isPosOverSelection(pos)) {
833 QAction *sep = menu.insertSeparator(menu.actions().first());
834 QAction *act = new Action(icon::get("edit-copy"), tr("Copy Selection"), &menu, this,
835 SLOT(selectionToClipboard()), QKeySequence::Copy);
836 menu.insertAction(sep, act);
838 QString searchSelectionText = selection();
839 if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
840 searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
841 searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
843 QAction *webSearchAction = new Action(icon::get("edit-find"), searchSelectionText, &menu, this, SLOT(webSearchOnSelection()));
844 menu.insertAction(sep, webSearchAction);
847 if (QtUi::mainWindow()->menuBar()->isHidden())
848 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
850 // show column reset action if columns have been resized in this session or there is at least one very narrow column
851 if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
852 (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
853 menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, SLOT(resetColumnWidths()), 0));
855 menu.exec(event->screenPos());
859 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
861 if (event->buttons() == Qt::LeftButton) {
862 if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
863 if (_clickTimer.isActive())
865 if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
866 initiateDrag(event->widget());
868 _clickMode = DragStartClick;
869 handleClick(Qt::LeftButton, _clickPos);
871 _clickMode = NoClick;
874 updateSelection(event->scenePos());
875 emit mouseMoveWhileSelecting(event->scenePos());
878 else if (_clickHandled && _clickMode < DoubleClick)
879 QGraphicsScene::mouseMoveEvent(event);
882 QGraphicsScene::mouseMoveEvent(event);
886 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
888 if (event->buttons() == Qt::LeftButton) {
889 _leftButtonPressed = true;
890 _clickHandled = false;
891 if (!isPosOverSelection(event->scenePos())) {
892 // immediately clear selection if clicked outside; otherwise, wait for potential drag
895 if (_clickMode != NoClick && _clickTimer.isActive()) {
896 switch (_clickMode) {
898 _clickMode = SingleClick; break;
900 _clickMode = DoubleClick; break;
902 _clickMode = TripleClick; break;
904 _clickMode = DoubleClick; break;
908 handleClick(Qt::LeftButton, _clickPos);
911 _clickMode = SingleClick;
912 _clickPos = event->scenePos();
916 if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
917 QGraphicsScene::mouseDoubleClickEvent(event);
919 QGraphicsScene::mousePressEvent(event);
923 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
925 // we check for doubleclick ourselves, so just call press handler
926 mousePressEvent(event);
930 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
932 if (event->button() == Qt::LeftButton && _leftButtonPressed) {
933 _leftButtonPressed = false;
934 if (_clickMode != NoClick) {
935 if (_clickMode == SingleClick)
938 if (!_clickTimer.isActive())
939 handleClick(Qt::LeftButton, _clickPos);
942 // no click -> drag or selection move
943 if (isGloballySelecting()) {
944 selectionToClipboard(QClipboard::Selection);
945 _isSelecting = false;
951 QGraphicsScene::mouseReleaseEvent(event);
955 void ChatScene::clickTimeout()
957 if (!_leftButtonPressed && _clickMode == SingleClick)
958 handleClick(Qt::LeftButton, _clickPos);
962 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
964 if (button == Qt::LeftButton) {
967 // Now send click down to items
968 ChatItem *chatItem = chatItemAt(scenePos);
970 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
972 _clickHandled = true;
977 void ChatScene::initiateDrag(QWidget *source)
979 QDrag *drag = new QDrag(source);
980 QMimeData *mimeData = new QMimeData;
981 mimeData->setText(selection());
982 drag->setMimeData(mimeData);
984 drag->exec(Qt::CopyAction);
988 /******** SELECTIONS ******************************************************************************/
990 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
995 stringToClipboard(selection(), mode);
999 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
1002 // remove trailing linefeeds
1003 if (str.endsWith('\n'))
1007 case QClipboard::Clipboard:
1008 QApplication::clipboard()->setText(str);
1010 case QClipboard::Selection:
1011 if (QApplication::clipboard()->supportsSelection())
1012 QApplication::clipboard()->setText(str, QClipboard::Selection);
1020 //!\brief Convert current selection to human-readable string.
1021 QString ChatScene::selection() const
1023 //TODO Make selection format configurable!
1024 if (hasGlobalSelection()) {
1025 int start = qMin(_selectionStart, _selectionEnd);
1026 int end = qMax(_selectionStart, _selectionEnd);
1027 if (start < 0 || end >= _lines.count()) {
1028 qDebug() << "Invalid selection range:" << start << end;
1033 for (int l = start; l <= end; l++) {
1034 if (_selectionMinCol == ChatLineModel::TimestampColumn) {
1035 ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
1036 if (!_showSenderBrackets && !_timestampHasBrackets) {
1037 // Only re-add brackets if the current timestamp format does not include them
1038 // -and- sender brackets are disabled. Don't filter on Message::Plain as
1039 // timestamp brackets affect all types of messages.
1040 // Remove any spaces before and after, otherwise it may look weird.
1041 result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
1042 .toString().trimmed());
1044 result += item->data(MessageModel::DisplayRole).toString() + " ";
1047 if (_selectionMinCol <= ChatLineModel::SenderColumn) {
1048 ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
1049 if (!_showSenderBrackets && (_alwaysBracketSender
1050 || item->chatLine()->msgType() == Message::Plain)) {
1051 // Copying to plain-text. Re-add the sender brackets if they're normally hidden
1054 // * All messages in the Chat Monitor
1056 // The Chat Monitor sets alwaysBracketSender() to true.
1057 result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
1060 result += item->data(MessageModel::DisplayRole).toString() + " ";
1063 result += _lines[l]->item(ChatLineModel::ContentsColumn)
1064 ->data(MessageModel::DisplayRole).toString() + "\n";
1068 else if (selectingItem())
1069 return selectingItem()->selection();
1074 bool ChatScene::hasSelection() const
1076 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1080 bool ChatScene::hasGlobalSelection() const
1082 return _selectionStart >= 0;
1086 bool ChatScene::isGloballySelecting() const
1088 return _isSelecting;
1092 void ChatScene::clearGlobalSelection()
1094 if (hasGlobalSelection()) {
1095 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
1096 _lines[l]->setSelected(false);
1097 _isSelecting = false;
1098 _selectionStart = -1;
1103 void ChatScene::clearSelection()
1105 clearGlobalSelection();
1106 if (selectingItem())
1107 selectingItem()->clearSelection();
1111 /******** *************************************************************************************/
1113 void ChatScene::webSearchOnSelection()
1115 if (!hasSelection())
1118 ChatViewSettings settings;
1119 QString webSearchBaseUrl = settings.webSearchUrlFormatString();
1120 QString webSearchUrl = webSearchBaseUrl.replace(QString("%s"), selection());
1121 QUrl url = QUrl::fromUserInput(webSearchUrl);
1122 QDesktopServices::openUrl(url);
1126 /******** *************************************************************************************/
1128 void ChatScene::requestBacklog()
1130 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
1132 return filter->requestBacklog();
1137 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1139 if (x < _firstColHandle->x())
1140 return ChatLineModel::TimestampColumn;
1141 if (x < _secondColHandle->x())
1142 return ChatLineModel::SenderColumn;
1144 return ChatLineModel::ContentsColumn;
1148 int ChatScene::rowByScenePos(qreal y) const
1150 QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1152 // ChatLine should be at the bottom of the list
1153 for (int i = itemList.count()-1; i >= 0; i--) {
1154 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
1162 void ChatScene::updateSceneRect(qreal width)
1164 if (_lines.isEmpty()) {
1165 updateSceneRect(QRectF(0, 0, width, 0));
1169 // we hide day change messages at the top by making the scene rect smaller
1170 // and by calling QGraphicsItem::hide() on all leading day change messages
1171 // the first one is needed to ensure proper scrollbar ranges
1172 // the second for cases where the viewport is larger then the set scenerect
1173 // (in this case the items are shown anyways)
1174 if (_firstLineRow == -1) {
1175 int numRows = model()->rowCount();
1177 QModelIndex firstLineIdx;
1178 while (_firstLineRow < numRows) {
1179 firstLineIdx = model()->index(_firstLineRow, 0);
1180 if ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
1182 _lines.at(_firstLineRow)->hide();
1187 // the following call should be safe. If it crashes something went wrong during insert/remove
1188 if (_firstLineRow < _lines.count()) {
1189 ChatLine *firstLine = _lines.at(_firstLineRow);
1190 ChatLine *lastLine = _lines.last();
1191 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1195 updateSceneRect(QRectF(0, 0, width, 0));
1200 void ChatScene::updateSceneRect(const QRectF &rect)
1208 // ========================================
1209 // Webkit/WebEngine Only stuff
1210 // ========================================
1211 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
1212 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
1214 if (!_showWebPreview)
1217 if (webPreview.urlRect != urlRect)
1218 webPreview.urlRect = urlRect;
1220 if (webPreview.parentItem != parentItem)
1221 webPreview.parentItem = parentItem;
1223 if (webPreview.url != url) {
1224 webPreview.url = url;
1225 // prepare to load a different URL
1226 if (webPreview.previewItem) {
1227 if (webPreview.previewItem->scene())
1228 removeItem(webPreview.previewItem);
1229 delete webPreview.previewItem;
1230 webPreview.previewItem = 0;
1232 webPreview.previewState = WebPreview::NoPreview;
1235 if (webPreview.url.isEmpty())
1238 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1239 switch (webPreview.previewState) {
1240 case WebPreview::NoPreview:
1241 webPreview.previewState = WebPreview::NewPreview;
1242 webPreview.timer.start(500);
1244 case WebPreview::NewPreview:
1245 case WebPreview::DelayPreview:
1246 case WebPreview::ShowPreview:
1247 // we're already waiting for the next step or showing the preview
1249 case WebPreview::HidePreview:
1250 // we still have a valid preview
1251 webPreview.previewState = WebPreview::DelayPreview;
1252 webPreview.timer.start(1000);
1255 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1259 void ChatScene::webPreviewNextStep()
1261 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1262 switch (webPreview.previewState) {
1263 case WebPreview::NoPreview:
1265 case WebPreview::NewPreview:
1266 Q_ASSERT(!webPreview.previewItem);
1267 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1268 webPreview.previewState = WebPreview::DelayPreview;
1269 webPreview.timer.start(1000);
1271 case WebPreview::DelayPreview:
1272 Q_ASSERT(webPreview.previewItem);
1273 // calc position and show
1275 qreal previewY = webPreview.urlRect.bottom();
1276 qreal previewX = webPreview.urlRect.x();
1277 if (previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1278 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1280 if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1281 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1283 webPreview.previewItem->setPos(previewX, previewY);
1285 addItem(webPreview.previewItem);
1286 webPreview.previewState = WebPreview::ShowPreview;
1288 case WebPreview::ShowPreview:
1289 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1290 qWarning() << "removing preview";
1291 if (webPreview.previewItem && webPreview.previewItem->scene()) {
1292 removeItem(webPreview.previewItem);
1295 // Intentional fallthrough
1297 case WebPreview::HidePreview:
1298 if (webPreview.previewItem) {
1299 delete webPreview.previewItem;
1300 webPreview.previewItem = 0;
1302 webPreview.parentItem = 0;
1303 webPreview.url = QUrl();
1304 webPreview.urlRect = QRectF();
1305 webPreview.previewState = WebPreview::NoPreview;
1307 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1311 void ChatScene::clearWebPreview(ChatItem *parentItem)
1313 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1314 switch (webPreview.previewState) {
1315 case WebPreview::NewPreview:
1316 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1318 case WebPreview::ShowPreview:
1319 if (parentItem == 0 || webPreview.parentItem == parentItem) {
1320 if (webPreview.previewItem && webPreview.previewItem->scene())
1321 removeItem(webPreview.previewItem);
1324 // Intentional fallthrough
1326 case WebPreview::DelayPreview:
1327 // we're just loading, so haven't shown the preview yet.
1328 webPreview.previewState = WebPreview::HidePreview;
1329 webPreview.timer.start(5000);
1331 case WebPreview::NoPreview:
1332 case WebPreview::HidePreview:
1335 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1341 // ========================================
1342 // end of webkit only
1343 // ========================================
1345 // Local configuration caching
1346 void ChatScene::showWebPreviewChanged()
1348 ChatViewSettings settings;
1349 _showWebPreview = settings.showWebPreview();
1352 void ChatScene::showSenderBracketsChanged()
1354 ChatViewSettings settings;
1355 _showSenderBrackets = settings.showSenderBrackets();
1358 void ChatScene::useCustomTimestampFormatChanged()
1360 ChatViewSettings settings;
1361 _useCustomTimestampFormat = settings.useCustomTimestampFormat();
1362 updateTimestampHasBrackets();
1365 void ChatScene::timestampFormatStringChanged()
1367 ChatViewSettings settings;
1368 _timestampFormatString = settings.timestampFormatString();
1369 updateTimestampHasBrackets();
1372 void ChatScene::updateTimestampHasBrackets()
1374 // Calculate these parameters only as needed, rather than on-demand
1376 if (!_useCustomTimestampFormat) {
1377 // The default timestamp format string does not have brackets, no need to check.
1378 // If UiStyle::updateSystemTimestampFormat() has brackets added, change this, too.
1379 _timestampHasBrackets = false;
1381 // Does the timestamp format contain brackets? For example:
1382 // Classic: "[hh:mm:ss]"
1383 // Modern: " hh:mm:ss"
1385 // Match groups of any opening or closing brackets - (), {}, [], <>, (>, {], etc:
1386 // ^\s*[({[<].+[)}\]>]\s*$
1387 // [...] is a character group containing ...
1388 // ^ matches start of string
1389 // \s* matches any amount of whitespace
1390 // [({[<] matches (, {, [, or <
1391 // .+ matches one or more characters
1392 // [)}\]>] matches ), }, ], or >, escaping the ]
1393 // $ matches end of string
1394 // Alternatively, if opening and closing brackets must be in pairs, use this:
1395 // (^\s*\(.+\)\s*$)|(^\s*\{.+\}\s*$)|(^\s*\[.+\]\s*$)|(^\s*<.+>\s*$)
1396 // Note that '\' must be escaped as '\\'
1397 // Helpful interactive website for debugging and explaining: https://regex101.com/
1398 const QRegExp regExpMatchBrackets("^\\s*[({[<].+[)}\\]>]\\s*$");
1399 _timestampHasBrackets = regExpMatchBrackets.exactMatch(_timestampFormatString);