common: Make SyncableObject non-copyable
[quassel.git] / src / qtui / chatlinemodelitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 "chatlinemodelitem.h"
22
23 #include <QFontMetrics>
24 #include <QTextBoundaryFinder>
25
26 #include "chatlinemodel.h"
27 #include "qtui.h"
28 #include "qtuistyle.h"
29
30 // This Struct is taken from Harfbuzz. We use it only to calc it's size.
31 // we use a shared memory region so we do not have to malloc a buffer area for every line
32 using HB_CharAttributes_Dummy = struct
33 {
34     /*HB_LineBreakType*/ unsigned lineBreakType : 2;
35     /*HB_Bool*/ unsigned whiteSpace : 1; /* A unicode whitespace character, except NBSP, ZWNBSP */
36     /*HB_Bool*/ unsigned charStop : 1;   /* Valid cursor position (for left/right arrow) */
37     /*HB_Bool*/ unsigned wordBoundary : 1;
38     /*HB_Bool*/ unsigned sentenceBoundary : 1;
39     unsigned unused : 2;
40 };
41
42 unsigned char* ChatLineModelItem::TextBoundaryFinderBuffer = (unsigned char*)malloc(512 * sizeof(HB_CharAttributes_Dummy));
43 int ChatLineModelItem::TextBoundaryFinderBufferSize = 512 * (sizeof(HB_CharAttributes_Dummy) / sizeof(unsigned char));
44
45 // ****************************************
46 // the actual ChatLineModelItem
47 // ****************************************
48 ChatLineModelItem::ChatLineModelItem(const Message& msg)
49     : MessageModelItem()
50     , _styledMsg(msg)
51 {
52     if (!msg.sender().contains('!'))
53         _styledMsg.setFlags(msg.flags() |= Message::ServerMsg);
54
55     if (_styledMsg.type() == Message::Nick) {
56         // HACK: Work around nick changes on Quassel core not properly being set as Self
57         // While this is fixed in the core, old cores and past history will still show incorrectly.
58         if (nickFromMask(_styledMsg.sender()) == stripFormatCodes(_styledMsg.contents()).toLower()) {
59             _styledMsg.setFlags(msg.flags() |= Message::Self);
60         }
61     }
62     // Unfortunately, the missing Self flag for other message types can't easily be worked around.
63 }
64
65 bool ChatLineModelItem::setData(int column, const QVariant& value, int role)
66 {
67     switch (role) {
68     case MessageModel::FlagsRole:
69         _styledMsg.setFlags((Message::Flags)value.toInt());
70         return true;
71     default:
72         return MessageModelItem::setData(column, value, role);
73     }
74 }
75
76 QVariant ChatLineModelItem::data(int column, int role) const
77 {
78     if (role == ChatLineModel::MsgLabelRole)
79         return QVariant::fromValue(messageLabel());
80
81     QVariant variant;
82     auto col = (MessageModel::ColumnType)column;
83     switch (col) {
84     case ChatLineModel::TimestampColumn:
85         variant = timestampData(role);
86         break;
87     case ChatLineModel::SenderColumn:
88         variant = senderData(role);
89         break;
90     case ChatLineModel::ContentsColumn:
91         variant = contentsData(role);
92         break;
93     default:
94         break;
95     }
96     if (!variant.isValid())
97         return MessageModelItem::data(column, role);
98     return variant;
99 }
100
101 QVariant ChatLineModelItem::timestampData(int role) const
102 {
103     switch (role) {
104     case ChatLineModel::DisplayRole:
105         return _styledMsg.decoratedTimestamp();
106     case ChatLineModel::EditRole:
107         return _styledMsg.timestamp();
108     case ChatLineModel::BackgroundRole:
109         return backgroundBrush(UiStyle::FormatType::Timestamp);
110     case ChatLineModel::SelectedBackgroundRole:
111         return backgroundBrush(UiStyle::FormatType::Timestamp, true);
112     case ChatLineModel::FormatRole:
113         return QVariant::fromValue(UiStyle::FormatList{
114             std::make_pair(quint16{0}, UiStyle::Format{UiStyle::formatType(_styledMsg.type()) | UiStyle::FormatType::Timestamp, {}, {}})});
115     }
116     return QVariant();
117 }
118
119 QVariant ChatLineModelItem::senderData(int role) const
120 {
121     switch (role) {
122     case ChatLineModel::DisplayRole:
123         return _styledMsg.decoratedSender();
124     case ChatLineModel::EditRole:
125         return _styledMsg.plainSender();
126     case ChatLineModel::BackgroundRole:
127         return backgroundBrush(UiStyle::FormatType::Sender);
128     case ChatLineModel::SelectedBackgroundRole:
129         return backgroundBrush(UiStyle::FormatType::Sender, true);
130     case ChatLineModel::FormatRole:
131         return QVariant::fromValue(UiStyle::FormatList{
132             std::make_pair(quint16{0}, UiStyle::Format{UiStyle::formatType(_styledMsg.type()) | UiStyle::FormatType::Sender, {}, {}})});
133     }
134     return QVariant();
135 }
136
137 QVariant ChatLineModelItem::contentsData(int role) const
138 {
139     switch (role) {
140     case ChatLineModel::DisplayRole:
141     case ChatLineModel::EditRole:
142         return _styledMsg.plainContents();
143     case ChatLineModel::BackgroundRole:
144         return backgroundBrush(UiStyle::FormatType::Contents);
145     case ChatLineModel::SelectedBackgroundRole:
146         return backgroundBrush(UiStyle::FormatType::Contents, true);
147     case ChatLineModel::FormatRole:
148         return QVariant::fromValue(_styledMsg.contentsFormatList());
149     case ChatLineModel::WrapListRole:
150         if (_wrapList.isEmpty())
151             computeWrapList();
152         return QVariant::fromValue(_wrapList);
153     }
154     return QVariant();
155 }
156
157 UiStyle::MessageLabel ChatLineModelItem::messageLabel() const
158 {
159     using MessageLabel = UiStyle::MessageLabel;
160
161     auto label = static_cast<MessageLabel>(_styledMsg.senderHash() << 16);
162     if (_styledMsg.flags() & Message::Self)
163         label |= MessageLabel::OwnMsg;
164     if (_styledMsg.flags() & Message::Highlight)
165         label |= MessageLabel::Highlight;
166     return label;
167 }
168
169 QVariant ChatLineModelItem::backgroundBrush(UiStyle::FormatType subelement, bool selected) const
170 {
171     QTextCharFormat fmt = QtUi::style()->format({UiStyle::formatType(_styledMsg.type()) | subelement, {}, {}},
172                                                 messageLabel() | (selected ? UiStyle::MessageLabel::Selected : UiStyle::MessageLabel::None));
173     if (fmt.hasProperty(QTextFormat::BackgroundBrush))
174         return QVariant::fromValue(fmt.background());
175     return QVariant();
176 }
177
178 void ChatLineModelItem::computeWrapList() const
179 {
180     QString text = _styledMsg.plainContents();
181     int length = text.length();
182     if (!length)
183         return;
184
185     QList<ChatLineModel::Word> wplist;  // use a temp list which we'll later copy into a QVector for efficiency
186     QTextBoundaryFinder finder(QTextBoundaryFinder::Line,
187                                _styledMsg.plainContents().unicode(),
188                                length,
189                                TextBoundaryFinderBuffer,
190                                TextBoundaryFinderBufferSize);
191
192     int idx;
193     int oldidx = 0;
194     ChatLineModel::Word word;
195     word.start = 0;
196     qreal wordstartx = 0;
197
198     QTextLayout layout(_styledMsg.plainContents());
199     QTextOption option;
200     option.setWrapMode(QTextOption::NoWrap);
201     layout.setTextOption(option);
202
203     UiStyle::setTextLayoutFormats(layout, QtUi::style()->toTextLayoutList(_styledMsg.contentsFormatList(), length, messageLabel()));
204     layout.beginLayout();
205     QTextLine line = layout.createLine();
206     line.setNumColumns(length);
207     layout.endLayout();
208
209     while ((idx = finder.toNextBoundary()) >= 0 && idx <= length) {
210         // QTextBoundaryFinder has inconsistent behavior in Qt version up to and including 4.6.3 (at least).
211         // It doesn't point to the position we should break, but to the character before that.
212         // Unfortunately Qt decided to fix this by changing the behavior of QTBF, so now we have to add a version
213         // check. At the time of this writing, I'm still trying to get this reverted upstream...
214         //
215         // cf. https://bugs.webkit.org/show_bug.cgi?id=31076 and Qt commit e6ac173
216         static int needWorkaround = -1;
217         if (needWorkaround < 0) {
218             needWorkaround = 0;
219             QStringList versions = QString(qVersion()).split('.');
220             if (versions.count() == 3 && versions.at(0).toInt() == 4) {
221                 if (versions.at(1).toInt() <= 6 && versions.at(2).toInt() <= 3)
222                     needWorkaround = 1;
223             }
224         }
225         if (needWorkaround == 1) {
226             if (idx < length)
227                 idx++;
228         }
229
230         if (idx == oldidx)
231             continue;
232
233         word.start = oldidx;
234         int wordend = idx;
235         for (; wordend > word.start; wordend--) {
236             if (!text.at(wordend - 1).isSpace())
237                 break;
238         }
239
240         qreal wordendx = line.cursorToX(wordend);
241         qreal trailingendx = line.cursorToX(idx);
242         word.endX = wordendx;
243         word.width = wordendx - wordstartx;
244         word.trailing = trailingendx - wordendx;
245         wordstartx = trailingendx;
246         wplist.append(word);
247
248         oldidx = idx;
249     }
250
251     // A QVector needs less space than a QList
252     _wrapList.resize(wplist.count());
253     for (int i = 0; i < wplist.count(); i++) {
254         _wrapList[i] = wplist.at(i);
255     }
256 }