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