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 _useCustomTimestampFormat = defaultSettings.useCustomTimestampFormat();
138 defaultSettings.notify("UseCustomTimestampFormat", this, SLOT(useCustomTimestampFormatChanged()));
140 _timestampFormatString = defaultSettings.timestampFormatString();
141 defaultSettings.notify("TimestampFormat", this, SLOT(timestampFormatStringChanged()));
142 updateTimestampHasBrackets();
144 _clickTimer.setInterval(QApplication::doubleClickInterval());
145 _clickTimer.setSingleShot(true);
146 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
148 setItemIndexMethod(QGraphicsScene::NoIndex);
152 ChatScene::~ChatScene()
157 ChatView *ChatScene::chatView() const
163 ColumnHandleItem *ChatScene::firstColumnHandle() const
165 return _firstColHandle;
169 ColumnHandleItem *ChatScene::secondColumnHandle() const
171 return _secondColHandle;
174 void ChatScene::resetColumnWidths()
176 //make sure first column is at least 80 px wide, second 120 px
177 int firstColHandlePos = qMax(_defaultFirstColHandlePos,
179 int secondColHandlePos = qMax(_defaultSecondColHandlePos,
180 firstColHandlePos + 120);
182 _firstColHandle->setXPos(firstColHandlePos);
183 _secondColHandle->setXPos(secondColHandlePos);
186 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
191 QList<ChatLine *>::ConstIterator start = _lines.begin();
192 QList<ChatLine *>::ConstIterator end = _lines.end();
193 QList<ChatLine *>::ConstIterator middle;
195 int n = int(end - start);
200 middle = start + half;
201 if ((*middle)->msgId() < msgId) {
210 if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
216 if (start == _lines.begin()) // not (yet?) in our scene
219 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
221 if (start == end) { // higher than last element
222 if (!ignoreDayChange)
223 return _lines.last();
225 for (int i = _lines.count() -1; i >= 0; i--) {
226 if (_lines.at(i)->msgType() != Message::DayChange)
232 // return the next-lower line
233 if (!ignoreDayChange)
237 if ((*(--start))->msgType() != Message::DayChange)
240 while (start != _lines.begin());
245 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
247 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
248 ChatLine *line = qgraphicsitem_cast<ChatLine *>(item);
250 return line->itemAt(line->mapFromScene(scenePos));
256 bool ChatScene::containsBuffer(const BufferId &id) const
258 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
260 return filter->containsBuffer(id);
266 void ChatScene::setMarkerLineVisible(bool visible)
268 _markerLineVisible = visible;
269 if (visible && _markerLineValid)
270 markerLine()->setVisible(true);
272 markerLine()->setVisible(false);
276 void ChatScene::setMarkerLine(MsgId msgId)
278 if (!isSingleBufferScene())
281 if (!msgId.isValid())
282 msgId = Client::markerLine(singleBufferId());
284 if (msgId.isValid()) {
285 ChatLine *line = chatLine(msgId, false, true);
287 markerLine()->setChatLine(line);
288 // if this was the last line, we won't see it because it's outside the sceneRect
289 // .. which is exactly what we want :)
290 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
292 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
293 if (markerLine()->pos().y() >= sceneRect().y()) {
294 _markerLineValid = true;
295 if (_markerLineVisible)
296 markerLine()->setVisible(true);
297 if (_markerLineJumpPending) {
298 _markerLineJumpPending = false;
299 if (markerLine()->isVisible()) {
300 markerLine()->ensureVisible(QRectF(), 50, 50);
307 _markerLineValid = false;
308 markerLine()->setVisible(false);
312 void ChatScene::jumpToMarkerLine(bool requestBacklog)
314 if (!isSingleBufferScene())
317 if (markerLine()->isVisible()) {
318 markerLine()->ensureVisible(QRectF(), 50, 50);
321 if (!_markerLineValid && requestBacklog) {
322 MsgId msgId = Client::markerLine(singleBufferId());
323 if (msgId.isValid()) {
324 _markerLineJumpPending = true;
325 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
327 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
328 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
329 // jump tries will eventually cause enough backlog to be fetched.
330 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
331 this->requestBacklog();
337 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
341 // QModelIndex sidx = model()->index(start, 2);
342 // QModelIndex eidx = model()->index(end, 2);
343 // qDebug() << "rowsInserted:";
345 // QModelIndex ssidx = model()->index(start - 1, 2);
346 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
347 // << ssidx.data(Qt::DisplayRole).toString();
349 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
350 // << sidx.data(Qt::DisplayRole).toString();
351 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
352 // << eidx.data(Qt::DisplayRole).toString();
353 // if(end + 1 < model()->rowCount()) {
354 // QModelIndex eeidx = model()->index(end + 1, 2);
355 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
356 // << eeidx.data(Qt::DisplayRole).toString();
361 qreal width = _sceneRect.width();
362 bool atBottom = (start == _lines.count());
363 bool atTop = !atBottom && (start == 0);
365 if (start < _lines.count()) {
366 y = _lines.value(start)->y();
368 else if (atBottom && !_lines.isEmpty()) {
369 y = _lines.last()->y() + _lines.last()->height();
372 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
373 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
374 qreal timestampWidth = firstColumnHandle()->sceneLeft();
375 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
376 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
379 for (int i = end; i >= start; i--) {
380 ChatLine *line = new ChatLine(i, model(),
382 timestampWidth, senderWidth, contentsWidth,
383 senderPos, contentsPos);
385 line->setPos(0, y-h);
386 _lines.insert(start, line);
391 for (int i = start; i <= end; i++) {
392 ChatLine *line = new ChatLine(i, model(),
394 timestampWidth, senderWidth, contentsWidth,
395 senderPos, contentsPos);
396 line->setPos(0, y+h);
398 _lines.insert(i, line);
403 // update existing items
404 for (int i = end+1; i < _lines.count(); i++) {
405 _lines[i]->setRow(i);
409 if (_selectionStart >= 0) {
410 int offset = end - start + 1;
411 int oldStart = _selectionStart;
412 if (_selectionStart >= start)
413 _selectionStart += offset;
414 if (_selectionEnd >= start) {
415 _selectionEnd += offset;
416 if (_selectionStart == oldStart)
417 for (int i = start; i < start + offset; i++)
418 _lines[i]->setSelected(true);
420 if (_firstSelectionRow >= start)
421 _firstSelectionRow += offset;
424 // neither pre- or append means we have to do dirty work: move items...
425 if (!(atTop || atBottom)) {
427 for (int i = 0; i <= end; i++) {
429 line->setPos(0, line->pos().y() - h);
430 if (line == markerLine()->chatLine())
431 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
435 // check if all went right
436 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
438 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
439 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
440 // 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();
441 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
442 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
446 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
447 // if(end + 1 < _lines.count()) {
448 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
449 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
450 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
451 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
452 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
458 if (start < _firstLineRow) {
459 int prevFirstLineRow = _firstLineRow + (end - start + 1);
460 for (int i = end + 1; i < prevFirstLineRow; i++) {
461 _lines.at(i)->show();
464 // force new search for first proper line
469 emit lastLineChanged(_lines.last(), h);
472 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
473 if (!_markerLineValid)
478 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
482 qreal h = 0; // total height of removed items;
484 bool atTop = (start == 0);
485 bool atBottom = (end == _lines.count() - 1);
488 if (_selectingItem) {
489 int row = _selectingItem->row();
490 if (row >= start && row <= end)
494 // remove items from scene
495 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
496 int lineCount = start;
497 while (lineIter != _lines.end() && lineCount <= end) {
498 if ((*lineIter) == markerLine()->chatLine())
499 markerLine()->setChatLine(0);
500 h += (*lineIter)->height();
502 lineIter = _lines.erase(lineIter);
506 // update rows of remaining chatlines
507 for (int i = start; i < _lines.count(); i++) {
508 _lines.at(i)->setRow(i);
512 if (_selectionStart >= 0) {
513 int offset = end - start + 1;
514 if (_selectionStart >= start)
515 _selectionStart = qMax(_selectionStart - offset, start);
516 if (_selectionEnd >= start)
517 _selectionEnd -= offset;
518 if (_firstSelectionRow >= start)
519 _firstSelectionRow -= offset;
521 if (_selectionEnd < _selectionStart) {
522 _isSelecting = false;
523 _selectionStart = -1;
527 // neither removing at bottom or top means we have to move items...
528 if (!(atTop || atBottom)) {
531 int moveEnd = _lines.count() - 1;
532 if (start < _lines.count() - start) {
542 for (int i = moveStart; i <= moveEnd; i++) {
544 line->setPos(0, line->pos().y() + offset);
548 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
551 // when searching for the first non-date-line we have to take into account that our
552 // model still contains the just removed lines so we cannot simply call updateSceneRect()
553 int numRows = model()->rowCount();
554 QModelIndex firstLineIdx;
556 bool needOffset = false;
559 if (_firstLineRow >= start && _firstLineRow <= end) {
560 _firstLineRow = end + 1;
563 firstLineIdx = model()->index(_firstLineRow, 0);
565 while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
568 _firstLineRow -= end - start + 1;
573 void ChatScene::rowsRemoved()
575 // move the marker line if necessary
580 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
582 layout(tl.row(), br.row(), _sceneRect.width());
586 void ChatScene::updateForViewport(qreal width, qreal height)
588 _viewportHeight = height;
593 void ChatScene::setWidth(qreal width)
595 if (width == _sceneRect.width())
597 layout(0, _lines.count()-1, width);
601 void ChatScene::layout(int start, int end, qreal width)
603 // clock_t startT = clock();
605 // disabling the index while doing this complex updates is about
606 // 2 to 10 times faster!
607 //setItemIndexMethod(QGraphicsScene::NoIndex);
611 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
612 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
613 while (row >= start) {
614 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
618 // remaining items don't need geometry changes, but maybe repositioning?
619 ChatLine *line = _lines.at(row);
620 qreal offset = linePos - (line->scenePos().y() + line->height());
623 line = _lines.at(row--);
624 line->setPos(0, line->scenePos().y() + offset);
630 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
632 updateSceneRect(width);
635 emit layoutChanged();
637 // clock_t endT = clock();
638 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
642 void ChatScene::firstHandlePositionChanged(qreal xpos)
644 if (_firstColHandlePos == xpos)
647 _firstColHandlePos = xpos >= 0 ? xpos : 0;
648 ChatViewSettings viewSettings(this);
649 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
650 ChatViewSettings defaultSettings;
651 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
653 // clock_t startT = clock();
655 // disabling the index while doing this complex updates is about
656 // 2 to 10 times faster!
657 //setItemIndexMethod(QGraphicsScene::NoIndex);
659 QList<ChatLine *>::iterator lineIter = _lines.end();
660 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
661 qreal timestampWidth = firstColumnHandle()->sceneLeft();
662 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
663 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
665 while (lineIter != lineIterBegin) {
667 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
669 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
673 // clock_t endT = clock();
674 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
678 void ChatScene::secondHandlePositionChanged(qreal xpos)
680 if (_secondColHandlePos == xpos)
683 _secondColHandlePos = xpos;
684 ChatViewSettings viewSettings(this);
685 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
686 ChatViewSettings defaultSettings;
687 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
689 // clock_t startT = clock();
691 // disabling the index while doing this complex updates is about
692 // 2 to 10 times faster!
693 //setItemIndexMethod(QGraphicsScene::NoIndex);
695 QList<ChatLine *>::iterator lineIter = _lines.end();
696 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
697 qreal linePos = _sceneRect.y() + _sceneRect.height();
698 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
699 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
700 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
701 while (lineIter != lineIterBegin) {
703 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
705 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
709 emit layoutChanged();
711 // clock_t endT = clock();
712 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
716 void ChatScene::setHandleXLimits()
718 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
719 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
724 void ChatScene::setSelectingItem(ChatItem *item)
726 if (_selectingItem) _selectingItem->clearSelection();
727 _selectingItem = item;
731 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
733 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
734 _selectionStartCol = _selectionMinCol = item->column();
736 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
737 updateSelection(item->mapToScene(itemPos));
741 void ChatScene::updateSelection(const QPointF &pos)
743 int curRow = rowByScenePos(pos);
744 if (curRow < 0) return;
745 int curColumn = (int)columnByScenePos(pos);
746 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
747 if (minColumn != _selectionMinCol) {
748 _selectionMinCol = minColumn;
749 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
750 _lines[l]->setSelected(true, minColumn);
753 int newstart = qMin(curRow, _firstSelectionRow);
754 int newend = qMax(curRow, _firstSelectionRow);
755 if (newstart < _selectionStart) {
756 for (int l = newstart; l < _selectionStart; l++)
757 _lines[l]->setSelected(true, minColumn);
759 if (newstart > _selectionStart) {
760 for (int l = _selectionStart; l < newstart; l++)
761 _lines[l]->setSelected(false);
763 if (newend > _selectionEnd) {
764 for (int l = _selectionEnd+1; l <= newend; l++)
765 _lines[l]->setSelected(true, minColumn);
767 if (newend < _selectionEnd) {
768 for (int l = newend+1; l <= _selectionEnd; l++)
769 _lines[l]->setSelected(false);
772 _selectionStart = newstart;
773 _selectionEnd = newend;
775 if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
776 if (!_selectingItem) {
777 // _selectingItem has been removed already
780 _lines[curRow]->setSelected(false);
781 _isSelecting = false;
782 _selectionStart = -1;
783 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
788 bool ChatScene::isPosOverSelection(const QPointF &pos) const
790 ChatItem *chatItem = chatItemAt(pos);
793 if (hasGlobalSelection()) {
794 int row = chatItem->row();
795 if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
796 return columnByScenePos(pos) >= _selectionMinCol;
799 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
805 bool ChatScene::isScrollingAllowed() const
810 // TODO: Handle clicks and single-item selections too
816 /******** MOUSE HANDLING **************************************************************************/
818 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
820 QPointF pos = event->scenePos();
823 // zoom actions and similar
824 chatView()->addActionsToMenu(&menu, pos);
827 // item-specific options (select link etc)
828 ChatItem *item = chatItemAt(pos);
830 item->addActionsToMenu(&menu, item->mapFromScene(pos));
832 // no item -> default scene actions
833 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
835 // If we have text selected, insert the Copy Selection as first item
836 if (isPosOverSelection(pos)) {
837 QAction *sep = menu.insertSeparator(menu.actions().first());
838 QAction *act = new Action(QIcon::fromTheme("edit-copy"), tr("Copy Selection"), &menu, this,
839 SLOT(selectionToClipboard()), QKeySequence::Copy);
840 menu.insertAction(sep, act);
842 QString searchSelectionText = selection();
843 if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
844 searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
845 searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
847 QAction *webSearchAction = new Action(QIcon::fromTheme("edit-find"), searchSelectionText, &menu, this, SLOT(webSearchOnSelection()));
848 menu.insertAction(sep, webSearchAction);
851 if (QtUi::mainWindow()->menuBar()->isHidden())
852 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
854 // show column reset action if columns have been resized in this session or there is at least one very narrow column
855 if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
856 (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
857 menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, SLOT(resetColumnWidths()), 0));
859 menu.exec(event->screenPos());
863 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
865 if (event->buttons() == Qt::LeftButton) {
866 if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
867 if (_clickTimer.isActive())
869 if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
870 initiateDrag(event->widget());
872 _clickMode = DragStartClick;
873 handleClick(Qt::LeftButton, _clickPos);
875 _clickMode = NoClick;
878 updateSelection(event->scenePos());
879 emit mouseMoveWhileSelecting(event->scenePos());
882 else if (_clickHandled && _clickMode < DoubleClick)
883 QGraphicsScene::mouseMoveEvent(event);
886 QGraphicsScene::mouseMoveEvent(event);
890 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
892 if (event->buttons() == Qt::LeftButton) {
893 _leftButtonPressed = true;
894 _clickHandled = false;
895 if (!isPosOverSelection(event->scenePos())) {
896 // immediately clear selection if clicked outside; otherwise, wait for potential drag
899 if (_clickMode != NoClick && _clickTimer.isActive()) {
900 switch (_clickMode) {
902 _clickMode = SingleClick; break;
904 _clickMode = DoubleClick; break;
906 _clickMode = TripleClick; break;
908 _clickMode = DoubleClick; break;
912 handleClick(Qt::LeftButton, _clickPos);
915 _clickMode = SingleClick;
916 _clickPos = event->scenePos();
920 if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
921 QGraphicsScene::mouseDoubleClickEvent(event);
923 QGraphicsScene::mousePressEvent(event);
927 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
929 // we check for doubleclick ourselves, so just call press handler
930 mousePressEvent(event);
934 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
936 if (event->button() == Qt::LeftButton && _leftButtonPressed) {
937 _leftButtonPressed = false;
938 if (_clickMode != NoClick) {
939 if (_clickMode == SingleClick)
942 if (!_clickTimer.isActive())
943 handleClick(Qt::LeftButton, _clickPos);
946 // no click -> drag or selection move
947 if (isGloballySelecting()) {
948 selectionToClipboard(QClipboard::Selection);
949 _isSelecting = false;
955 QGraphicsScene::mouseReleaseEvent(event);
959 void ChatScene::clickTimeout()
961 if (!_leftButtonPressed && _clickMode == SingleClick)
962 handleClick(Qt::LeftButton, _clickPos);
966 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
968 if (button == Qt::LeftButton) {
971 // Now send click down to items
972 ChatItem *chatItem = chatItemAt(scenePos);
974 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
976 _clickHandled = true;
981 void ChatScene::initiateDrag(QWidget *source)
983 QDrag *drag = new QDrag(source);
984 QMimeData *mimeData = new QMimeData;
985 mimeData->setText(selection());
986 drag->setMimeData(mimeData);
988 drag->exec(Qt::CopyAction);
992 /******** SELECTIONS ******************************************************************************/
994 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
999 stringToClipboard(selection(), mode);
1003 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
1006 // remove trailing linefeeds
1007 if (str.endsWith('\n'))
1011 case QClipboard::Clipboard:
1012 QApplication::clipboard()->setText(str);
1014 case QClipboard::Selection:
1015 if (QApplication::clipboard()->supportsSelection())
1016 QApplication::clipboard()->setText(str, QClipboard::Selection);
1024 //!\brief Convert current selection to human-readable string.
1025 QString ChatScene::selection() const
1027 //TODO Make selection format configurable!
1028 if (hasGlobalSelection()) {
1029 int start = qMin(_selectionStart, _selectionEnd);
1030 int end = qMax(_selectionStart, _selectionEnd);
1031 if (start < 0 || end >= _lines.count()) {
1032 qDebug() << "Invalid selection range:" << start << end;
1037 for (int l = start; l <= end; l++) {
1038 if (_selectionMinCol == ChatLineModel::TimestampColumn) {
1039 ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
1040 if (!_showSenderBrackets && !_timestampHasBrackets) {
1041 // Only re-add brackets if the current timestamp format does not include them
1042 // -and- sender brackets are disabled. Don't filter on Message::Plain as
1043 // timestamp brackets affect all types of messages.
1044 // Remove any spaces before and after, otherwise it may look weird.
1045 result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
1046 .toString().trimmed());
1048 result += item->data(MessageModel::DisplayRole).toString() + " ";
1051 if (_selectionMinCol <= ChatLineModel::SenderColumn) {
1052 ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
1053 if (!_showSenderBrackets && item->chatLine()->msgType() == Message::Plain) {
1054 // Copying to plain-text. Only re-add the sender brackets if they're normally
1056 result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
1059 result += item->data(MessageModel::DisplayRole).toString() + " ";
1062 result += _lines[l]->item(ChatLineModel::ContentsColumn)
1063 ->data(MessageModel::DisplayRole).toString() + "\n";
1067 else if (selectingItem())
1068 return selectingItem()->selection();
1073 bool ChatScene::hasSelection() const
1075 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1079 bool ChatScene::hasGlobalSelection() const
1081 return _selectionStart >= 0;
1085 bool ChatScene::isGloballySelecting() const
1087 return _isSelecting;
1091 void ChatScene::clearGlobalSelection()
1093 if (hasGlobalSelection()) {
1094 for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
1095 _lines[l]->setSelected(false);
1096 _isSelecting = false;
1097 _selectionStart = -1;
1102 void ChatScene::clearSelection()
1104 clearGlobalSelection();
1105 if (selectingItem())
1106 selectingItem()->clearSelection();
1110 /******** *************************************************************************************/
1112 void ChatScene::webSearchOnSelection()
1114 if (!hasSelection())
1117 ChatViewSettings settings;
1118 QString webSearchBaseUrl = settings.webSearchUrlFormatString();
1119 QString webSearchUrl = webSearchBaseUrl.replace(QString("%s"), selection());
1120 QUrl url = QUrl::fromUserInput(webSearchUrl);
1121 QDesktopServices::openUrl(url);
1125 /******** *************************************************************************************/
1127 void ChatScene::requestBacklog()
1129 MessageFilter *filter = qobject_cast<MessageFilter *>(model());
1131 return filter->requestBacklog();
1136 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1138 if (x < _firstColHandle->x())
1139 return ChatLineModel::TimestampColumn;
1140 if (x < _secondColHandle->x())
1141 return ChatLineModel::SenderColumn;
1143 return ChatLineModel::ContentsColumn;
1147 int ChatScene::rowByScenePos(qreal y) const
1149 QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1151 // ChatLine should be at the bottom of the list
1152 for (int i = itemList.count()-1; i >= 0; i--) {
1153 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
1161 void ChatScene::updateSceneRect(qreal width)
1163 if (_lines.isEmpty()) {
1164 updateSceneRect(QRectF(0, 0, width, 0));
1168 // we hide day change messages at the top by making the scene rect smaller
1169 // and by calling QGraphicsItem::hide() on all leading day change messages
1170 // the first one is needed to ensure proper scrollbar ranges
1171 // the second for cases where the viewport is larger then the set scenerect
1172 // (in this case the items are shown anyways)
1173 if (_firstLineRow == -1) {
1174 int numRows = model()->rowCount();
1176 QModelIndex firstLineIdx;
1177 while (_firstLineRow < numRows) {
1178 firstLineIdx = model()->index(_firstLineRow, 0);
1179 if ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
1181 _lines.at(_firstLineRow)->hide();
1186 // the following call should be safe. If it crashes something went wrong during insert/remove
1187 if (_firstLineRow < _lines.count()) {
1188 ChatLine *firstLine = _lines.at(_firstLineRow);
1189 ChatLine *lastLine = _lines.last();
1190 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1194 updateSceneRect(QRectF(0, 0, width, 0));
1199 void ChatScene::updateSceneRect(const QRectF &rect)
1207 // ========================================
1208 // Webkit/WebEngine Only stuff
1209 // ========================================
1210 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
1211 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
1213 if (!_showWebPreview)
1216 if (webPreview.urlRect != urlRect)
1217 webPreview.urlRect = urlRect;
1219 if (webPreview.parentItem != parentItem)
1220 webPreview.parentItem = parentItem;
1222 if (webPreview.url != url) {
1223 webPreview.url = url;
1224 // prepare to load a different URL
1225 if (webPreview.previewItem) {
1226 if (webPreview.previewItem->scene())
1227 removeItem(webPreview.previewItem);
1228 delete webPreview.previewItem;
1229 webPreview.previewItem = 0;
1231 webPreview.previewState = WebPreview::NoPreview;
1234 if (webPreview.url.isEmpty())
1237 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1238 switch (webPreview.previewState) {
1239 case WebPreview::NoPreview:
1240 webPreview.previewState = WebPreview::NewPreview;
1241 webPreview.timer.start(500);
1243 case WebPreview::NewPreview:
1244 case WebPreview::DelayPreview:
1245 case WebPreview::ShowPreview:
1246 // we're already waiting for the next step or showing the preview
1248 case WebPreview::HidePreview:
1249 // we still have a valid preview
1250 webPreview.previewState = WebPreview::DelayPreview;
1251 webPreview.timer.start(1000);
1254 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1258 void ChatScene::webPreviewNextStep()
1260 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1261 switch (webPreview.previewState) {
1262 case WebPreview::NoPreview:
1264 case WebPreview::NewPreview:
1265 Q_ASSERT(!webPreview.previewItem);
1266 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1267 webPreview.previewState = WebPreview::DelayPreview;
1268 webPreview.timer.start(1000);
1270 case WebPreview::DelayPreview:
1271 Q_ASSERT(webPreview.previewItem);
1272 // calc position and show
1274 qreal previewY = webPreview.urlRect.bottom();
1275 qreal previewX = webPreview.urlRect.x();
1276 if (previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1277 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1279 if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1280 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1282 webPreview.previewItem->setPos(previewX, previewY);
1284 addItem(webPreview.previewItem);
1285 webPreview.previewState = WebPreview::ShowPreview;
1287 case WebPreview::ShowPreview:
1288 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1289 qWarning() << "removing preview";
1290 if (webPreview.previewItem && webPreview.previewItem->scene())
1291 removeItem(webPreview.previewItem);
1292 // Fall through to deletion!
1294 case WebPreview::HidePreview:
1295 if (webPreview.previewItem) {
1296 delete webPreview.previewItem;
1297 webPreview.previewItem = 0;
1299 webPreview.parentItem = 0;
1300 webPreview.url = QUrl();
1301 webPreview.urlRect = QRectF();
1302 webPreview.previewState = WebPreview::NoPreview;
1304 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1308 void ChatScene::clearWebPreview(ChatItem *parentItem)
1310 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1311 switch (webPreview.previewState) {
1312 case WebPreview::NewPreview:
1313 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1315 case WebPreview::ShowPreview:
1316 if (parentItem == 0 || webPreview.parentItem == parentItem) {
1317 if (webPreview.previewItem && webPreview.previewItem->scene())
1318 removeItem(webPreview.previewItem);
1320 // fall through into to set hidden state
1322 case WebPreview::DelayPreview:
1323 // we're just loading, so haven't shown the preview yet.
1324 webPreview.previewState = WebPreview::HidePreview;
1325 webPreview.timer.start(5000);
1327 case WebPreview::NoPreview:
1328 case WebPreview::HidePreview:
1331 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1337 // ========================================
1338 // end of webkit only
1339 // ========================================
1341 // Local configuration caching
1342 void ChatScene::showWebPreviewChanged()
1344 ChatViewSettings settings;
1345 _showWebPreview = settings.showWebPreview();
1348 void ChatScene::showSenderBracketsChanged()
1350 ChatViewSettings settings;
1351 _showSenderBrackets = settings.showSenderBrackets();
1354 void ChatScene::useCustomTimestampFormatChanged()
1356 ChatViewSettings settings;
1357 _useCustomTimestampFormat = settings.useCustomTimestampFormat();
1358 updateTimestampHasBrackets();
1361 void ChatScene::timestampFormatStringChanged()
1363 ChatViewSettings settings;
1364 _timestampFormatString = settings.timestampFormatString();
1365 updateTimestampHasBrackets();
1368 void ChatScene::updateTimestampHasBrackets()
1370 // Calculate these parameters only as needed, rather than on-demand
1372 if (!_useCustomTimestampFormat) {
1373 // The default timestamp format string does not have brackets, no need to check.
1374 // If UiStyle::updateSystemTimestampFormat() has brackets added, change this, too.
1375 _timestampHasBrackets = false;
1377 // Does the timestamp format contain brackets? For example:
1378 // Classic: "[hh:mm:ss]"
1379 // Modern: " hh:mm:ss"
1381 // Match groups of any opening or closing brackets - (), {}, [], <>, (>, {], etc:
1382 // ^\s*[({[<].+[)}\]>]\s*$
1383 // [...] is a character group containing ...
1384 // ^ matches start of string
1385 // \s* matches any amount of whitespace
1386 // [({[<] matches (, {, [, or <
1387 // .+ matches one or more characters
1388 // [)}\]>] matches ), }, ], or >, escaping the ]
1389 // $ matches end of string
1390 // Alternatively, if opening and closing brackets must be in pairs, use this:
1391 // (^\s*\(.+\)\s*$)|(^\s*\{.+\}\s*$)|(^\s*\[.+\]\s*$)|(^\s*<.+>\s*$)
1392 // Note that '\' must be escaped as '\\'
1393 // Helpful interactive website for debugging and explaining: https://regex101.com/
1394 const QRegExp regExpMatchBrackets("^\\s*[({[<].+[)}\\]>]\\s*$");
1395 _timestampHasBrackets = regExpMatchBrackets.exactMatch(_timestampFormatString);