modernize: Use auto where the type is clear from context
[quassel.git] / src / qtui / chatscene.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 "chatscene.h"
22
23 #include <utility>
24
25 #include <QApplication>
26 #include <QClipboard>
27 #include <QDesktopServices>
28 #include <QDrag>
29 #include <QGraphicsSceneMouseEvent>
30 #include <QMenu>
31 #include <QMenuBar>
32 #include <QMimeData>
33 #include <QPersistentModelIndex>
34 #include <QUrl>
35
36 #ifdef HAVE_WEBENGINE
37 #  include <QWebEngineView>
38 #elif defined HAVE_WEBKIT
39 #  include <QWebView>
40 #endif
41
42 #include "chatitem.h"
43 #include "chatline.h"
44 #include "chatlinemodelitem.h"
45 #include "chatview.h"
46 #include "chatviewsettings.h"
47 #include "client.h"
48 #include "clientbacklogmanager.h"
49 #include "columnhandleitem.h"
50 #include "contextmenuactionprovider.h"
51 #include "icon.h"
52 #include "mainwin.h"
53 #include "markerlineitem.h"
54 #include "messagefilter.h"
55 #include "qtui.h"
56 #include "qtuistyle.h"
57 #include "webpreviewitem.h"
58
59 const qreal minContentsWidth = 200;
60
61 ChatScene::ChatScene(QAbstractItemModel *model, QString idString, qreal width, ChatView *parent)
62     : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
63     _chatView(parent),
64     _idString(std::move(idString)),
65     _model(model),
66     _singleBufferId(BufferId()),
67     _sceneRect(0, 0, width, 0),
68     _firstLineRow(-1),
69     _viewportHeight(0),
70     _markerLine(new MarkerLineItem(width)),
71     _markerLineVisible(false),
72     _markerLineValid(false),
73     _markerLineJumpPending(false),
74     _cutoffMode(CutoffRight),
75     _alwaysBracketSender(false),
76     _selectingItem(nullptr),
77     _selectionStart(-1),
78     _isSelecting(false),
79     _clickMode(NoClick),
80     _clickHandled(true),
81     _leftButtonPressed(false)
82 {
83     auto *filter = qobject_cast<MessageFilter *>(model);
84     if (filter && filter->isSingleBufferFilter()) {
85         _singleBufferId = filter->singleBufferId();
86     }
87
88     addItem(_markerLine);
89     connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
90
91     ChatViewSettings defaultSettings;
92     _defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
93     _defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
94
95     ChatViewSettings viewSettings(this);
96     _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", _defaultFirstColHandlePos).toInt();
97     _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", _defaultSecondColHandlePos).toInt();
98
99     _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
100     addItem(_firstColHandle);
101     _firstColHandle->setXPos(_firstColHandlePos);
102     connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
103     connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
104
105     _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
106     addItem(_secondColHandle);
107     _secondColHandle->setXPos(_secondColHandlePos);
108     connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
109
110     connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
111
112     setHandleXLimits();
113
114     if (model->rowCount() > 0)
115         rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
116
117     connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
118         this, SLOT(rowsInserted(const QModelIndex &, int, int)));
119     connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
120         this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
121     connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
122         this, SLOT(rowsRemoved()));
123     connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
124
125 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
126     webPreview.timer.setSingleShot(true);
127     connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
128 #endif
129     _showWebPreview = defaultSettings.showWebPreview();
130     defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
131
132     _showSenderBrackets = defaultSettings.showSenderBrackets();
133     defaultSettings.notify("ShowSenderBrackets", this, SLOT(showSenderBracketsChanged()));
134
135     _useCustomTimestampFormat = defaultSettings.useCustomTimestampFormat();
136     defaultSettings.notify("UseCustomTimestampFormat", this, SLOT(useCustomTimestampFormatChanged()));
137
138     _timestampFormatString = defaultSettings.timestampFormatString();
139     defaultSettings.notify("TimestampFormat", this, SLOT(timestampFormatStringChanged()));
140     updateTimestampHasBrackets();
141
142     _clickTimer.setInterval(QApplication::doubleClickInterval());
143     _clickTimer.setSingleShot(true);
144     connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
145
146     setItemIndexMethod(QGraphicsScene::NoIndex);
147 }
148
149
150 ChatView *ChatScene::chatView() const
151 {
152     return _chatView;
153 }
154
155
156 ColumnHandleItem *ChatScene::firstColumnHandle() const
157 {
158     return _firstColHandle;
159 }
160
161
162 ColumnHandleItem *ChatScene::secondColumnHandle() const
163 {
164     return _secondColHandle;
165 }
166
167 void ChatScene::resetColumnWidths()
168 {
169     //make sure first column is at least 80 px wide, second 120 px
170     int firstColHandlePos = qMax(_defaultFirstColHandlePos,
171                                  80);
172     int secondColHandlePos = qMax(_defaultSecondColHandlePos,
173                                   firstColHandlePos + 120);
174
175     _firstColHandle->setXPos(firstColHandlePos);
176     _secondColHandle->setXPos(secondColHandlePos);
177 }
178
179 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
180 {
181     if (!_lines.count())
182         return nullptr;
183
184     QList<ChatLine *>::ConstIterator start = _lines.begin();
185     QList<ChatLine *>::ConstIterator end = _lines.end();
186     QList<ChatLine *>::ConstIterator middle;
187
188     auto n = int(end - start);
189     int half;
190
191     while (n > 0) {
192         half = n >> 1;
193         middle = start + half;
194         if ((*middle)->msgId() < msgId) {
195             start = middle + 1;
196             n -= half + 1;
197         }
198         else {
199             n = half;
200         }
201     }
202
203     if (start != end && (*start)->msgId() == msgId && (ignoreDayChange ? (*start)->msgType() != Message::DayChange : true))
204         return *start;
205
206     if (matchExact)
207         return nullptr;
208
209     if (start == _lines.begin()) // not (yet?) in our scene
210         return nullptr;
211
212     // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
213
214     if (start == end) { // higher than last element
215         if (!ignoreDayChange)
216             return _lines.last();
217
218         for (int i = _lines.count() -1; i >= 0; i--) {
219             if (_lines.at(i)->msgType() != Message::DayChange)
220                 return _lines.at(i);
221         }
222         return nullptr;
223     }
224
225     // return the next-lower line
226     if (!ignoreDayChange)
227         return *(--start);
228
229     do {
230         if ((*(--start))->msgType() != Message::DayChange)
231             return *start;
232     }
233     while (start != _lines.begin());
234     return nullptr;
235 }
236
237
238 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
239 {
240     foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
241         auto *line = qgraphicsitem_cast<ChatLine *>(item);
242         if (line)
243             return line->itemAt(line->mapFromScene(scenePos));
244     }
245     return nullptr;
246 }
247
248
249 bool ChatScene::containsBuffer(const BufferId &id) const
250 {
251     auto *filter = qobject_cast<MessageFilter *>(model());
252     if (filter)
253         return filter->containsBuffer(id);
254     else
255         return false;
256 }
257
258
259 void ChatScene::setMarkerLineVisible(bool visible)
260 {
261     _markerLineVisible = visible;
262     if (visible && _markerLineValid)
263         markerLine()->setVisible(true);
264     else
265         markerLine()->setVisible(false);
266 }
267
268
269 void ChatScene::setMarkerLine(MsgId msgId)
270 {
271     if (!isSingleBufferScene())
272         return;
273
274     if (!msgId.isValid())
275         msgId = Client::markerLine(singleBufferId());
276
277     if (msgId.isValid()) {
278         ChatLine *line = chatLine(msgId, false, true);
279         if (line) {
280             markerLine()->setChatLine(line);
281             // if this was the last line, we won't see it because it's outside the sceneRect
282             // .. which is exactly what we want :)
283             markerLine()->setPos(line->pos() + QPointF(0, line->height()));
284
285             // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
286             if (markerLine()->pos().y() >= sceneRect().y()) {
287                 _markerLineValid = true;
288                 if (_markerLineVisible)
289                     markerLine()->setVisible(true);
290                 if (_markerLineJumpPending) {
291                     _markerLineJumpPending = false;
292                     if (markerLine()->isVisible()) {
293                         markerLine()->ensureVisible(QRectF(), 50, 50);
294                     }
295                 }
296                 return;
297             }
298         }
299     }
300     _markerLineValid = false;
301     markerLine()->setVisible(false);
302 }
303
304
305 void ChatScene::jumpToMarkerLine(bool requestBacklog)
306 {
307     if (!isSingleBufferScene())
308         return;
309
310     if (markerLine()->isVisible()) {
311         markerLine()->ensureVisible(QRectF(), 50, 50);
312         return;
313     }
314     if (!_markerLineValid && requestBacklog) {
315         MsgId msgId = Client::markerLine(singleBufferId());
316         if (msgId.isValid()) {
317             _markerLineJumpPending = true;
318             Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
319
320             // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
321             // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
322             // jump tries will eventually cause enough backlog to be fetched.
323             // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
324             this->requestBacklog();
325         }
326     }
327 }
328
329
330 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
331 {
332     Q_UNUSED(index);
333
334 //   QModelIndex sidx = model()->index(start, 2);
335 //   QModelIndex eidx = model()->index(end, 2);
336 //   qDebug() << "rowsInserted:";
337 //   if(start > 0) {
338 //     QModelIndex ssidx = model()->index(start - 1, 2);
339 //     qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
340 //           << ssidx.data(Qt::DisplayRole).toString();
341 //   }
342 //   qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
343 //         << sidx.data(Qt::DisplayRole).toString();
344 //   qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
345 //         << eidx.data(Qt::DisplayRole).toString();
346 //   if(end + 1 < model()->rowCount()) {
347 //     QModelIndex eeidx = model()->index(end + 1, 2);
348 //     qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
349 //           << eeidx.data(Qt::DisplayRole).toString();
350 //   }
351
352     qreal h = 0;
353     qreal y = 0;
354     qreal width = _sceneRect.width();
355     bool atBottom = (start == _lines.count());
356     bool atTop = !atBottom && (start == 0);
357
358     if (start < _lines.count()) {
359         y = _lines.value(start)->y();
360     }
361     else if (atBottom && !_lines.isEmpty()) {
362         y = _lines.last()->y() + _lines.last()->height();
363     }
364
365     qreal contentsWidth = width - secondColumnHandle()->sceneRight();
366     qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
367     qreal timestampWidth = firstColumnHandle()->sceneLeft();
368     QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
369     QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
370
371     if (atTop) {
372         for (int i = end; i >= start; i--) {
373             auto *line = new ChatLine(i, model(),
374                 width,
375                 timestampWidth, senderWidth, contentsWidth,
376                 senderPos, contentsPos);
377             h += line->height();
378             line->setPos(0, y-h);
379             _lines.insert(start, line);
380             addItem(line);
381         }
382     }
383     else {
384         for (int i = start; i <= end; i++) {
385             auto *line = new ChatLine(i, model(),
386                 width,
387                 timestampWidth, senderWidth, contentsWidth,
388                 senderPos, contentsPos);
389             line->setPos(0, y+h);
390             h += line->height();
391             _lines.insert(i, line);
392             addItem(line);
393         }
394     }
395
396     // update existing items
397     for (int i = end+1; i < _lines.count(); i++) {
398         _lines[i]->setRow(i);
399     }
400
401     // update selection
402     if (_selectionStart >= 0) {
403         int offset = end - start + 1;
404         int oldStart = _selectionStart;
405         if (_selectionStart >= start)
406             _selectionStart += offset;
407         if (_selectionEnd >= start) {
408             _selectionEnd += offset;
409             if (_selectionStart == oldStart)
410                 for (int i = start; i < start + offset; i++)
411                     _lines[i]->setSelected(true);
412         }
413         if (_firstSelectionRow >= start)
414             _firstSelectionRow += offset;
415     }
416
417     // neither pre- or append means we have to do dirty work: move items...
418     if (!(atTop || atBottom)) {
419         ChatLine *line = nullptr;
420         for (int i = 0; i <= end; i++) {
421             line = _lines.at(i);
422             line->setPos(0, line->pos().y() - h);
423             if (line == markerLine()->chatLine())
424                 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
425         }
426     }
427
428     // check if all went right
429     Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
430 //   if(start != 0) {
431 //     if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
432 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
433 //       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();
434 //       qDebug() << "line[start]" << _lines.at(start)->pos().y();
435 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
436 //       Q_ASSERT(false)
437 //     }
438 //   }
439     Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
440 //   if(end + 1 < _lines.count()) {
441 //     if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
442 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
443 //       qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
444 //       qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
445 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
446 //       Q_ASSERT(false);
447 //     }
448 //   }
449
450     if (!atBottom) {
451         if (start < _firstLineRow) {
452             int prevFirstLineRow = _firstLineRow + (end - start + 1);
453             for (int i = end + 1; i < prevFirstLineRow; i++) {
454                 _lines.at(i)->show();
455             }
456         }
457         // force new search for first proper line
458         _firstLineRow = -1;
459     }
460     updateSceneRect();
461     if (atBottom) {
462         emit lastLineChanged(_lines.last(), h);
463     }
464
465     // now move the marker line if necessary. we don't need to do anything if we appended lines though...
466     if (!_markerLineValid)
467         setMarkerLine();
468 }
469
470
471 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
472 {
473     Q_UNUSED(parent);
474
475     qreal h = 0; // total height of removed items;
476
477     bool atTop = (start == 0);
478     bool atBottom = (end == _lines.count() - 1);
479
480     // clear selection
481     if (_selectingItem) {
482         int row = _selectingItem->row();
483         if (row >= start && row <= end)
484             setSelectingItem(nullptr);
485     }
486
487     // remove items from scene
488     QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
489     int lineCount = start;
490     while (lineIter != _lines.end() && lineCount <= end) {
491         if ((*lineIter) == markerLine()->chatLine())
492             markerLine()->setChatLine(nullptr);
493         h += (*lineIter)->height();
494         delete *lineIter;
495         lineIter = _lines.erase(lineIter);
496         lineCount++;
497     }
498
499     // update rows of remaining chatlines
500     for (int i = start; i < _lines.count(); i++) {
501         _lines.at(i)->setRow(i);
502     }
503
504     // update selection
505     if (_selectionStart >= 0) {
506         int offset = end - start + 1;
507         if (_selectionStart >= start)
508             _selectionStart = qMax(_selectionStart - offset, start);
509         if (_selectionEnd >= start)
510             _selectionEnd -= offset;
511         if (_firstSelectionRow >= start)
512             _firstSelectionRow -= offset;
513
514         if (_selectionEnd < _selectionStart) {
515             _isSelecting = false;
516             _selectionStart = -1;
517         }
518     }
519
520     // neither removing at bottom or top means we have to move items...
521     if (!(atTop || atBottom)) {
522         qreal offset = h;
523         int moveStart = 0;
524         int moveEnd = _lines.count() - 1;
525         if (start < _lines.count() - start) {
526             // move top part
527             moveEnd = start - 1;
528         }
529         else {
530             // move bottom part
531             moveStart = start;
532             offset = -offset;
533         }
534         ChatLine *line = nullptr;
535         for (int i = moveStart; i <= moveEnd; i++) {
536             line = _lines.at(i);
537             line->setPos(0, line->pos().y() + offset);
538         }
539     }
540
541     Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
542
543     // update sceneRect
544     // when searching for the first non-date-line we have to take into account that our
545     // model still contains the just removed lines so we cannot simply call updateSceneRect()
546     int numRows = model()->rowCount();
547     QModelIndex firstLineIdx;
548     _firstLineRow = -1;
549     bool needOffset = false;
550     do {
551         _firstLineRow++;
552         if (_firstLineRow >= start && _firstLineRow <= end) {
553             _firstLineRow = end + 1;
554             needOffset = true;
555         }
556         firstLineIdx = model()->index(_firstLineRow, 0);
557     }
558     while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
559
560     if (needOffset)
561         _firstLineRow -= end - start + 1;
562     updateSceneRect();
563 }
564
565
566 void ChatScene::rowsRemoved()
567 {
568     // move the marker line if necessary
569     setMarkerLine();
570 }
571
572
573 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
574 {
575     layout(tl.row(), br.row(), _sceneRect.width());
576 }
577
578
579 void ChatScene::updateForViewport(qreal width, qreal height)
580 {
581     _viewportHeight = height;
582     setWidth(width);
583 }
584
585
586 void ChatScene::setWidth(qreal width)
587 {
588     if (width == _sceneRect.width())
589         return;
590     layout(0, _lines.count()-1, width);
591 }
592
593
594 void ChatScene::layout(int start, int end, qreal width)
595 {
596     // clock_t startT = clock();
597
598     // disabling the index while doing this complex updates is about
599     // 2 to 10 times faster!
600     //setItemIndexMethod(QGraphicsScene::NoIndex);
601
602     if (end >= 0) {
603         int row = end;
604         qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
605         qreal contentsWidth = width - secondColumnHandle()->sceneRight();
606         while (row >= start) {
607             _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
608         }
609
610         if (row >= 0) {
611             // remaining items don't need geometry changes, but maybe repositioning?
612             ChatLine *line = _lines.at(row);
613             qreal offset = linePos - (line->scenePos().y() + line->height());
614             if (offset != 0) {
615                 while (row >= 0) {
616                     line = _lines.at(row--);
617                     line->setPos(0, line->scenePos().y() + offset);
618                 }
619             }
620         }
621     }
622
623     //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
624
625     updateSceneRect(width);
626     setHandleXLimits();
627     setMarkerLine();
628     emit layoutChanged();
629
630 //   clock_t endT = clock();
631 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
632 }
633
634
635 void ChatScene::firstHandlePositionChanged(qreal xpos)
636 {
637     if (_firstColHandlePos == xpos)
638         return;
639
640     _firstColHandlePos = xpos >= 0 ? xpos : 0;
641     ChatViewSettings viewSettings(this);
642     viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
643     ChatViewSettings defaultSettings;
644     defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
645
646     // clock_t startT = clock();
647
648     // disabling the index while doing this complex updates is about
649     // 2 to 10 times faster!
650     //setItemIndexMethod(QGraphicsScene::NoIndex);
651
652     QList<ChatLine *>::iterator lineIter = _lines.end();
653     QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
654     qreal timestampWidth = firstColumnHandle()->sceneLeft();
655     qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
656     QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
657
658     while (lineIter != lineIterBegin) {
659         --lineIter;
660         (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
661     }
662     //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
663
664     setHandleXLimits();
665
666 //   clock_t endT = clock();
667 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
668 }
669
670
671 void ChatScene::secondHandlePositionChanged(qreal xpos)
672 {
673     if (_secondColHandlePos == xpos)
674         return;
675
676     _secondColHandlePos = xpos;
677     ChatViewSettings viewSettings(this);
678     viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
679     ChatViewSettings defaultSettings;
680     defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
681
682     // clock_t startT = clock();
683
684     // disabling the index while doing this complex updates is about
685     // 2 to 10 times faster!
686     //setItemIndexMethod(QGraphicsScene::NoIndex);
687
688     QList<ChatLine *>::iterator lineIter = _lines.end();
689     QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
690     qreal linePos = _sceneRect.y() + _sceneRect.height();
691     qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
692     qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
693     QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
694     while (lineIter != lineIterBegin) {
695         --lineIter;
696         (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
697     }
698     //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
699
700     updateSceneRect();
701     setHandleXLimits();
702     emit layoutChanged();
703
704 //   clock_t endT = clock();
705 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
706 }
707
708
709 void ChatScene::setHandleXLimits()
710 {
711     _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
712     _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
713     update();
714 }
715
716
717 void ChatScene::setSelectingItem(ChatItem *item)
718 {
719     if (_selectingItem) _selectingItem->clearSelection();
720     _selectingItem = item;
721 }
722
723
724 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
725 {
726     _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
727     _selectionStartCol = _selectionMinCol = item->column();
728     _isSelecting = true;
729     _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
730     updateSelection(item->mapToScene(itemPos));
731 }
732
733
734 void ChatScene::updateSelection(const QPointF &pos)
735 {
736     int curRow = rowByScenePos(pos);
737     if (curRow < 0) return;
738     auto curColumn = (int)columnByScenePos(pos);
739     auto minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
740     if (minColumn != _selectionMinCol) {
741         _selectionMinCol = minColumn;
742         for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
743             _lines[l]->setSelected(true, minColumn);
744         }
745     }
746     int newstart = qMin(curRow, _firstSelectionRow);
747     int newend = qMax(curRow, _firstSelectionRow);
748     if (newstart < _selectionStart) {
749         for (int l = newstart; l < _selectionStart; l++)
750             _lines[l]->setSelected(true, minColumn);
751     }
752     if (newstart > _selectionStart) {
753         for (int l = _selectionStart; l < newstart; l++)
754             _lines[l]->setSelected(false);
755     }
756     if (newend > _selectionEnd) {
757         for (int l = _selectionEnd+1; l <= newend; l++)
758             _lines[l]->setSelected(true, minColumn);
759     }
760     if (newend < _selectionEnd) {
761         for (int l = newend+1; l <= _selectionEnd; l++)
762             _lines[l]->setSelected(false);
763     }
764
765     _selectionStart = newstart;
766     _selectionEnd = newend;
767
768     if (newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
769         if (!_selectingItem) {
770             // _selectingItem has been removed already
771             return;
772         }
773         _lines[curRow]->setSelected(false);
774         _isSelecting = false;
775         _selectionStart = -1;
776         _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
777     }
778 }
779
780
781 bool ChatScene::isPosOverSelection(const QPointF &pos) const
782 {
783     ChatItem *chatItem = chatItemAt(pos);
784     if (!chatItem)
785         return false;
786     if (hasGlobalSelection()) {
787         int row = chatItem->row();
788         if (row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
789             return columnByScenePos(pos) >= _selectionMinCol;
790     }
791     else {
792         return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
793     }
794     return false;
795 }
796
797
798 bool ChatScene::isScrollingAllowed() const
799 {
800     if (_isSelecting)
801         return false;
802
803     // TODO: Handle clicks and single-item selections too
804
805     return true;
806 }
807
808
809 /******** MOUSE HANDLING **************************************************************************/
810
811 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
812 {
813     QPointF pos = event->scenePos();
814     QMenu menu;
815
816     // zoom actions and similar
817     chatView()->addActionsToMenu(&menu, pos);
818     menu.addSeparator();
819
820     // item-specific options (select link etc)
821     ChatItem *item = chatItemAt(pos);
822     if (item)
823         item->addActionsToMenu(&menu, item->mapFromScene(pos));
824     else
825         // no item -> default scene actions
826         GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
827
828     // If we have text selected, insert the Copy Selection as first item
829     if (isPosOverSelection(pos)) {
830         QAction *sep = menu.insertSeparator(menu.actions().first());
831         QAction *act = new Action(icon::get("edit-copy"), tr("Copy Selection"), &menu, this,
832             SLOT(selectionToClipboard()), QKeySequence::Copy);
833         menu.insertAction(sep, act);
834
835         QString searchSelectionText = selection();
836         if (searchSelectionText.length() > _webSearchSelectionTextMaxVisible)
837             searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
838         searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
839
840         QAction *webSearchAction = new Action(icon::get("edit-find"), searchSelectionText, &menu, this, SLOT(webSearchOnSelection()));
841         menu.insertAction(sep, webSearchAction);
842     }
843
844     if (QtUi::mainWindow()->menuBar()->isHidden())
845         menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
846
847     // show column reset action if columns have been resized in this session or there is at least one very narrow column
848     if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
849         (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
850         menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, SLOT(resetColumnWidths()), 0));
851
852     menu.exec(event->screenPos());
853 }
854
855
856 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
857 {
858     if (event->buttons() == Qt::LeftButton) {
859         if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
860             if (_clickTimer.isActive())
861                 _clickTimer.stop();
862             if (_clickMode == SingleClick && isPosOverSelection(_clickPos))
863                 initiateDrag(event->widget());
864             else {
865                 _clickMode = DragStartClick;
866                 handleClick(Qt::LeftButton, _clickPos);
867             }
868             _clickMode = NoClick;
869         }
870         if (_isSelecting) {
871             updateSelection(event->scenePos());
872             emit mouseMoveWhileSelecting(event->scenePos());
873             event->accept();
874         }
875         else if (_clickHandled && _clickMode < DoubleClick)
876             QGraphicsScene::mouseMoveEvent(event);
877     }
878     else
879         QGraphicsScene::mouseMoveEvent(event);
880 }
881
882
883 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
884 {
885     if (event->buttons() == Qt::LeftButton) {
886         _leftButtonPressed = true;
887         _clickHandled = false;
888         if (!isPosOverSelection(event->scenePos())) {
889             // immediately clear selection if clicked outside; otherwise, wait for potential drag
890             clearSelection();
891         }
892         if (_clickMode != NoClick && _clickTimer.isActive()) {
893             switch (_clickMode) {
894             case NoClick:
895                 _clickMode = SingleClick; break;
896             case SingleClick:
897                 _clickMode = DoubleClick; break;
898             case DoubleClick:
899                 _clickMode = TripleClick; break;
900             case TripleClick:
901                 _clickMode = DoubleClick; break;
902             case DragStartClick:
903                 break;
904             }
905             handleClick(Qt::LeftButton, _clickPos);
906         }
907         else {
908             _clickMode = SingleClick;
909             _clickPos = event->scenePos();
910         }
911         _clickTimer.start();
912     }
913     if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
914         QGraphicsScene::mouseDoubleClickEvent(event);
915     else
916         QGraphicsScene::mousePressEvent(event);
917 }
918
919
920 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
921 {
922     // we check for doubleclick ourselves, so just call press handler
923     mousePressEvent(event);
924 }
925
926
927 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
928 {
929     if (event->button() == Qt::LeftButton && _leftButtonPressed) {
930         _leftButtonPressed = false;
931         if (_clickMode != NoClick) {
932             if (_clickMode == SingleClick)
933                 clearSelection();
934             event->accept();
935             if (!_clickTimer.isActive())
936                 handleClick(Qt::LeftButton, _clickPos);
937         }
938         else {
939             // no click -> drag or selection move
940             if (isGloballySelecting()) {
941                 selectionToClipboard(QClipboard::Selection);
942                 _isSelecting = false;
943                 event->accept();
944                 return;
945             }
946         }
947     }
948     QGraphicsScene::mouseReleaseEvent(event);
949 }
950
951
952 void ChatScene::clickTimeout()
953 {
954     if (!_leftButtonPressed && _clickMode == SingleClick)
955         handleClick(Qt::LeftButton, _clickPos);
956 }
957
958
959 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
960 {
961     if (button == Qt::LeftButton) {
962         clearSelection();
963
964         // Now send click down to items
965         ChatItem *chatItem = chatItemAt(scenePos);
966         if (chatItem) {
967             chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
968         }
969         _clickHandled = true;
970     }
971 }
972
973
974 void ChatScene::initiateDrag(QWidget *source)
975 {
976     auto *drag = new QDrag(source);
977     auto *mimeData = new QMimeData;
978     mimeData->setText(selection());
979     drag->setMimeData(mimeData);
980
981     drag->exec(Qt::CopyAction);
982 }
983
984
985 /******** SELECTIONS ******************************************************************************/
986
987 void ChatScene::selectionToClipboard(QClipboard::Mode mode)
988 {
989     if (!hasSelection())
990         return;
991
992     stringToClipboard(selection(), mode);
993 }
994
995
996 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
997 {
998     QString str = str_;
999     // remove trailing linefeeds
1000     if (str.endsWith('\n'))
1001         str.chop(1);
1002
1003     switch (mode) {
1004     case QClipboard::Clipboard:
1005         QApplication::clipboard()->setText(str);
1006         break;
1007     case QClipboard::Selection:
1008         if (QApplication::clipboard()->supportsSelection())
1009             QApplication::clipboard()->setText(str, QClipboard::Selection);
1010         break;
1011     default:
1012         break;
1013     };
1014 }
1015
1016
1017 //!\brief Convert current selection to human-readable string.
1018 QString ChatScene::selection() const
1019 {
1020     //TODO Make selection format configurable!
1021     if (hasGlobalSelection()) {
1022         int start = qMin(_selectionStart, _selectionEnd);
1023         int end = qMax(_selectionStart, _selectionEnd);
1024         if (start < 0 || end >= _lines.count()) {
1025             qDebug() << "Invalid selection range:" << start << end;
1026             return QString();
1027         }
1028         QString result;
1029
1030         for (int l = start; l <= end; l++) {
1031             if (_selectionMinCol == ChatLineModel::TimestampColumn) {
1032                 ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
1033                 if (!_showSenderBrackets && !_timestampHasBrackets) {
1034                     // Only re-add brackets if the current timestamp format does not include them
1035                     // -and- sender brackets are disabled.  Don't filter on Message::Plain as
1036                     // timestamp brackets affect all types of messages.
1037                     // Remove any spaces before and after, otherwise it may look weird.
1038                     result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
1039                                                    .toString().trimmed());
1040                 } else {
1041                     result += item->data(MessageModel::DisplayRole).toString() + " ";
1042                 }
1043             }
1044             if (_selectionMinCol <= ChatLineModel::SenderColumn) {
1045                 ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
1046                 if (!_showSenderBrackets && (_alwaysBracketSender
1047                                              || item->chatLine()->msgType() == Message::Plain)) {
1048                     // Copying to plain-text.  Re-add the sender brackets if they're normally hidden
1049                     // for...
1050                     // * Plain messages
1051                     // * All messages in the Chat Monitor
1052                     //
1053                     // The Chat Monitor sets alwaysBracketSender() to true.
1054                     result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
1055                                                    .toString());
1056                 } else {
1057                     result += item->data(MessageModel::DisplayRole).toString() + " ";
1058                 }
1059             }
1060             result += _lines[l]->item(ChatLineModel::ContentsColumn)
1061                     ->data(MessageModel::DisplayRole).toString() + "\n";
1062         }
1063         return result;
1064     }
1065     else if (selectingItem())
1066         return selectingItem()->selection();
1067     return QString();
1068 }
1069
1070
1071 bool ChatScene::hasSelection() const
1072 {
1073     return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
1074 }
1075
1076
1077 bool ChatScene::hasGlobalSelection() const
1078 {
1079     return _selectionStart >= 0;
1080 }
1081
1082
1083 bool ChatScene::isGloballySelecting() const
1084 {
1085     return _isSelecting;
1086 }
1087
1088
1089 void ChatScene::clearGlobalSelection()
1090 {
1091     if (hasGlobalSelection()) {
1092         for (int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
1093             _lines[l]->setSelected(false);
1094         _isSelecting = false;
1095         _selectionStart = -1;
1096     }
1097 }
1098
1099
1100 void ChatScene::clearSelection()
1101 {
1102     clearGlobalSelection();
1103     if (selectingItem())
1104         selectingItem()->clearSelection();
1105 }
1106
1107
1108 /******** *************************************************************************************/
1109
1110 void ChatScene::webSearchOnSelection()
1111 {
1112     if (!hasSelection())
1113         return;
1114
1115     ChatViewSettings settings;
1116     QString webSearchBaseUrl = settings.webSearchUrlFormatString();
1117     QString webSearchUrl = webSearchBaseUrl.replace(QString("%s"), selection());
1118     QUrl url = QUrl::fromUserInput(webSearchUrl);
1119     QDesktopServices::openUrl(url);
1120 }
1121
1122
1123 /******** *************************************************************************************/
1124
1125 void ChatScene::requestBacklog()
1126 {
1127     auto *filter = qobject_cast<MessageFilter *>(model());
1128     if (filter)
1129         return filter->requestBacklog();
1130     return;
1131 }
1132
1133
1134 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
1135 {
1136     if (x < _firstColHandle->x())
1137         return ChatLineModel::TimestampColumn;
1138     if (x < _secondColHandle->x())
1139         return ChatLineModel::SenderColumn;
1140
1141     return ChatLineModel::ContentsColumn;
1142 }
1143
1144
1145 int ChatScene::rowByScenePos(qreal y) const
1146 {
1147     QList<QGraphicsItem *> itemList = items(QPointF(0, y));
1148
1149     // ChatLine should be at the bottom of the list
1150     for (int i = itemList.count()-1; i >= 0; i--) {
1151         auto *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
1152         if (line)
1153             return line->row();
1154     }
1155     return -1;
1156 }
1157
1158
1159 void ChatScene::updateSceneRect(qreal width)
1160 {
1161     if (_lines.isEmpty()) {
1162         updateSceneRect(QRectF(0, 0, width, 0));
1163         return;
1164     }
1165
1166     // we hide day change messages at the top by making the scene rect smaller
1167     // and by calling QGraphicsItem::hide() on all leading day change messages
1168     // the first one is needed to ensure proper scrollbar ranges
1169     // the second for cases where the viewport is larger then the set scenerect
1170     //  (in this case the items are shown anyways)
1171     if (_firstLineRow == -1) {
1172         int numRows = model()->rowCount();
1173         _firstLineRow = 0;
1174         QModelIndex firstLineIdx;
1175         while (_firstLineRow < numRows) {
1176             firstLineIdx = model()->index(_firstLineRow, 0);
1177             if ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
1178                 break;
1179             _lines.at(_firstLineRow)->hide();
1180             _firstLineRow++;
1181         }
1182     }
1183
1184     // the following call should be safe. If it crashes something went wrong during insert/remove
1185     if (_firstLineRow < _lines.count()) {
1186         ChatLine *firstLine = _lines.at(_firstLineRow);
1187         ChatLine *lastLine = _lines.last();
1188         updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1189     }
1190     else {
1191         // empty scene rect
1192         updateSceneRect(QRectF(0, 0, width, 0));
1193     }
1194 }
1195
1196
1197 void ChatScene::updateSceneRect(const QRectF &rect)
1198 {
1199     _sceneRect = rect;
1200     setSceneRect(rect);
1201     update();
1202 }
1203
1204
1205 // ========================================
1206 //  Webkit/WebEngine Only stuff
1207 // ========================================
1208 #if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
1209 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
1210 {
1211     if (!_showWebPreview)
1212         return;
1213
1214     if (webPreview.urlRect != urlRect)
1215         webPreview.urlRect = urlRect;
1216
1217     if (webPreview.parentItem != parentItem)
1218         webPreview.parentItem = parentItem;
1219
1220     if (webPreview.url != url) {
1221         webPreview.url = url;
1222         // prepare to load a different URL
1223         if (webPreview.previewItem) {
1224             if (webPreview.previewItem->scene())
1225                 removeItem(webPreview.previewItem);
1226             delete webPreview.previewItem;
1227             webPreview.previewItem = nullptr;
1228         }
1229         webPreview.previewState = WebPreview::NoPreview;
1230     }
1231
1232     if (webPreview.url.isEmpty())
1233         return;
1234
1235     // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1236     switch (webPreview.previewState) {
1237     case WebPreview::NoPreview:
1238         webPreview.previewState = WebPreview::NewPreview;
1239         webPreview.timer.start(500);
1240         break;
1241     case WebPreview::NewPreview:
1242     case WebPreview::DelayPreview:
1243     case WebPreview::ShowPreview:
1244         // we're already waiting for the next step or showing the preview
1245         break;
1246     case WebPreview::HidePreview:
1247         // we still have a valid preview
1248         webPreview.previewState = WebPreview::DelayPreview;
1249         webPreview.timer.start(1000);
1250         break;
1251     }
1252     // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
1253 }
1254
1255
1256 void ChatScene::webPreviewNextStep()
1257 {
1258     // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1259     switch (webPreview.previewState) {
1260     case WebPreview::NoPreview:
1261         break;
1262     case WebPreview::NewPreview:
1263         Q_ASSERT(!webPreview.previewItem);
1264         webPreview.previewItem = new WebPreviewItem(webPreview.url);
1265         webPreview.previewState = WebPreview::DelayPreview;
1266         webPreview.timer.start(1000);
1267         break;
1268     case WebPreview::DelayPreview:
1269         Q_ASSERT(webPreview.previewItem);
1270         // calc position and show
1271         {
1272             qreal previewY = webPreview.urlRect.bottom();
1273             qreal previewX = webPreview.urlRect.x();
1274             if (previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1275                 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1276
1277             if (previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1278                 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1279
1280             webPreview.previewItem->setPos(previewX, previewY);
1281         }
1282         addItem(webPreview.previewItem);
1283         webPreview.previewState = WebPreview::ShowPreview;
1284         break;
1285     case WebPreview::ShowPreview:
1286         qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1287         qWarning() << "removing preview";
1288         if (webPreview.previewItem && webPreview.previewItem->scene()) {
1289             removeItem(webPreview.previewItem);
1290         }
1291
1292         // Intentional fallthrough
1293
1294     case WebPreview::HidePreview:
1295         if (webPreview.previewItem) {
1296             delete webPreview.previewItem;
1297             webPreview.previewItem = nullptr;
1298         }
1299         webPreview.parentItem = nullptr;
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 == nullptr || webPreview.parentItem == parentItem) {
1317             if (webPreview.previewItem && webPreview.previewItem->scene())
1318                 removeItem(webPreview.previewItem);
1319         }
1320
1321         // Intentional fallthrough
1322
1323     case WebPreview::DelayPreview:
1324         // we're just loading, so haven't shown the preview yet.
1325         webPreview.previewState = WebPreview::HidePreview;
1326         webPreview.timer.start(5000);
1327         break;
1328     case WebPreview::NoPreview:
1329     case WebPreview::HidePreview:
1330         break;
1331     }
1332     // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
1333 }
1334
1335
1336 #endif
1337
1338 // ========================================
1339 //  end of webkit only
1340 // ========================================
1341
1342 // Local configuration caching
1343 void ChatScene::showWebPreviewChanged()
1344 {
1345     ChatViewSettings settings;
1346     _showWebPreview = settings.showWebPreview();
1347 }
1348
1349 void ChatScene::showSenderBracketsChanged()
1350 {
1351     ChatViewSettings settings;
1352     _showSenderBrackets = settings.showSenderBrackets();
1353 }
1354
1355 void ChatScene::useCustomTimestampFormatChanged()
1356 {
1357     ChatViewSettings settings;
1358     _useCustomTimestampFormat = settings.useCustomTimestampFormat();
1359     updateTimestampHasBrackets();
1360 }
1361
1362 void ChatScene::timestampFormatStringChanged()
1363 {
1364     ChatViewSettings settings;
1365     _timestampFormatString = settings.timestampFormatString();
1366     updateTimestampHasBrackets();
1367 }
1368
1369 void ChatScene::updateTimestampHasBrackets()
1370 {
1371     // Calculate these parameters only as needed, rather than on-demand
1372
1373     if (!_useCustomTimestampFormat) {
1374         // The default timestamp format string does not have brackets, no need to check.
1375         // If UiStyle::updateSystemTimestampFormat() has brackets added, change this, too.
1376         _timestampHasBrackets = false;
1377     } else {
1378         // Does the timestamp format contain brackets?  For example:
1379         // Classic: "[hh:mm:ss]"
1380         // Modern:  " hh:mm:ss"
1381         //
1382         // Match groups of any opening or closing brackets - (), {}, [], <>, (>, {], etc:
1383         //   ^\s*[({[<].+[)}\]>]\s*$
1384         //   [...]    is a character group containing ...
1385         //   ^        matches start of string
1386         //   \s*      matches any amount of whitespace
1387         //   [({[<]   matches (, {, [, or <
1388         //   .+       matches one or more characters
1389         //   [)}\]>]  matches ), }, ], or >, escaping the ]
1390         //   $        matches end of string
1391         // Alternatively, if opening and closing brackets must be in pairs, use this:
1392         //   (^\s*\(.+\)\s*$)|(^\s*\{.+\}\s*$)|(^\s*\[.+\]\s*$)|(^\s*<.+>\s*$)
1393         // Note that '\' must be escaped as '\\'
1394         // Helpful interactive website for debugging and explaining:  https://regex101.com/
1395         const QRegExp regExpMatchBrackets("^\\s*[({[<].+[)}\\]>]\\s*$");
1396         _timestampHasBrackets = regExpMatchBrackets.exactMatch(_timestampFormatString);
1397     }
1398 }