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