1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 <QApplication>
23 #include <QDesktopServices>
25 #include <QGraphicsSceneMouseEvent>
30 #include <QPersistentModelIndex>
40 # include <QWebEngineView>
41 #elif defined HAVE_WEBKIT
47 #include "chatlinemodelitem.h"
48 #include "chatscene.h"
51 #include "clientbacklogmanager.h"
52 #include "columnhandleitem.h"
53 #include "contextmenuactionprovider.h"
55 #include "markerlineitem.h"
56 #include "messagefilter.h"
58 #include "qtuistyle.h"
59 #include "chatviewsettings.h"
60 #include "webpreviewitem.h"
62 const qreal minContentsWidth = 200;
64 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
65 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
69 _singleBufferId(BufferId()),
70 _sceneRect(0, 0, width, 0),
73 _markerLine(new MarkerLineItem(width)),
74 _markerLineVisible(false),
75 _markerLineValid(false),
76 _markerLineJumpPending(false),
77 _cutoffMode(CutoffRight),
83 _leftButtonPressed(false)
85 MessageFilter *filter = qobject_cast<MessageFilter *>(model);
86 if (filter && filter->isSingleBufferFilter()) {
87 _singleBufferId = filter->singleBufferId();
91 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
93 ChatViewSettings defaultSettings;
94 _defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
95 _defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
97 ChatViewSettings viewSettings(this);
98 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", _defaultFirstColHandlePos).toInt();
99 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", _defaultSecondColHandlePos).toInt();
101 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
102 addItem(_firstColHandle);
103 _firstColHandle->setXPos(_firstColHandlePos);
104 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
105 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
107 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
108 addItem(_secondColHandle);
109 _secondColHandle->setXPos(_secondColHandlePos);
110 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
112 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
116 if (model->rowCount() > 0)
117 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
119 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
120 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
121 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
122 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
123 connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
124 this, SLOT(rowsRemoved()));
125 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
127 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
128 webPreview.timer.setSingleShot(true);
129 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
131 _showWebPreview = defaultSettings.showWebPreview();
132 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
134 _showSenderBrackets = defaultSettings.showSenderBrackets();
135 defaultSettings.notify("ShowSenderBrackets", this, SLOT(showSenderBracketsChanged()));
137 _timestampFormatString = defaultSettings.timestampFormatString();
138 defaultSettings.notify("TimestampFormat", this, SLOT(timestampFormatStringChanged()));
139 updateTimestampHasBrackets();
141 _clickTimer.setInterval(QApplication::doubleClickInterval());
142 _clickTimer.setSingleShot(true);
143 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
145 setItemIndexMethod(QGraphicsScene::NoIndex);
149 ChatScene::~ChatScene()
154 ChatView *ChatScene::chatView() const
160 ColumnHandleItem *ChatScene::firstColumnHandle() const
162 return _firstColHandle;
166 ColumnHandleItem *ChatScene::secondColumnHandle() const
168 return _secondColHandle;
171 void ChatScene::resetColumnWidths()
173 //make sure first column is at least 80 px wide, second 120 px
174 int firstColHandlePos = qMax(_defaultFirstColHandlePos,
176 int secondColHandlePos = qMax(_defaultSecondColHandlePos,
177 firstColHandlePos + 120);
179 _firstColHandle->setXPos(firstColHandlePos);
180 _secondColHandle->setXPos(secondColHandlePos);
183 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
188 QList<ChatLine *>::ConstIterator start = _lines.begin();
189 QList<ChatLine *>::ConstIterator end = _lines.end();
190 QList<ChatLine *>::ConstIterator middle;
192 int n = int(end - start);
197 middle = start + half;
198 if ((*middle)->msgId() < msgId) {
207 if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
213 if (start == _lines.begin()) // not (yet?) in our scene
216 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
218 if (start == end) { // higher than last element
219 if (!ignoreDayChange)
220 return _lines.last();
222 for (int i = _lines.count() -1; i >= 0; i--) {
223 if (_lines.at(i)->msgType() != Message::DayChange)
229 // return the next-lower line
230 if (!ignoreDayChange)
234 if ((*(--start))->msgType() != Message::DayChange)
237 while (start != _lines.begin());
242 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
244 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
245 ChatLine *line = qgraphicsitem_cast<ChatLine *>(item);
247 return line->itemAt(line->mapFromScene(scenePos));
253 bool ChatScene::containsBuffer(const BufferId &id) const
255 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
257 return filter->containsBuffer(id);
263 void ChatScene::setMarkerLineVisible(bool visible)
265 _markerLineVisible = visible;
266 if (visible && _markerLineValid)
267 markerLine()->setVisible(true);
269 markerLine()->setVisible(false);
273 void ChatScene::setMarkerLine(MsgId msgId)
275 if (!isSingleBufferScene())
278 if (!msgId.isValid())
279 msgId = Client::markerLine(singleBufferId());
281 if (msgId.isValid()) {
282 ChatLine *line = chatLine(msgId, false, true);
284 markerLine()->setChatLine(line);
285 // if this was the last line, we won't see it because it's outside the sceneRect
286 // .. which is exactly what we want :)
287 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
289 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
290 if (markerLine()->pos().y() >= sceneRect().y()) {
291 _markerLineValid = true;
292 if (_markerLineVisible)
293 markerLine()->setVisible(true);
294 if (_markerLineJumpPending) {
295 _markerLineJumpPending = false;
296 if (markerLine()->isVisible()) {
297 markerLine()->ensureVisible(QRectF(), 50, 50);
304 _markerLineValid = false;
305 markerLine()->setVisible(false);
309 void ChatScene::jumpToMarkerLine(bool requestBacklog)
311 if (!isSingleBufferScene())
314 if (markerLine()->isVisible()) {
315 markerLine()->ensureVisible(QRectF(), 50, 50);
318 if (!_markerLineValid && requestBacklog) {
319 MsgId msgId = Client::markerLine(singleBufferId());
320 if (msgId.isValid()) {
321 _markerLineJumpPending = true;
322 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
324 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
325 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
326 // jump tries will eventually cause enough backlog to be fetched.
327 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
328 this->requestBacklog();
334 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
338 // QModelIndex sidx = model()->index(start, 2);
339 // QModelIndex eidx = model()->index(end, 2);
340 // qDebug() << "rowsInserted:";
342 // QModelIndex ssidx = model()->index(start - 1, 2);
343 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
344 // << ssidx.data(Qt::DisplayRole).toString();
346 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
347 // << sidx.data(Qt::DisplayRole).toString();
348 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
349 // << eidx.data(Qt::DisplayRole).toString();
350 // if(end + 1 < model()->rowCount()) {
351 // QModelIndex eeidx = model()->index(end + 1, 2);
352 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
353 // << eeidx.data(Qt::DisplayRole).toString();
358 qreal width = _sceneRect.width();
359 bool atBottom = (start == _lines.count());
360 bool atTop = !atBottom && (start == 0);
362 if (start < _lines.count()) {
363 y = _lines.value(start)->y();
365 else if (atBottom && !_lines.isEmpty()) {
366 y = _lines.last()->y() + _lines.last()->height();
369 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
370 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
371 qreal timestampWidth = firstColumnHandle()->sceneLeft();
372 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
373 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
376 for (int i = end; i >= start; i--) {
377 ChatLine *line = new ChatLine(i, model(),
379 timestampWidth, senderWidth, contentsWidth,
380 senderPos, contentsPos);
382 line->setPos(0, y-h);
383 _lines.insert(start, line);
388 for (int i = start; i <= end; i++) {
389 ChatLine *line = new ChatLine(i, model(),
391 timestampWidth, senderWidth, contentsWidth,
392 senderPos, contentsPos);
393 line->setPos(0, y+h);
395 _lines.insert(i, line);
400 // update existing items
401 for (int i = end+1; i < _lines.count(); i++) {
402 _lines[i]->setRow(i);
406 if (_selectionStart >= 0) {
407 int offset = end - start + 1;
408 int oldStart = _selectionStart;
409 if (_selectionStart >= start)
410 _selectionStart += offset;
411 if (_selectionEnd >= start) {
412 _selectionEnd += offset;
413 if (_selectionStart == oldStart)
414 for (int i = start; i < start + offset; i++)
415 _lines[i]->setSelected(true);
417 if (_firstSelectionRow >= start)
418 _firstSelectionRow += offset;
421 // neither pre- or append means we have to do dirty work: move items...
422 if (!(atTop || atBottom)) {
424 for (int i = 0; i <= end; i++) {
426 line->setPos(0, line->pos().y() - h);
427 if (line == markerLine()->chatLine())
428 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
432 // check if all went right
433 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
435 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
436 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
437 // 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();
438 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
439 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
443 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
444 // if(end + 1 < _lines.count()) {
445 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
446 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
447 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
448 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
449 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
455 if (start < _firstLineRow) {
456 int prevFirstLineRow = _firstLineRow + (end - start + 1);
457 for (int i = end + 1; i < prevFirstLineRow; i++) {
458 _lines.at(i)->show();
461 // force new search for first proper line
466 emit lastLineChanged(_lines.last(), h);
469 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
470 if (!_markerLineValid)
475 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
479 qreal h = 0; // total height of removed items;
481 bool atTop = (start == 0);
482 bool atBottom = (end == _lines.count() - 1);
485 if (_selectingItem) {
486 int row = _selectingItem->row();
487 if (row >= start && row <= end)
491 // remove items from scene
492 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
493 int lineCount = start;
494 while (lineIter != _lines.end() && lineCount <= end) {
495 if ((*lineIter) == markerLine()->chatLine())
496 markerLine()->setChatLine(0);
497 h += (*lineIter)->height();
499 lineIter = _lines.erase(lineIter);
503 // update rows of remaining chatlines
504 for (int i = start; i < _lines.count(); i++) {
505 _lines.at(i)->setRow(i);
509 if (_selectionStart >= 0) {
510 int offset = end - start + 1;
511 if (_selectionStart >= start)
512 _selectionStart = qMax(_selectionStart - offset, start);
513 if (_selectionEnd >= start)
514 _selectionEnd -= offset;
515 if (_firstSelectionRow >= start)
516 _firstSelectionRow -= offset;
518 if (_selectionEnd < _selectionStart) {
519 _isSelecting = false;
520 _selectionStart = -1;
524 // neither removing at bottom or top means we have to move items...
525 if (!(atTop || atBottom)) {
528 int moveEnd = _lines.count() - 1;
529 if (start < _lines.count() - start) {
539 for (int i = moveStart; i <= moveEnd; i++) {
541 line->setPos(0, line->pos().y() + offset);
545 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
548 // when searching for the first non-date-line we have to take into account that our
549 // model still contains the just removed lines so we cannot simply call updateSceneRect()
550 int numRows = model()->rowCount();
551 QModelIndex firstLineIdx;
553 bool needOffset = false;
556 if (_firstLineRow >= start && _firstLineRow <= end) {
557 _firstLineRow = end + 1;
560 firstLineIdx = model()->index(_firstLineRow, 0);
562 while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
565 _firstLineRow -= end - start + 1;
570 void ChatScene::rowsRemoved()
572 // move the marker line if necessary
577 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
579 layout(tl.row(), br.row(), _sceneRect.width());
583 void ChatScene::updateForViewport(qreal width, qreal height)
585 _viewportHeight = height;
590 void ChatScene::setWidth(qreal width)
592 if (width == _sceneRect.width())
594 layout(0, _lines.count()-1, width);
598 void ChatScene::layout(int start, int end, qreal width)
600 // clock_t startT = clock();
602 // disabling the index while doing this complex updates is about
603 // 2 to 10 times faster!
604 //setItemIndexMethod(QGraphicsScene::NoIndex);
608 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
609 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
610 while (row >= start) {
611 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
615 // remaining items don't need geometry changes, but maybe repositioning?
616 ChatLine *line = _lines.at(row);
617 qreal offset = linePos - (line->scenePos().y() + line->height());
620 line = _lines.at(row--);
621 line->setPos(0, line->scenePos().y() + offset);
627 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
629 updateSceneRect(width);
632 emit layoutChanged();
634 // clock_t endT = clock();
635 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
639 void ChatScene::firstHandlePositionChanged(qreal xpos)
641 if (_firstColHandlePos == xpos)
644 _firstColHandlePos = xpos >= 0 ? xpos : 0;
645 ChatViewSettings viewSettings(this);
646 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
647 ChatViewSettings defaultSettings;
648 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
650 // clock_t startT = clock();
652 // disabling the index while doing this complex updates is about
653 // 2 to 10 times faster!
654 //setItemIndexMethod(QGraphicsScene::NoIndex);
656 QList<ChatLine *>::iterator lineIter = _lines.end();
657 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
658 qreal timestampWidth = firstColumnHandle()->sceneLeft();
659 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
660 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
662 while (lineIter != lineIterBegin) {
664 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
666 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
670 // clock_t endT = clock();
671 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
675 void ChatScene::secondHandlePositionChanged(qreal xpos)
677 if (_secondColHandlePos == xpos)
680 _secondColHandlePos = xpos;
681 ChatViewSettings viewSettings(this);
682 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
683 ChatViewSettings defaultSettings;
684 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
686 // clock_t startT = clock();
688 // disabling the index while doing this complex updates is about
689 // 2 to 10 times faster!
690 //setItemIndexMethod(QGraphicsScene::NoIndex);
692 QList<ChatLine *>::iterator lineIter = _lines.end();
693 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
694 qreal linePos = _sceneRect.y() + _sceneRect.height();
695 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
696 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
697 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
698 while (lineIter != lineIterBegin) {
700 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
702 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
706 emit layoutChanged();
708 // clock_t endT = clock();
709 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
713 void ChatScene::setHandleXLimits()
715 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
716 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
721 void ChatScene::setSelectingItem(ChatItem *item)
723 if (_selectingItem) _selectingItem->clearSelection();
724 _selectingItem = item;
728 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
730 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
731 _selectionStartCol = _selectionMinCol = item->column();
733 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
734 updateSelection(item->mapToScene(itemPos));
738 void ChatScene::updateSelection(const QPointF &pos)
740 int curRow = rowByScenePos(pos);
741 if (curRow < 0) return;
742 int curColumn = (int)columnByScenePos(pos);
743 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
744 if (minColumn != _selectionMinCol) {
745 _selectionMinCol = minColumn;
746 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
747 _lines[l]->setSelected(true, minColumn);
750 int newstart = qMin(curRow, _firstSelectionRow);
751 int newend = qMax(curRow, _firstSelectionRow);
752 if (newstart < _selectionStart) {
753 for (int l = newstart; l < _selectionStart; l++)
754 _lines[l]->setSelected(true, minColumn);
756 if (newstart > _selectionStart) {
757 for (int l = _selectionStart; l < newstart; l++)
758 _lines[l]->setSelected(false);
760 if (newend > _selectionEnd) {
761 for (int l = _selectionEnd+1; l <= newend; l++)
762 _lines[l]->setSelected(true, minColumn);
764 if (newend < _selectionEnd) {
765 for (int l = newend+1; l <= _selectionEnd; l++)
766 _lines[l]->setSelected(false);
769 _selectionStart = newstart;
770 _selectionEnd = newend;
772 if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
773 if (!_selectingItem) {
774 // _selectingItem has been removed already
777 _lines[curRow]->setSelected(false);
778 _isSelecting = false;
779 _selectionStart = -1;
780 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
785 bool ChatScene::isPosOverSelection(const QPointF &pos) const
787 ChatItem *chatItem = chatItemAt(pos);
790 if (hasGlobalSelection()) {
791 int row = chatItem->row();
792 if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
793 return columnByScenePos(pos) >= _selectionMinCol;
796 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
802 bool ChatScene::isScrollingAllowed() const
807 // TODO: Handle clicks and single-item selections too
813 /******** MOUSE HANDLING **************************************************************************/
815 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
817 QPointF pos = event->scenePos();
820 // zoom actions and similar
821 chatView()->addActionsToMenu(&menu, pos);
824 // item-specific options (select link etc)
825 ChatItem *item = chatItemAt(pos);
827 item->addActionsToMenu(&menu, item->mapFromScene(pos));
829 // no item -> default scene actions
830 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
832 // If we have text selected, insert the Copy Selection as first item
833 if (isPosOverSelection(pos)) {
834 QAction *sep = menu.insertSeparator(menu.actions().first());
835 QAction *act = new Action(QIcon::fromTheme("edit-copy"), tr("Copy Selection"), &menu, this,
836 SLOT(selectionToClipboard()), QKeySequence::Copy);
837 menu.insertAction(sep, act);
839 QString searchSelectionText = selection();
840 if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
841 searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
842 searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
844 QAction *webSearchAction = new Action(QIcon::fromTheme("edit-find"), searchSelectionText, &menu, this, SLOT(webSearchOnSelection()));
845 menu.insertAction(sep, webSearchAction);
848 if (QtUi::mainWindow()->menuBar()->isHidden())
849 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
851 // show column reset action if columns have been resized in this session or there is at least one very narrow column
852 if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
853 (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
854 menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, SLOT(resetColumnWidths()), 0));
856 menu.exec(event->screenPos());
860 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
862 if (event->buttons() == Qt::LeftButton) {
863 if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
864 if (_clickTimer.isActive())
866 if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
867 initiateDrag(event->widget());
869 _clickMode = DragStartClick;
870 handleClick(Qt::LeftButton, _clickPos);
872 _clickMode = NoClick;
875 updateSelection(event->scenePos());
876 emit mouseMoveWhileSelecting(event->scenePos());
879 else if (_clickHandled && _clickMode < DoubleClick)
880 QGraphicsScene::mouseMoveEvent(event);
883 QGraphicsScene::mouseMoveEvent(event);
887 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
889 if (event->buttons() == Qt::LeftButton) {
890 _leftButtonPressed = true;
891 _clickHandled = false;
892 if (!isPosOverSelection(event->scenePos())) {
893 // immediately clear selection if clicked outside; otherwise, wait for potential drag
896 if (_clickMode != NoClick && _clickTimer.isActive()) {
897 switch (_clickMode) {
899 _clickMode = SingleClick; break;
901 _clickMode = DoubleClick; break;
903 _clickMode = TripleClick; break;
905 _clickMode = DoubleClick; break;
909 handleClick(Qt::LeftButton, _clickPos);
912 _clickMode = SingleClick;
913 _clickPos = event->scenePos();
917 if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
918 QGraphicsScene::mouseDoubleClickEvent(event);
920 QGraphicsScene::mousePressEvent(event);
924 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
926 // we check for doubleclick ourselves, so just call press handler
927 mousePressEvent(event);
931 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
933 if (event->button() == Qt::LeftButton && _leftButtonPressed) {
934 _leftButtonPressed = false;
935 if (_clickMode != NoClick) {
936 if (_clickMode == SingleClick)
939 if (!_clickTimer.isActive())
940 handleClick(Qt::LeftButton, _clickPos);
943 // no click -> drag or selection move
944 if (isGloballySelecting()) {
945 selectionToClipboard(QClipboard::Selection);
946 _isSelecting = false;
952 QGraphicsScene::mouseReleaseEvent(event);
956 void ChatScene::clickTimeout()
958 if (!_leftButtonPressed && _clickMode == SingleClick)
959 handleClick(Qt::LeftButton, _clickPos);
963 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
965 if (button == Qt::LeftButton) {
968 // Now send click down to items
969 ChatItem *chatItem = chatItemAt(scenePos);
971 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
973 _clickHandled = true;
978 void ChatScene::initiateDrag(QWidget *source)
980 QDrag *drag = new QDrag(source);
981 QMimeData *mimeData = new QMimeData;
982 mimeData->setText(selection());
983 drag->setMimeData(mimeData);
985 drag->exec(Qt::CopyAction);
989 /******** SELECTIONS ******************************************************************************/
991 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
996 stringToClipboard(selection(), mode);
1000 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
1003 // remove trailing linefeeds
1004 if (str.endsWith('\n'))
1008 case QClipboard::Clipboard:
1009 QApplication::clipboard()->setText(str);
1011 case QClipboard::Selection:
1012 if (QApplication::clipboard()->supportsSelection())
1013 QApplication::clipboard()->setText(str, QClipboard::Selection);
1021 //!\brief Convert current selection to human-readable string.
1022 QString ChatScene::selection() const
1024 //TODO Make selection format configurable!
1025 if (hasGlobalSelection()) {
1026 int start = qMin(_selectionStart, _selectionEnd);
1027 int end = qMax(_selectionStart, _selectionEnd);
1028 if (start < 0 || end >= _lines.count()) {
1029 qDebug() << "Invalid selection range:" << start << end;
1034 for (int l = start; l <= end; l++) {
1035 if (_selectionMinCol == ChatLineModel::TimestampColumn) {
1036 ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
1037 if (!_showSenderBrackets && !_timestampHasBrackets) {
1038 // Only re-add brackets if the current timestamp format does not include them
1039 // -and- sender brackets are disabled. Don't filter on Message::Plain as
1040 // timestamp brackets affect all types of messages.
1041 // Remove any spaces before and after, otherwise it may look weird.
1042 result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
1043 .toString().trimmed());
1045 result += item->data(MessageModel::DisplayRole).toString() + " ";
1048 if (_selectionMinCol <= ChatLineModel::SenderColumn) {
1049 ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
1050 if (!_showSenderBrackets && item->chatLine()->msgType() == Message::Plain) {
1051 // Copying to plain-text. Only re-add the sender brackets if they're normally
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 MessageFilter *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 ChatLine *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 = 0;
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);
1289 // Fall through to deletion!
1290 case WebPreview::HidePreview:
1291 if (webPreview.previewItem) {
1292 delete webPreview.previewItem;
1293 webPreview.previewItem = 0;
1295 webPreview.parentItem = 0;
1296 webPreview.url = QUrl();
1297 webPreview.urlRect = QRectF();
1298 webPreview.previewState = WebPreview::NoPreview;
1300 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1304 void ChatScene::clearWebPreview(ChatItem *parentItem)
1306 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1307 switch (webPreview.previewState) {
1308 case WebPreview::NewPreview:
1309 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1311 case WebPreview::ShowPreview:
1312 if (parentItem == 0 || webPreview.parentItem == parentItem) {
1313 if (webPreview.previewItem && webPreview.previewItem->scene())
1314 removeItem(webPreview.previewItem);
1316 // fall through into to set hidden state
1317 case WebPreview::DelayPreview:
1318 // we're just loading, so haven't shown the preview yet.
1319 webPreview.previewState = WebPreview::HidePreview;
1320 webPreview.timer.start(5000);
1322 case WebPreview::NoPreview:
1323 case WebPreview::HidePreview:
1326 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1332 // ========================================
1333 // end of webkit only
1334 // ========================================
1336 // Local configuration caching
1337 void ChatScene::showWebPreviewChanged()
1339 ChatViewSettings settings;
1340 _showWebPreview = settings.showWebPreview();
1343 void ChatScene::showSenderBracketsChanged()
1345 ChatViewSettings settings;
1346 _showSenderBrackets = settings.showSenderBrackets();
1349 void ChatScene::timestampFormatStringChanged()
1351 ChatViewSettings settings;
1352 _timestampFormatString = settings.timestampFormatString();
1353 updateTimestampHasBrackets();
1356 void ChatScene::updateTimestampHasBrackets()
1358 // Calculate these parameters only as needed, rather than on-demand
1360 // Does the timestamp format contain brackets? For example:
1361 // Classic: "[hh:mm:ss]"
1362 // Modern: " hh:mm:ss"
1364 // Match groups of any opening or closing brackets - (), {}, [], <>, (>, {], etc:
1365 // ^\s*[({[<].+[)}\]>]\s*$
1366 // [...] is a character group containing ...
1367 // ^ matches start of string
1368 // \s* matches any amount of whitespace
1369 // [({[<] matches (, {, [, or <
1370 // .+ matches one or more characters
1371 // [)}\]>] matches ), }, ], or >, escaping the ]
1372 // $ matches end of string
1373 // Alternatively, if opening and closing brackets must be in pairs, use this:
1374 // (^\s*\(.+\)\s*$)|(^\s*\{.+\}\s*$)|(^\s*\[.+\]\s*$)|(^\s*<.+>\s*$)
1375 // Note that '\' must be escaped as '\\'
1376 // Helpful interactive website for debugging and explaining: https://regex101.com/
1377 const QRegExp regExpMatchBrackets("^\\s*[({[<].+[)}\\]>]\\s*$");
1378 _timestampHasBrackets = regExpMatchBrackets.exactMatch(_timestampFormatString);