Make the UI actually emit the required signal
[quassel.git] / src / qtui / chatscene.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include <QApplication>
22 #include <QClipboard>
23 #include <QDesktopServices>
24 #include <QDrag>
25 #include <QGraphicsSceneMouseEvent>
26 #include <QIcon>
27 #include <QMenu>
28 #include <QMenuBar>
29 #include <QMimeData>
30 #include <QPersistentModelIndex>
31 #include <QUrl>
32
33 #ifdef HAVE_KDE4
34 #  include <KMenuBar>
35 #else
36 #  include <QMenuBar>
37 #endif
38
39 #ifdef HAVE_WEBENGINE
40 #  include <QWebEngineView>
41 #elif defined HAVE_WEBKIT
42 #  include <QWebView>
43 #endif
44
45 #include "chatitem.h"
46 #include "chatline.h"
47 #include "chatlinemodelitem.h"
48 #include "chatscene.h"
49 #include "chatview.h"
50 #include "client.h"
51 #include "clientbacklogmanager.h"
52 #include "columnhandleitem.h"
53 #include "contextmenuactionprovider.h"
54 #include "mainwin.h"
55 #include "markerlineitem.h"
56 #include "messagefilter.h"
57 #include "qtui.h"
58 #include "qtuistyle.h"
59 #include "chatviewsettings.h"
60 #include "webpreviewitem.h"
61
62 const qreal minContentsWidth = 200;
63
64 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
65     : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
66     _chatView(parent),
67     _idString(idString),
68     _model(model),
69     _singleBufferId(BufferId()),
70     _sceneRect(0, 0, width, 0),
71     _firstLineRow(-1),
72     _viewportHeight(0),
73     _markerLine(new MarkerLineItem(width)),
74     _markerLineVisible(false),
75     _markerLineValid(false),
76     _markerLineJumpPending(false),
77     _cutoffMode(CutoffRight),
78     _selectingItem(0),
79     _selectionStart(-1),
80     _isSelecting(false),
81     _clickMode(NoClick),
82     _clickHandled(true),
83     _leftButtonPressed(false)
84 {
85     MessageFilter *filter = qobject_cast<MessageFilter *>(model);
86     if (filter && filter->isSingleBufferFilter()) {
87         _singleBufferId = filter->singleBufferId();
88     }
89
90     addItem(_markerLine);
91     connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
92
93     ChatViewSettings defaultSettings;
94     _defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
95     _defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
96
97     ChatViewSettings viewSettings(this);
98     _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", _defaultFirstColHandlePos).toInt();
99     _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", _defaultSecondColHandlePos).toInt();
100
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 &)));
106
107     _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
108     addItem(_secondColHandle);
109     _secondColHandle->setXPos(_secondColHandlePos);
110     connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
111
112     connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
113
114     setHandleXLimits();
115
116     if (model->rowCount() > 0)
117         rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
118
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)));
126
127 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
128     webPreview.timer.setSingleShot(true);
129     connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
130 #endif
131     _showWebPreview = defaultSettings.showWebPreview();
132     defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
133
134     _showSenderBrackets = defaultSettings.showSenderBrackets();
135     defaultSettings.notify("ShowSenderBrackets", this, SLOT(showSenderBracketsChanged()));
136
137     _useCustomTimestampFormat = defaultSettings.useCustomTimestampFormat();
138     defaultSettings.notify("UseCustomTimestampFormat", this, SLOT(useCustomTimestampFormatChanged()));
139
140     _timestampFormatString = defaultSettings.timestampFormatString();
141     defaultSettings.notify("TimestampFormat", this, SLOT(timestampFormatStringChanged()));
142     updateTimestampHasBrackets();
143
144     _clickTimer.setInterval(QApplication::doubleClickInterval());
145     _clickTimer.setSingleShot(true);
146     connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
147
148     setItemIndexMethod(QGraphicsScene::NoIndex);
149 }
150
151
152 ChatScene::~ChatScene()
153 {
154 }
155
156
157 ChatView *ChatScene::chatView() const
158 {
159     return _chatView;
160 }
161
162
163 ColumnHandleItem *ChatScene::firstColumnHandle() const
164 {
165     return _firstColHandle;
166 }
167
168
169 ColumnHandleItem *ChatScene::secondColumnHandle() const
170 {
171     return _secondColHandle;
172 }
173
174 void ChatScene::resetColumnWidths()
175 {
176     //make sure first column is at least 80 px wide, second 120 px
177     int firstColHandlePos = qMax(_defaultFirstColHandlePos,
178                                  80);
179     int secondColHandlePos = qMax(_defaultSecondColHandlePos,
180                                   firstColHandlePos + 120);
181
182     _firstColHandle->setXPos(firstColHandlePos);
183     _secondColHandle->setXPos(secondColHandlePos);
184 }
185
186 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
187 {
188     if (!_lines.count())
189         return 0;
190
191     QList<ChatLine *>::ConstIterator start = _lines.begin();
192     QList<ChatLine *>::ConstIterator end = _lines.end();
193     QList<ChatLine *>::ConstIterator middle;
194
195     int n = int(end - start);
196     int half;
197
198     while (n > 0) {
199         half = n >> 1;
200         middle = start + half;
201         if ((*middle)->msgId() < msgId) {
202             start = middle + 1;
203             n -= half + 1;
204         }
205         else {
206             n = half;
207         }
208     }
209
210     if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
211         return *start;
212
213     if (matchExact)
214         return 0;
215
216     if (start == _lines.begin()) // not (yet?) in our scene
217         return 0;
218
219     // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
220
221     if (start == end) { // higher than last element
222         if (!ignoreDayChange)
223             return _lines.last();
224
225         for (int i = _lines.count() -1; i >= 0; i--) {
226             if (_lines.at(i)->msgType() != Message::DayChange)
227                 return _lines.at(i);
228         }
229         return 0;
230     }
231
232     // return the next-lower line
233     if (!ignoreDayChange)
234         return *(--start);
235
236     do {
237         if ((*(--start))->msgType() != Message::DayChange)
238             return *start;
239     }
240     while (start != _lines.begin());
241     return 0;
242 }
243
244
245 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
246 {
247     foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
248         ChatLine *line = qgraphicsitem_cast<ChatLine *>(item);
249         if (line)
250             return line->itemAt(line->mapFromScene(scenePos));
251     }
252     return 0;
253 }
254
255
256 bool ChatScene::containsBuffer(const BufferId &id) const
257 {
258     MessageFilter *filter = qobject_cast<MessageFilter *>(model());
259     if (filter)
260         return filter->containsBuffer(id);
261     else
262         return false;
263 }
264
265
266 void ChatScene::setMarkerLineVisible(bool visible)
267 {
268     _markerLineVisible = visible;
269     if (visible && _markerLineValid)
270         markerLine()->setVisible(true);
271     else
272         markerLine()->setVisible(false);
273 }
274
275
276 void ChatScene::setMarkerLine(MsgId msgId)
277 {
278     if (!isSingleBufferScene())
279         return;
280
281     if (!msgId.isValid())
282         msgId = Client::markerLine(singleBufferId());
283
284     if (msgId.isValid()) {
285         ChatLine *line = chatLine(msgId, false, true);
286         if (line) {
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()));
291
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);
301                     }
302                 }
303                 return;
304             }
305         }
306     }
307     _markerLineValid = false;
308     markerLine()->setVisible(false);
309 }
310
311
312 void ChatScene::jumpToMarkerLine(bool requestBacklog)
313 {
314     if (!isSingleBufferScene())
315         return;
316
317     if (markerLine()->isVisible()) {
318         markerLine()->ensureVisible(QRectF(), 50, 50);
319         return;
320     }
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);
326
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();
332         }
333     }
334 }
335
336
337 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
338 {
339     Q_UNUSED(index);
340
341 //   QModelIndex sidx = model()->index(start, 2);
342 //   QModelIndex eidx = model()->index(end, 2);
343 //   qDebug() << "rowsInserted:";
344 //   if(start > 0) {
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();
348 //   }
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();
357 //   }
358
359     qreal h = 0;
360     qreal y = 0;
361     qreal width = _sceneRect.width();
362     bool atBottom = (start == _lines.count());
363     bool atTop = !atBottom && (start == 0);
364
365     if (start < _lines.count()) {
366         y = _lines.value(start)->y();
367     }
368     else if (atBottom && !_lines.isEmpty()) {
369         y = _lines.last()->y() + _lines.last()->height();
370     }
371
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);
377
378     if (atTop) {
379         for (int i = end; i >= start; i--) {
380             ChatLine *line = new ChatLine(i, model(),
381                 width,
382                 timestampWidth, senderWidth, contentsWidth,
383                 senderPos, contentsPos);
384             h += line->height();
385             line->setPos(0, y-h);
386             _lines.insert(start, line);
387             addItem(line);
388         }
389     }
390     else {
391         for (int i = start; i <= end; i++) {
392             ChatLine *line = new ChatLine(i, model(),
393                 width,
394                 timestampWidth, senderWidth, contentsWidth,
395                 senderPos, contentsPos);
396             line->setPos(0, y+h);
397             h += line->height();
398             _lines.insert(i, line);
399             addItem(line);
400         }
401     }
402
403     // update existing items
404     for (int i = end+1; i < _lines.count(); i++) {
405         _lines[i]->setRow(i);
406     }
407
408     // update selection
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);
419         }
420         if (_firstSelectionRow >= start)
421             _firstSelectionRow += offset;
422     }
423
424     // neither pre- or append means we have to do dirty work: move items...
425     if (!(atTop || atBottom)) {
426         ChatLine *line = 0;
427         for (int i = 0; i <= end; i++) {
428             line = _lines.at(i);
429             line->setPos(0, line->pos().y() - h);
430             if (line == markerLine()->chatLine())
431                 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
432         }
433     }
434
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());
437 //   if(start != 0) {
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;
443 //       Q_ASSERT(false)
444 //     }
445 //   }
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;
453 //       Q_ASSERT(false);
454 //     }
455 //   }
456
457     if (!atBottom) {
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();
462             }
463         }
464         // force new search for first proper line
465         _firstLineRow = -1;
466     }
467     updateSceneRect();
468     if (atBottom) {
469         emit lastLineChanged(_lines.last(), h);
470     }
471
472     // now move the marker line if necessary. we don't need to do anything if we appended lines though...
473     if (!_markerLineValid)
474         setMarkerLine();
475 }
476
477
478 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
479 {
480     Q_UNUSED(parent);
481
482     qreal h = 0; // total height of removed items;
483
484     bool atTop = (start == 0);
485     bool atBottom = (end == _lines.count() - 1);
486
487     // clear selection
488     if (_selectingItem) {
489         int row = _selectingItem->row();
490         if (row >= start && row <= end)
491             setSelectingItem(0);
492     }
493
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();
501         delete *lineIter;
502         lineIter = _lines.erase(lineIter);
503         lineCount++;
504     }
505
506     // update rows of remaining chatlines
507     for (int i = start; i < _lines.count(); i++) {
508         _lines.at(i)->setRow(i);
509     }
510
511     // update selection
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;
520
521         if (_selectionEnd < _selectionStart) {
522             _isSelecting = false;
523             _selectionStart = -1;
524         }
525     }
526
527     // neither removing at bottom or top means we have to move items...
528     if (!(atTop || atBottom)) {
529         qreal offset = h;
530         int moveStart = 0;
531         int moveEnd = _lines.count() - 1;
532         if (start < _lines.count() - start) {
533             // move top part
534             moveEnd = start - 1;
535         }
536         else {
537             // move bottom part
538             moveStart = start;
539             offset = -offset;
540         }
541         ChatLine *line = 0;
542         for (int i = moveStart; i <= moveEnd; i++) {
543             line = _lines.at(i);
544             line->setPos(0, line->pos().y() + offset);
545         }
546     }
547
548     Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
549
550     // update sceneRect
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;
555     _firstLineRow = -1;
556     bool needOffset = false;
557     do {
558         _firstLineRow++;
559         if (_firstLineRow >= start && _firstLineRow <= end) {
560             _firstLineRow = end + 1;
561             needOffset = true;
562         }
563         firstLineIdx = model()->index(_firstLineRow, 0);
564     }
565     while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
566
567     if (needOffset)
568         _firstLineRow -= end - start + 1;
569     updateSceneRect();
570 }
571
572
573 void ChatScene::rowsRemoved()
574 {
575     // move the marker line if necessary
576     setMarkerLine();
577 }
578
579
580 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
581 {
582     layout(tl.row(), br.row(), _sceneRect.width());
583 }
584
585
586 void ChatScene::updateForViewport(qreal width, qreal height)
587 {
588     _viewportHeight = height;
589     setWidth(width);
590 }
591
592
593 void ChatScene::setWidth(qreal width)
594 {
595     if (width == _sceneRect.width())
596         return;
597     layout(0, _lines.count()-1, width);
598 }
599
600
601 void ChatScene::layout(int start, int end, qreal width)
602 {
603     // clock_t startT = clock();
604
605     // disabling the index while doing this complex updates is about
606     // 2 to 10 times faster!
607     //setItemIndexMethod(QGraphicsScene::NoIndex);
608
609     if (end >= 0) {
610         int row = end;
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);
615         }
616
617         if (row >= 0) {
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());
621             if (offset != 0) {
622                 while (row >= 0) {
623                     line = _lines.at(row--);
624                     line->setPos(0, line->scenePos().y() + offset);
625                 }
626             }
627         }
628     }
629
630     //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
631
632     updateSceneRect(width);
633     setHandleXLimits();
634     setMarkerLine();
635     emit layoutChanged();
636
637 //   clock_t endT = clock();
638 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
639 }
640
641
642 void ChatScene::firstHandlePositionChanged(qreal xpos)
643 {
644     if (_firstColHandlePos == xpos)
645         return;
646
647     _firstColHandlePos = xpos >= 0 ? xpos : 0;
648     ChatViewSettings viewSettings(this);
649     viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
650     ChatViewSettings defaultSettings;
651     defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
652
653     // clock_t startT = clock();
654
655     // disabling the index while doing this complex updates is about
656     // 2 to 10 times faster!
657     //setItemIndexMethod(QGraphicsScene::NoIndex);
658
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);
664
665     while (lineIter != lineIterBegin) {
666         --lineIter;
667         (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
668     }
669     //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
670
671     setHandleXLimits();
672
673 //   clock_t endT = clock();
674 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
675 }
676
677
678 void ChatScene::secondHandlePositionChanged(qreal xpos)
679 {
680     if (_secondColHandlePos == xpos)
681         return;
682
683     _secondColHandlePos = xpos;
684     ChatViewSettings viewSettings(this);
685     viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
686     ChatViewSettings defaultSettings;
687     defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
688
689     // clock_t startT = clock();
690
691     // disabling the index while doing this complex updates is about
692     // 2 to 10 times faster!
693     //setItemIndexMethod(QGraphicsScene::NoIndex);
694
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) {
702         --lineIter;
703         (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
704     }
705     //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
706
707     updateSceneRect();
708     setHandleXLimits();
709     emit layoutChanged();
710
711 //   clock_t endT = clock();
712 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
713 }
714
715
716 void ChatScene::setHandleXLimits()
717 {
718     _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
719     _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
720     update();
721 }
722
723
724 void ChatScene::setSelectingItem(ChatItem *item)
725 {
726     if (_selectingItem) _selectingItem->clearSelection();
727     _selectingItem = item;
728 }
729
730
731 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
732 {
733     _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
734     _selectionStartCol = _selectionMinCol = item->column();
735     _isSelecting = true;
736     _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
737     updateSelection(item->mapToScene(itemPos));
738 }
739
740
741 void ChatScene::updateSelection(const QPointF &pos)
742 {
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);
751         }
752     }
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);
758     }
759     if (newstart > _selectionStart) {
760         for (int l = _selectionStart; l < newstart; l++)
761             _lines[l]->setSelected(false);
762     }
763     if (newend > _selectionEnd) {
764         for (int l = _selectionEnd+1; l <= newend; l++)
765             _lines[l]->setSelected(true, minColumn);
766     }
767     if (newend < _selectionEnd) {
768         for (int l = newend+1; l <= _selectionEnd; l++)
769             _lines[l]->setSelected(false);
770     }
771
772     _selectionStart = newstart;
773     _selectionEnd = newend;
774
775     if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
776         if (!_selectingItem) {
777             // _selectingItem has been removed already
778             return;
779         }
780         _lines[curRow]->setSelected(false);
781         _isSelecting = false;
782         _selectionStart = -1;
783         _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
784     }
785 }
786
787
788 bool ChatScene::isPosOverSelection(const QPointF &pos) const
789 {
790     ChatItem *chatItem = chatItemAt(pos);
791     if (!chatItem)
792         return false;
793     if (hasGlobalSelection()) {
794         int row = chatItem->row();
795         if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
796             return columnByScenePos(pos) >= _selectionMinCol;
797     }
798     else {
799         return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
800     }
801     return false;
802 }
803
804
805 bool ChatScene::isScrollingAllowed() const
806 {
807     if (_isSelecting)
808         return false;
809
810     // TODO: Handle clicks and single-item selections too
811
812     return true;
813 }
814
815
816 /******** MOUSE HANDLING **************************************************************************/
817
818 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
819 {
820     QPointF pos = event->scenePos();
821     QMenu menu;
822
823     // zoom actions and similar
824     chatView()->addActionsToMenu(&menu, pos);
825     menu.addSeparator();
826
827     // item-specific options (select link etc)
828     ChatItem *item = chatItemAt(pos);
829     if (item)
830         item->addActionsToMenu(&menu, item->mapFromScene(pos));
831     else
832         // no item -> default scene actions
833         GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
834
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);
841
842         QString searchSelectionText = selection();
843         if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
844             searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
845         searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
846
847         QAction *webSearchAction = new Action(QIcon::fromTheme("edit-find"), searchSelectionText, &menu, this, SLOT(webSearchOnSelection()));
848         menu.insertAction(sep, webSearchAction);
849     }
850
851     if (QtUi::mainWindow()->menuBar()->isHidden())
852         menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
853
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));
858
859     menu.exec(event->screenPos());
860 }
861
862
863 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
864 {
865     if (event->buttons() == Qt::LeftButton) {
866         if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
867             if (_clickTimer.isActive())
868                 _clickTimer.stop();
869             if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
870                 initiateDrag(event->widget());
871             else {
872                 _clickMode = DragStartClick;
873                 handleClick(Qt::LeftButton, _clickPos);
874             }
875             _clickMode = NoClick;
876         }
877         if (_isSelecting) {
878             updateSelection(event->scenePos());
879             emit mouseMoveWhileSelecting(event->scenePos());
880             event->accept();
881         }
882         else if (_clickHandled && _clickMode < DoubleClick)
883             QGraphicsScene::mouseMoveEvent(event);
884     }
885     else
886         QGraphicsScene::mouseMoveEvent(event);
887 }
888
889
890 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
891 {
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
897             clearSelection();
898         }
899         if (_clickMode != NoClick && _clickTimer.isActive()) {
900             switch (_clickMode) {
901             case NoClick:
902                 _clickMode = SingleClick; break;
903             case SingleClick:
904                 _clickMode = DoubleClick; break;
905             case DoubleClick:
906                 _clickMode = TripleClick; break;
907             case TripleClick:
908                 _clickMode = DoubleClick; break;
909             case DragStartClick:
910                 break;
911             }
912             handleClick(Qt::LeftButton, _clickPos);
913         }
914         else {
915             _clickMode = SingleClick;
916             _clickPos = event->scenePos();
917         }
918         _clickTimer.start();
919     }
920     if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
921         QGraphicsScene::mouseDoubleClickEvent(event);
922     else
923         QGraphicsScene::mousePressEvent(event);
924 }
925
926
927 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
928 {
929     // we check for doubleclick ourselves, so just call press handler
930     mousePressEvent(event);
931 }
932
933
934 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
935 {
936     if (event->button() == Qt::LeftButton && _leftButtonPressed) {
937         _leftButtonPressed = false;
938         if (_clickMode != NoClick) {
939             if (_clickMode == SingleClick)
940                 clearSelection();
941             event->accept();
942             if (!_clickTimer.isActive())
943                 handleClick(Qt::LeftButton, _clickPos);
944         }
945         else {
946             // no click -> drag or selection move
947             if (isGloballySelecting()) {
948                 selectionToClipboard(QClipboard::Selection);
949                 _isSelecting = false;
950                 event->accept();
951                 return;
952             }
953         }
954     }
955     QGraphicsScene::mouseReleaseEvent(event);
956 }
957
958
959 void ChatScene::clickTimeout()
960 {
961     if (!_leftButtonPressed && _clickMode == SingleClick)
962         handleClick(Qt::LeftButton, _clickPos);
963 }
964
965
966 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
967 {
968     if (button == Qt::LeftButton) {
969         clearSelection();
970
971         // Now send click down to items
972         ChatItem *chatItem = chatItemAt(scenePos);
973         if (chatItem) {
974             chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
975         }
976         _clickHandled = true;
977     }
978 }
979
980
981 void ChatScene::initiateDrag(QWidget *source)
982 {
983     QDrag *drag = new QDrag(source);
984     QMimeData *mimeData = new QMimeData;
985     mimeData->setText(selection());
986     drag->setMimeData(mimeData);
987
988     drag->exec(Qt::CopyAction);
989 }
990
991
992 /******** SELECTIONS ******************************************************************************/
993
994 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
995 {
996     if (!hasSelection())
997         return;
998
999     stringToClipboard(selection(), mode);
1000 }
1001
1002
1003 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
1004 {
1005     QString str = str_;
1006     // remove trailing linefeeds
1007     if (str.endsWith('\n'))
1008         str.chop(1);
1009
1010     switch (mode) {
1011     case QClipboard::Clipboard:
1012         QApplication::clipboard()->setText(str);
1013         break;
1014     case QClipboard::Selection:
1015         if (QApplication::clipboard()->supportsSelection())
1016             QApplication::clipboard()->setText(str, QClipboard::Selection);
1017         break;
1018     default:
1019         break;
1020     };
1021 }
1022
1023
1024 //!\brief Convert current selection to human-readable string.
1025 QString ChatScene::selection() const
1026 {
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;
1033             return QString();
1034         }
1035         QString result;
1036
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());
1047                 } else {
1048                     result += item->data(MessageModel::DisplayRole).toString() + " ";
1049                 }
1050             }
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
1055                     // hidden.
1056                     result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
1057                                                    .toString());
1058                 } else {
1059                     result += item->data(MessageModel::DisplayRole).toString() + " ";
1060                 }
1061             }
1062             result += _lines[l]->item(ChatLineModel::ContentsColumn)
1063                     ->data(MessageModel::DisplayRole).toString() + "\n";
1064         }
1065         return result;
1066     }
1067     else if (selectingItem())
1068         return selectingItem()->selection();
1069     return QString();
1070 }
1071
1072
1073 bool ChatScene::hasSelection() const
1074 {
1075     return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1076 }
1077
1078
1079 bool ChatScene::hasGlobalSelection() const
1080 {
1081     return _selectionStart >= 0;
1082 }
1083
1084
1085 bool ChatScene::isGloballySelecting() const
1086 {
1087     return _isSelecting;
1088 }
1089
1090
1091 void ChatScene::clearGlobalSelection()
1092 {
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;
1098     }
1099 }
1100
1101
1102 void ChatScene::clearSelection()
1103 {
1104     clearGlobalSelection();
1105     if (selectingItem())
1106         selectingItem()->clearSelection();
1107 }
1108
1109
1110 /******** *************************************************************************************/
1111
1112 void ChatScene::webSearchOnSelection()
1113 {
1114     if (!hasSelection())
1115         return;
1116
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);
1122 }
1123
1124
1125 /******** *************************************************************************************/
1126
1127 void ChatScene::requestBacklog()
1128 {
1129     MessageFilter *filter = qobject_cast<MessageFilter *>(model());
1130     if (filter)
1131         return filter->requestBacklog();
1132     return;
1133 }
1134
1135
1136 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1137 {
1138     if (x < _firstColHandle->x())
1139         return ChatLineModel::TimestampColumn;
1140     if (x < _secondColHandle->x())
1141         return ChatLineModel::SenderColumn;
1142
1143     return ChatLineModel::ContentsColumn;
1144 }
1145
1146
1147 int ChatScene::rowByScenePos(qreal y) const
1148 {
1149     QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1150
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));
1154         if (line)
1155             return line->row();
1156     }
1157     return -1;
1158 }
1159
1160
1161 void ChatScene::updateSceneRect(qreal width)
1162 {
1163     if (_lines.isEmpty()) {
1164         updateSceneRect(QRectF(0, 0, width, 0));
1165         return;
1166     }
1167
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();
1175         _firstLineRow = 0;
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)
1180                 break;
1181             _lines.at(_firstLineRow)->hide();
1182             _firstLineRow++;
1183         }
1184     }
1185
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()));
1191     }
1192     else {
1193         // empty scene rect
1194         updateSceneRect(QRectF(0, 0, width, 0));
1195     }
1196 }
1197
1198
1199 void ChatScene::updateSceneRect(const QRectF &rect)
1200 {
1201     _sceneRect = rect;
1202     setSceneRect(rect);
1203     update();
1204 }
1205
1206
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)
1212 {
1213     if (!_showWebPreview)
1214         return;
1215
1216     if (webPreview.urlRect != urlRect)
1217         webPreview.urlRect = urlRect;
1218
1219     if (webPreview.parentItem != parentItem)
1220         webPreview.parentItem = parentItem;
1221
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;
1230         }
1231         webPreview.previewState = WebPreview::NoPreview;
1232     }
1233
1234     if (webPreview.url.isEmpty())
1235         return;
1236
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);
1242         break;
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
1247         break;
1248     case WebPreview::HidePreview:
1249         // we still have a valid preview
1250         webPreview.previewState = WebPreview::DelayPreview;
1251         webPreview.timer.start(1000);
1252         break;
1253     }
1254     // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
1255 }
1256
1257
1258 void ChatScene::webPreviewNextStep()
1259 {
1260     // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1261     switch (webPreview.previewState) {
1262     case WebPreview::NoPreview:
1263         break;
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);
1269         break;
1270     case WebPreview::DelayPreview:
1271         Q_ASSERT(webPreview.previewItem);
1272         // calc position and show
1273         {
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();
1278
1279             if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1280                 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1281
1282             webPreview.previewItem->setPos(previewX, previewY);
1283         }
1284         addItem(webPreview.previewItem);
1285         webPreview.previewState = WebPreview::ShowPreview;
1286         break;
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!
1293     [[fallthrough]];
1294     case WebPreview::HidePreview:
1295         if (webPreview.previewItem) {
1296             delete webPreview.previewItem;
1297             webPreview.previewItem = 0;
1298         }
1299         webPreview.parentItem = 0;
1300         webPreview.url = QUrl();
1301         webPreview.urlRect = QRectF();
1302         webPreview.previewState = WebPreview::NoPreview;
1303     }
1304     // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
1305 }
1306
1307
1308 void ChatScene::clearWebPreview(ChatItem *parentItem)
1309 {
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
1314         break;
1315     case WebPreview::ShowPreview:
1316         if (parentItem == 0 || webPreview.parentItem == parentItem) {
1317             if (webPreview.previewItem && webPreview.previewItem->scene())
1318                 removeItem(webPreview.previewItem);
1319         }
1320     // fall through into to set hidden state
1321     [[fallthrough]];
1322     case WebPreview::DelayPreview:
1323         // we're just loading, so haven't shown the preview yet.
1324         webPreview.previewState = WebPreview::HidePreview;
1325         webPreview.timer.start(5000);
1326         break;
1327     case WebPreview::NoPreview:
1328     case WebPreview::HidePreview:
1329         break;
1330     }
1331     // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
1332 }
1333
1334
1335 #endif
1336
1337 // ========================================
1338 //  end of webkit only
1339 // ========================================
1340
1341 // Local configuration caching
1342 void ChatScene::showWebPreviewChanged()
1343 {
1344     ChatViewSettings settings;
1345     _showWebPreview = settings.showWebPreview();
1346 }
1347
1348 void ChatScene::showSenderBracketsChanged()
1349 {
1350     ChatViewSettings settings;
1351     _showSenderBrackets = settings.showSenderBrackets();
1352 }
1353
1354 void ChatScene::useCustomTimestampFormatChanged()
1355 {
1356     ChatViewSettings settings;
1357     _useCustomTimestampFormat = settings.useCustomTimestampFormat();
1358     updateTimestampHasBrackets();
1359 }
1360
1361 void ChatScene::timestampFormatStringChanged()
1362 {
1363     ChatViewSettings settings;
1364     _timestampFormatString = settings.timestampFormatString();
1365     updateTimestampHasBrackets();
1366 }
1367
1368 void ChatScene::updateTimestampHasBrackets()
1369 {
1370     // Calculate these parameters only as needed, rather than on-demand
1371
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;
1376     } else {
1377         // Does the timestamp format contain brackets?  For example:
1378         // Classic: "[hh:mm:ss]"
1379         // Modern:  " hh:mm:ss"
1380         //
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);
1396     }
1397 }