uistyle: Support reverse color rendering
[quassel.git] / src / uisupport / uistyle.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 <utility>
22 #include <vector>
23
24 #include <QApplication>
25 #include <QColor>
26 #include <QIcon>
27
28 #include "buffersettings.h"
29 #include "qssparser.h"
30 #include "quassel.h"
31 #include "uistyle.h"
32 #include "uisettings.h"
33 #include "util.h"
34
35 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
36 bool UiStyle::_useCustomTimestampFormat;       /// If true, use the custom timestamp format
37 QString UiStyle::_timestampFormatString;       /// Timestamp format
38 QString UiStyle::_systemTimestampFormatString; /// Cached copy of system locale timestamp format
39 bool UiStyle::_showSenderPrefixes;             /// If true, show prefixmodes before sender names
40 bool UiStyle::_showSenderBrackets;             /// If true, show brackets around sender names
41
42 namespace {
43
44 // Extended mIRC colors as defined in https://modern.ircdocs.horse/formatting.html#colors-16-98
45 QColor extendedMircColor(int number)
46 {
47     static const std::vector<QColor> colorMap = {
48         "#470000", "#472100", "#474700", "#324700", "#004700", "#00472c", "#004747", "#002747", "#000047", "#2e0047", "#470047", "#47002a",
49         "#740000", "#743a00", "#747400", "#517400", "#007400", "#007449", "#007474", "#004074", "#000074", "#4b0074", "#740074", "#740045",
50         "#b50000", "#b56300", "#b5b500", "#7db500", "#00b500", "#00b571", "#00b5b5", "#0063b5", "#0000b5", "#7500b5", "#b500b5", "#b5006b",
51         "#ff0000", "#ff8c00", "#ffff00", "#b2ff00", "#00ff00", "#00ffa0", "#00ffff", "#008cff", "#0000ff", "#a500ff", "#ff00ff", "#ff0098",
52         "#ff5959", "#ffb459", "#ffff71", "#cfff60", "#6fff6f", "#65ffc9", "#6dffff", "#59b4ff", "#5959ff", "#c459ff", "#ff66ff", "#ff59bc",
53         "#ff9c9c", "#ffd39c", "#ffff9c", "#e2ff9c", "#9cff9c", "#9cffdb", "#9cffff", "#9cd3ff", "#9c9cff", "#dc9cff", "#ff9cff", "#ff94d3",
54         "#000000", "#131313", "#282828", "#363636", "#4d4d4d", "#656565", "#818181", "#9f9f9f", "#bcbcbc", "#e2e2e2", "#ffffff"
55     };
56     if (number < 16)
57         return {};
58     size_t index = number - 16;
59     return (index < colorMap.size() ? colorMap[index] : QColor{});
60 }
61
62 }
63
64 UiStyle::UiStyle(QObject *parent)
65     : QObject(parent),
66     _channelJoinedIcon(QIcon::fromTheme("irc-channel-joined", QIcon(":/icons/irc-channel-joined.png"))),
67     _channelPartedIcon(QIcon::fromTheme("irc-channel-parted", QIcon(":/icons/irc-channel-parted.png"))),
68     _userOfflineIcon(QIcon::fromTheme("im-user-offline", QIcon::fromTheme("user-offline", QIcon(":/icons/im-user-offline.png")))),
69     _userOnlineIcon(QIcon::fromTheme("im-user", QIcon::fromTheme("user-available", QIcon(":/icons/im-user.png")))), // im-user-* are non-standard oxygen extensions
70     _userAwayIcon(QIcon::fromTheme("im-user-away", QIcon::fromTheme("user-away", QIcon(":/icons/im-user-away.png")))),
71     _categoryOpIcon(QIcon::fromTheme("irc-operator")),
72     _categoryVoiceIcon(QIcon::fromTheme("irc-voice")),
73     _opIconLimit(UserCategoryItem::categoryFromModes("o")),
74     _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
75 {
76     static bool registered = []() {
77         qRegisterMetaType<FormatList>();
78         qRegisterMetaTypeStreamOperators<FormatList>();
79         return true;
80     }();
81     Q_UNUSED(registered)
82
83     _uiStylePalette = QVector<QBrush>(static_cast<int>(ColorRole::NumRoles), QBrush());
84
85     // Now initialize the mapping between FormatCodes and FormatTypes...
86     _formatCodes["%O"] = FormatType::Base;
87     _formatCodes["%B"] = FormatType::Bold;
88     _formatCodes["%S"] = FormatType::Italic;
89     _formatCodes["%U"] = FormatType::Underline;
90
91     _formatCodes["%DN"] = FormatType::Nick;
92     _formatCodes["%DH"] = FormatType::Hostmask;
93     _formatCodes["%DC"] = FormatType::ChannelName;
94     _formatCodes["%DM"] = FormatType::ModeFlags;
95     _formatCodes["%DU"] = FormatType::Url;
96
97     // Initialize fallback defaults
98     // NOTE: If you change this, update qtui/chatviewsettings.h, too.  More explanations available
99     // in there.
100     setUseCustomTimestampFormat(false);
101     setTimestampFormatString(" hh:mm:ss");
102     enableSenderPrefixes(false);
103     enableSenderBrackets(true);
104
105     // BufferView / NickView settings
106     UiStyleSettings s;
107     _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
108     s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
109
110     _allowMircColors = s.value("AllowMircColors", true).toBool();
111     s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
112
113     loadStyleSheet();
114 }
115
116
117 UiStyle::~UiStyle()
118 {
119     qDeleteAll(_metricsCache);
120 }
121
122
123 void UiStyle::reload()
124 {
125     loadStyleSheet();
126 }
127
128
129 void UiStyle::loadStyleSheet()
130 {
131     qDeleteAll(_metricsCache);
132     _metricsCache.clear();
133     _formatCache.clear();
134     _formats.clear();
135
136     UiStyleSettings s;
137
138     QString styleSheet;
139     styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
140     styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
141     if (s.value("UseCustomStyleSheet", false).toBool()) {
142         QString customSheetPath(s.value("CustomStyleSheetPath").toString());
143         QString customSheet = loadStyleSheet("file:///" + customSheetPath, true);
144         if (customSheet.isEmpty()) {
145             // MIGRATION: changed default install path for data from /usr/share/apps to /usr/share
146             if (customSheetPath.startsWith("/usr/share/apps/quassel")) {
147                 customSheetPath.replace(QRegExp("^/usr/share/apps"), "/usr/share");
148                 customSheet = loadStyleSheet("file:///" + customSheetPath, true);
149                 if (!customSheet.isEmpty()) {
150                     s.setValue("CustomStyleSheetPath", customSheetPath);
151                     qDebug() << "Custom stylesheet path migrated to" << customSheetPath;
152                 }
153             }
154         }
155         styleSheet += customSheet;
156     }
157     styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
158
159     if (!styleSheet.isEmpty()) {
160         QssParser parser;
161         parser.processStyleSheet(styleSheet);
162         QApplication::setPalette(parser.palette());
163
164         _uiStylePalette = parser.uiStylePalette();
165         _formats = parser.formats();
166         _listItemFormats = parser.listItemFormats();
167
168         styleSheet = styleSheet.trimmed();
169         if (!styleSheet.isEmpty())
170             qApp->setStyleSheet(styleSheet);  // pass the remaining sections to the application
171     }
172
173     emit changed();
174 }
175
176
177 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
178 {
179     QString ss = styleSheet;
180     if (ss.startsWith("file:///")) {
181         ss.remove(0, 8);
182         if (ss.isEmpty())
183             return QString();
184
185         QFile file(ss);
186         if (file.open(QFile::ReadOnly)) {
187             QTextStream stream(&file);
188             ss = stream.readAll();
189             file.close();
190         }
191         else {
192             if (shouldExist)
193                 qWarning() << "Could not open stylesheet file:" << file.fileName();
194             return QString();
195         }
196     }
197     return ss;
198 }
199
200
201 void UiStyle::updateSystemTimestampFormat()
202 {
203     // Does the system locale use AM/PM designators?  For example:
204     // AM/PM:    h:mm AP
205     // AM/PM:    hh:mm a
206     // 24-hour:  h:mm
207     // 24-hour:  hh:mm ADD things
208     // For timestamp format, see https://doc.qt.io/qt-5/qdatetime.html#toString
209     // This won't update if the system locale is changed while Quassel is running.  If need be,
210     // Quassel could hook into notifications of changing system locale to update this.
211     //
212     // Match any AP or A designation if on a word boundary, including underscores.
213     //   .*(\b|_)(A|AP)(\b|_).*
214     //   .*         Match any number of characters
215     //   \b         Match a word boundary, i.e. "AAA.BBB", "." is matched
216     //   _          Match the literal character '_' (not considered a word boundary)
217     //   (X|Y)  Match either X or Y, exactly
218     //
219     // Note that '\' must be escaped as '\\'
220     // QRegExp does not support (?> ...), so it's replaced with standard matching, (...)
221     // Helpful interactive website for debugging and explaining:  https://regex101.com/
222     const QRegExp regExpMatchAMPM(".*(\\b|_)(A|AP)(\\b|_).*", Qt::CaseInsensitive);
223
224     if (regExpMatchAMPM.exactMatch(QLocale::system().timeFormat(QLocale::ShortFormat))) {
225         // AM/PM style used
226         _systemTimestampFormatString = " h:mm:ss ap";
227     } else {
228         // 24-hour style used
229         _systemTimestampFormatString = " hh:mm:ss";
230     }
231     // Include a space to give the timestamp a small bit of padding between the border of the chat
232     // buffer window and the numbers.  Helps with readability.
233     // If you change this to include brackets, e.g. "[hh:mm:ss]", also update
234     // ChatScene::updateTimestampHasBrackets() to true or false as needed!
235 }
236
237
238 // FIXME The following should trigger a reload/refresh of the chat view.
239 void UiStyle::setUseCustomTimestampFormat(bool enabled)
240 {
241     if (_useCustomTimestampFormat != enabled) {
242         _useCustomTimestampFormat = enabled;
243     }
244 }
245
246 void UiStyle::setTimestampFormatString(const QString &format)
247 {
248     if (_timestampFormatString != format) {
249         _timestampFormatString = format;
250     }
251 }
252
253 void UiStyle::enableSenderPrefixes(bool enabled)
254 {
255     if (_showSenderPrefixes != enabled) {
256         _showSenderPrefixes = enabled;
257     }
258 }
259
260 void UiStyle::enableSenderBrackets(bool enabled)
261 {
262     if (_showSenderBrackets != enabled) {
263         _showSenderBrackets = enabled;
264     }
265 }
266
267
268 void UiStyle::allowMircColorsChanged(const QVariant &v)
269 {
270     _allowMircColors = v.toBool();
271     emit changed();
272 }
273
274
275 /******** ItemView Styling *******/
276
277 void UiStyle::showItemViewIconsChanged(const QVariant &v)
278 {
279     _showBufferViewIcons = _showNickViewIcons = v.toBool();
280 }
281
282
283 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
284 {
285     BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
286     bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
287
288     if (role == Qt::DecorationRole) {
289         if (!_showBufferViewIcons)
290             return QVariant();
291
292         switch (type) {
293         case BufferInfo::ChannelBuffer:
294             if (isActive)
295                 return _channelJoinedIcon;
296             else
297                 return _channelPartedIcon;
298         case BufferInfo::QueryBuffer:
299             if (!isActive)
300                 return _userOfflineIcon;
301             if (index.data(NetworkModel::UserAwayRole).toBool())
302                 return _userAwayIcon;
303             else
304                 return _userOnlineIcon;
305         default:
306             return QVariant();
307         }
308     }
309
310     ItemFormatType fmtType = ItemFormatType::BufferViewItem;
311     switch (type) {
312     case BufferInfo::StatusBuffer:
313         fmtType |= ItemFormatType::NetworkItem;
314         break;
315     case BufferInfo::ChannelBuffer:
316         fmtType |= ItemFormatType::ChannelBufferItem;
317         break;
318     case BufferInfo::QueryBuffer:
319         fmtType |= ItemFormatType::QueryBufferItem;
320         break;
321     default:
322         return QVariant();
323     }
324
325     QTextCharFormat fmt = _listItemFormats.value(ItemFormatType::BufferViewItem);
326     fmt.merge(_listItemFormats.value(fmtType));
327
328     BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
329     if (activity & BufferInfo::Highlight) {
330         fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::HighlightedBuffer));
331         fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::HighlightedBuffer));
332     }
333     else if (activity & BufferInfo::NewMessage) {
334         fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::UnreadBuffer));
335         fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::UnreadBuffer));
336     }
337     else if (activity & BufferInfo::OtherActivity) {
338         fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::ActiveBuffer));
339         fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::ActiveBuffer));
340     }
341     else if (!isActive) {
342         fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::InactiveBuffer));
343         fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::InactiveBuffer));
344     }
345     else if (index.data(NetworkModel::UserAwayRole).toBool()) {
346         fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::UserAway));
347         fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::UserAway));
348     }
349
350     return itemData(role, fmt);
351 }
352
353
354 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
355 {
356     NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
357
358     if (role == Qt::DecorationRole) {
359         if (!_showNickViewIcons)
360             return QVariant();
361
362         switch (type) {
363         case NetworkModel::UserCategoryItemType:
364         {
365             int categoryId = index.data(TreeModel::SortRole).toInt();
366             if (categoryId <= _opIconLimit)
367                 return _categoryOpIcon;
368             if (categoryId <= _voiceIconLimit)
369                 return _categoryVoiceIcon;
370             return _userOnlineIcon;
371         }
372         case NetworkModel::IrcUserItemType:
373             if (index.data(NetworkModel::ItemActiveRole).toBool())
374                 return _userOnlineIcon;
375             else
376                 return _userAwayIcon;
377         default:
378             return QVariant();
379         }
380     }
381
382     QTextCharFormat fmt = _listItemFormats.value(ItemFormatType::NickViewItem);
383
384     switch (type) {
385     case NetworkModel::IrcUserItemType:
386         fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::IrcUserItem));
387         if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
388             fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::UserAway));
389             fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::IrcUserItem | ItemFormatType::UserAway));
390         }
391         break;
392     case NetworkModel::UserCategoryItemType:
393         fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::UserCategoryItem));
394         break;
395     default:
396         return QVariant();
397     }
398
399     return itemData(role, fmt);
400 }
401
402
403 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
404 {
405     switch (role) {
406     case Qt::FontRole:
407         return format.font();
408     case Qt::ForegroundRole:
409         return format.property(QTextFormat::ForegroundBrush);
410     case Qt::BackgroundRole:
411         return format.property(QTextFormat::BackgroundBrush);
412     default:
413         return QVariant();
414     }
415 }
416
417
418 /******** Caching *******/
419
420 QTextCharFormat UiStyle::parsedFormat(quint64 key) const
421 {
422     return _formats.value(key, QTextCharFormat());
423 }
424
425 namespace {
426
427 // Create unique key for given Format object and message label
428 QString formatKey(const UiStyle::Format &format, UiStyle::MessageLabel label)
429 {
430     return QString::number(format.type | label, 16)
431             + (format.foreground.isValid() ? format.foreground.name() : "#------")
432             + (format.background.isValid() ? format.background.name() : "#------");
433 }
434
435 }
436
437 QTextCharFormat UiStyle::cachedFormat(const Format &format, MessageLabel messageLabel) const
438 {
439     return _formatCache.value(formatKey(format, messageLabel), QTextCharFormat());
440 }
441
442
443 void UiStyle::setCachedFormat(const QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const
444 {
445     _formatCache[formatKey(format, messageLabel)] = charFormat;
446 }
447
448
449 QFontMetricsF *UiStyle::fontMetrics(FormatType ftype, MessageLabel label) const
450 {
451     // QFontMetricsF is not assignable, so we need to store pointers :/
452     quint64 key = ftype | label;
453
454     if (_metricsCache.contains(key))
455         return _metricsCache.value(key);
456
457     return (_metricsCache[key] = new QFontMetricsF(format({ftype, {}, {}}, label).font()));
458 }
459
460
461 /******** Generate formats ********/
462
463 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
464 //       until you _really_ know what you do!
465 QTextCharFormat UiStyle::format(const Format &format, MessageLabel label) const
466 {
467     if (format.type == FormatType::Invalid)
468         return {};
469
470     // Check if we have exactly this format readily cached already
471     QTextCharFormat charFormat = cachedFormat(format, label);
472     if (charFormat.properties().count())
473         return charFormat;
474
475     // Merge all formats except mIRC and extended colors
476     mergeFormat(charFormat, format, label & 0xffff0000);  // keep nickhash in label
477     for (quint32 mask = 0x00000001; mask <= static_cast<quint32>(MessageLabel::Selected); mask <<= 1) {
478         if (static_cast<quint32>(label) & mask) {
479             mergeFormat(charFormat, format, label & (mask | 0xffff0000));
480         }
481     }
482
483     // Merge mIRC and extended colors, if appropriate. These override any color set previously in the format,
484     // unless the AllowForegroundOverride or AllowBackgroundOverride properties are set (via stylesheet).
485     if (_allowMircColors) {
486         mergeColors(charFormat, format, MessageLabel::None);
487         for (quint32 mask = 0x00000001; mask <= static_cast<quint32>(MessageLabel::Selected); mask <<= 1) {
488             if (static_cast<quint32>(label) & mask) {
489                 mergeColors(charFormat, format, label & mask);
490             }
491         }
492     }
493
494     setCachedFormat(charFormat, format, label);
495     return charFormat;
496 }
497
498
499 void UiStyle::mergeFormat(QTextCharFormat &charFormat, const Format &format, MessageLabel label) const
500 {
501     mergeSubElementFormat(charFormat, format.type & 0x00ff, label);
502
503     // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
504     //       or "foreground 01 and background 03"
505     if ((format.type & 0xfff00) != FormatType::Base) { // element format
506         for (quint32 mask = 0x00100; mask <= 0x80000; mask <<= 1) {
507             if ((format.type & mask) != FormatType::Base) {
508                 mergeSubElementFormat(charFormat, format.type & (mask | 0xff), label);
509             }
510         }
511     }
512 }
513
514
515 // Merge a subelement format into an existing message format
516 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, FormatType ftype, MessageLabel label) const
517 {
518     quint64 key = ftype | label;
519     fmt.merge(parsedFormat(key & 0x0000ffffffffff00ull)); // label + subelement
520     fmt.merge(parsedFormat(key & 0x0000ffffffffffffull)); // label + subelement + msgtype
521     fmt.merge(parsedFormat(key & 0xffffffffffffff00ull)); // label + subelement + nickhash
522     fmt.merge(parsedFormat(key & 0xffffffffffffffffull)); // label + subelement + nickhash + msgtype
523 }
524
525
526 void UiStyle::mergeColors(QTextCharFormat &charFormat, const Format &format, MessageLabel label) const
527 {
528     bool allowFg = charFormat.property(static_cast<int>(FormatProperty::AllowForegroundOverride)).toBool();
529     bool allowBg = charFormat.property(static_cast<int>(FormatProperty::AllowBackgroundOverride)).toBool();
530
531     // Classic mIRC colors (styleable)
532     // We assume that those can't be combined with subelement and message types.
533     if (allowFg && (format.type & 0x00400000) != FormatType::Base)
534         charFormat.merge(parsedFormat((format.type & 0x0f400000) | label));  // foreground
535     if (allowBg && (format.type & 0x00800000) != FormatType::Base)
536         charFormat.merge(parsedFormat((format.type & 0xf0800000) | label));  // background
537     if (allowFg && allowBg && (format.type & 0x00c00000) == static_cast<FormatType>(0x00c00000))
538         charFormat.merge(parsedFormat((format.type & 0xffc00000) | label));  // combination
539
540     // Extended mIRC colors (hardcoded)
541     if (allowFg && format.foreground.isValid())
542         charFormat.setForeground(format.foreground);
543     if (allowBg && format.background.isValid())
544         charFormat.setBackground(format.background);
545 }
546
547
548 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
549 {
550     switch (msgType) {
551     case Message::Plain:
552         return FormatType::PlainMsg;
553     case Message::Notice:
554         return FormatType::NoticeMsg;
555     case Message::Action:
556         return FormatType::ActionMsg;
557     case Message::Nick:
558         return FormatType::NickMsg;
559     case Message::Mode:
560         return FormatType::ModeMsg;
561     case Message::Join:
562         return FormatType::JoinMsg;
563     case Message::Part:
564         return FormatType::PartMsg;
565     case Message::Quit:
566         return FormatType::QuitMsg;
567     case Message::Kick:
568         return FormatType::KickMsg;
569     case Message::Kill:
570         return FormatType::KillMsg;
571     case Message::Server:
572         return FormatType::ServerMsg;
573     case Message::Info:
574         return FormatType::InfoMsg;
575     case Message::Error:
576         return FormatType::ErrorMsg;
577     case Message::DayChange:
578         return FormatType::DayChangeMsg;
579     case Message::Topic:
580         return FormatType::TopicMsg;
581     case Message::NetsplitJoin:
582         return FormatType::NetsplitJoinMsg;
583     case Message::NetsplitQuit:
584         return FormatType::NetsplitQuitMsg;
585     case Message::Invite:
586         return FormatType::InviteMsg;
587     }
588     //Q_ASSERT(false); // we need to handle all message types
589     qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
590     return FormatType::ErrorMsg;
591 }
592
593
594 UiStyle::FormatType UiStyle::formatType(const QString &code)
595 {
596     if (_formatCodes.contains(code))
597         return _formatCodes.value(code);
598     return FormatType::Invalid;
599 }
600
601
602 QString UiStyle::formatCode(FormatType ftype)
603 {
604     return _formatCodes.key(ftype);
605 }
606
607
608 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, MessageLabel messageLabel) const
609 {
610     QList<QTextLayout::FormatRange> formatRanges;
611     QTextLayout::FormatRange range;
612     size_t i = 0;
613     for (i = 0; i < formatList.size(); i++) {
614         range.format = format(formatList.at(i).second, messageLabel);
615         range.start = formatList.at(i).first;
616         if (i > 0)
617             formatRanges.last().length = range.start - formatRanges.last().start;
618         formatRanges.append(range);
619     }
620     if (i > 0)
621         formatRanges.last().length = textLength - formatRanges.last().start;
622     return formatRanges;
623 }
624
625
626 // This method expects a well-formatted string, there is no error checking!
627 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
628 UiStyle::StyledString UiStyle::styleString(const QString &s_, FormatType baseFormat)
629 {
630     QString s = s_;
631     StyledString result;
632     result.formatList.emplace_back(std::make_pair(quint16{0}, Format{baseFormat, {}, {}}));
633
634     if (s.length() > 65535) {
635         // We use quint16 for indexes
636         qWarning() << QString("String too long to be styled: %1").arg(s);
637         result.plainText = s;
638         return result;
639     }
640
641     Format curfmt{baseFormat, {}, {}};
642     QChar fgChar{'f'}; // character to indicate foreground color, changed when reversing
643
644     int pos = 0; quint16 length = 0;
645     for (;;) {
646         pos = s.indexOf('%', pos);
647         if (pos < 0) break;
648         if (s[pos+1] == '%') { // escaped %, we just remove one and continue
649             s.remove(pos, 1);
650             pos++;
651             continue;
652         }
653         if (s[pos+1] == 'D' && s[pos+2] == 'c') { // mIRC color code
654             if (s[pos+3] == '-') { // color off
655                 curfmt.type &= 0x003fffff;
656                 curfmt.foreground = QColor{};
657                 curfmt.background = QColor{};
658                 length = 4;
659             }
660             else {
661                 quint32 color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
662                 // Color values 0-15 are traditional mIRC colors, defined in the stylesheet and thus going through the format engine
663                 // Larger color values are hardcoded and applied separately (cf. https://modern.ircdocs.horse/formatting.html#colors-16-98)
664                 if (s[pos+3] == fgChar) {
665                     if (color < 16) {
666                         // Traditional mIRC color, defined in the stylesheet
667                         curfmt.type &= 0xf0ffffff;
668                         curfmt.type |= color << 24 | 0x00400000;
669                         curfmt.foreground = QColor{};
670                     }
671                     else {
672                         curfmt.type &= 0xf0bfffff;  // mask out traditional foreground color
673                         curfmt.foreground = extendedMircColor(color);
674                     }
675                 }
676                 else {
677                     if (color < 16) {
678                         curfmt.type &= 0x0fffffff;
679                         curfmt.type |= color << 28 | 0x00800000;
680                         curfmt.background = QColor{};
681                     }
682                     else {
683                         curfmt.type &= 0x0f7fffff;  // mask out traditional background color
684                         curfmt.background = extendedMircColor(color);
685                     }
686                 }
687                 length = 6;
688             }
689         }
690         else if (s[pos+1] == 'D' && s[pos+2] == 'h') { // Hex color
691             QColor color{s.mid(pos+4, 7)};
692             if (s[pos+3] == fgChar) {
693                 curfmt.type &= 0xf0bfffff;  // mask out mIRC foreground color
694                 curfmt.foreground = std::move(color);
695             }
696             else {
697                 curfmt.type &= 0x0f7fffff;  // mask out mIRC background color
698                 curfmt.background = std::move(color);
699             }
700             length = 11;
701         }
702         else if (s[pos+1] == 'O') { // reset formatting
703             curfmt.type &= 0x000000ff; // we keep message type-specific formatting
704             curfmt.foreground = QColor{};
705             curfmt.background = QColor{};
706             fgChar = 'f';
707             length = 2;
708         }
709         else if (s[pos+1] == 'R') { // Reverse colors
710             fgChar = (fgChar == 'f' ? 'b' : 'f');
711             quint32 orig = static_cast<quint32>(curfmt.type & 0xffc00000);
712             curfmt.type &= 0x003fffff;
713             curfmt.type |= (orig & 0x00400000) <<1;
714             curfmt.type |= (orig & 0x0f000000) <<4;
715             curfmt.type |= (orig & 0x00800000) >>1;
716             curfmt.type |= (orig & 0xf0000000) >>4;
717             std::swap(curfmt.foreground, curfmt.background);
718             length = 2;
719         }
720         else { // all others are toggles
721             QString code = QString("%") + s[pos+1];
722             if (s[pos+1] == 'D') code += s[pos+2];
723             FormatType ftype = formatType(code);
724             if (ftype == FormatType::Invalid) {
725                 pos++;
726                 qWarning() << (QString("Invalid format code in string: %1").arg(s));
727                 continue;
728             }
729             curfmt.type ^= ftype;
730             length = code.length();
731         }
732         s.remove(pos, length);
733         if (pos == result.formatList.back().first)
734             result.formatList.back().second = curfmt;
735         else
736             result.formatList.emplace_back(std::make_pair(pos, curfmt));
737     }
738     result.plainText = s;
739     return result;
740 }
741
742
743 QString UiStyle::mircToInternal(const QString &mirc_)
744 {
745     QString mirc;
746     mirc.reserve(mirc_.size());
747     foreach (const QChar &c, mirc_) {
748         if ((c < '\x20' || c == '\x7f') && c != '\x03' && c != '\x04') {
749             switch (c.unicode()) {
750                 case '\x02':
751                     mirc += "%B";
752                     break;
753                 case '\x0f':
754                     mirc += "%O";
755                     break;
756                 case '\x09':
757                     mirc += "        ";
758                     break;
759                 case '\x12':
760                 case '\x16':
761                     mirc += "%R";
762                     break;
763                 case '\x1d':
764                     mirc += "%S";
765                     break;
766                 case '\x1f':
767                     mirc += "%U";
768                     break;
769                 case '\x7f':
770                     mirc += QChar(0x2421);
771                     break;
772                 default:
773                     mirc += QChar(0x2400 + c.unicode());
774             }
775         } else {
776             if (c == '%')
777                 mirc += c;
778             mirc += c;
779         }
780     }
781
782     // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
783     // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
784     // %Dc- turns color off.
785     // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
786     //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
787     {
788         int pos = 0;
789         while (true) {
790             pos = mirc.indexOf('\x03', pos);
791             if (pos < 0)
792                 break;  // no more mirc color codes
793             QString ins, num;
794             int l = mirc.length();
795             int i = pos + 1;
796             // check for fg color
797             if (i < l && mirc[i].isDigit()) {
798                 num = mirc[i++];
799                 if (i < l && mirc[i].isDigit())
800                     num.append(mirc[i++]);
801                 else
802                     num.prepend('0');
803                 ins = QString("%Dcf%1").arg(num);
804
805                 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
806                     i++;
807                     num = mirc[i++];
808                     if (i < l && mirc[i].isDigit())
809                         num.append(mirc[i++]);
810                     else
811                         num.prepend('0');
812                     ins += QString("%Dcb%1").arg(num);
813                 }
814             }
815             else {
816                 ins = "%Dc-";
817             }
818             mirc.replace(pos, i-pos, ins);
819         }
820     }
821
822     // Hex colors, as specified in https://modern.ircdocs.horse/formatting.html#hex-color
823     // %Dhf#rrggbb is foreground, %Dhb#rrggbb is background
824     {
825         static const QRegExp rx{"[\\da-fA-F]{6}"};
826         int pos = 0;
827         while (true) {
828             if (pos >= mirc.length())
829                 break;
830             pos = mirc.indexOf('\x04', pos);
831             if (pos < 0)
832                 break;
833             int i = pos + 1;
834             QString ins;
835             auto num = mirc.mid(i, 6);
836             if (!num.isEmpty() && rx.exactMatch(num)) {
837                 ins = "%Dhf#" + num.toLower();
838                 i += 6;
839                 if (i < mirc.length() && mirc[i] == ',' && !(num = mirc.mid(i + 1, 6)).isEmpty() && rx.exactMatch(num)) {
840                     ins += "%Dhb#" + num.toLower();
841                     i += 7;
842                 }
843             }
844             else {
845                 ins = "%Dc-";
846             }
847             mirc.replace(pos, i - pos, ins);
848             pos += ins.length();
849         }
850     }
851
852     return mirc;
853 }
854
855
856 QString UiStyle::systemTimestampFormatString()
857 {
858     if (_systemTimestampFormatString.isEmpty()) {
859         // Calculate and cache the system timestamp format string
860         updateSystemTimestampFormat();
861     }
862     return _systemTimestampFormatString;
863 }
864
865
866 QString UiStyle::timestampFormatString()
867 {
868     if (useCustomTimestampFormat()) {
869         return _timestampFormatString;
870     } else {
871         return systemTimestampFormatString();
872     }
873 }
874
875
876 /***********************************************************************************/
877 UiStyle::StyledMessage::StyledMessage(const Message &msg)
878     : Message(msg)
879 {
880     switch (type()) {
881         // Don't compute the sender hash for message types without a nickname embedded
882         case Message::Server:
883         case Message::Info:
884         case Message::Error:
885         case Message::DayChange:
886         case Message::Topic:
887         case Message::Invite:
888         // Don't compute the sender hash for messages with multiple nicks
889         // Fixing this without breaking themes would be.. complex.
890         case Message::NetsplitJoin:
891         case Message::NetsplitQuit:
892         case Message::Kick:
893         // Don't compute the sender hash for message types that are not yet completed elsewhere
894         case Message::Kill:
895             _senderHash = 0x00;
896             break;
897         default:
898             // Compute the sender hash for all other message types
899             _senderHash = 0xff;
900             break;
901     }
902 }
903
904
905 void UiStyle::StyledMessage::style() const
906 {
907     QString user = userFromMask(sender());
908     QString host = hostFromMask(sender());
909     QString nick = nickFromMask(sender());
910     QString txt = UiStyle::mircToInternal(contents());
911     QString bufferName = bufferInfo().bufferName();
912     bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
913     host.replace('%', "%%");     // hostnames too...
914     user.replace('%', "%%");     // and the username...
915     nick.replace('%', "%%");     // ... and then there's totally RFC-violating servers like justin.tv m(
916     const int maxNetsplitNicks = 15;
917
918     QString t;
919     switch (type()) {
920     case Message::Plain:
921         t = QString("%1").arg(txt); break;
922     case Message::Notice:
923         t = QString("%1").arg(txt); break;
924     case Message::Action:
925         t = QString("%DN%1%DN %2").arg(nick).arg(txt);
926         break;
927     case Message::Nick:
928         //: Nick Message
929         if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
930         else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
931         break;
932     case Message::Mode:
933         //: Mode Message
934         if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
935         else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
936         break;
937     case Message::Join:
938         //: Join Message
939         t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
940     case Message::Part:
941         //: Part Message
942         t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
943         if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
944         break;
945     case Message::Quit:
946         //: Quit Message
947         t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
948         if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
949         break;
950     case Message::Kick:
951     {
952         QString victim = txt.section(" ", 0, 0);
953         QString kickmsg = txt.section(" ", 1);
954         //: Kick Message
955         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
956         if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
957     }
958     break;
959     //case Message::Kill: FIXME
960
961     case Message::Server:
962         t = QString("%1").arg(txt); break;
963     case Message::Info:
964         t = QString("%1").arg(txt); break;
965     case Message::Error:
966         t = QString("%1").arg(txt); break;
967     case Message::DayChange:
968     {
969         //: Day Change Message
970         t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
971     }
972         break;
973     case Message::Topic:
974         t = QString("%1").arg(txt); break;
975     case Message::NetsplitJoin:
976     {
977         QStringList users = txt.split("#:#");
978         QStringList servers = users.takeLast().split(" ");
979
980         for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
981             users[i] = nickFromMask(users.at(i));
982
983         t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
984         if (users.count() <= maxNetsplitNicks)
985             t.append(QString("%DN%1%DN").arg(users.join(", ")));
986         else
987             t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
988     }
989     break;
990     case Message::NetsplitQuit:
991     {
992         QStringList users = txt.split("#:#");
993         QStringList servers = users.takeLast().split(" ");
994
995         for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
996             users[i] = nickFromMask(users.at(i));
997
998         t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
999
1000         if (users.count() <= maxNetsplitNicks)
1001             t.append(QString("%DN%1%DN").arg(users.join(", ")));
1002         else
1003             t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
1004     }
1005     break;
1006     case Message::Invite:
1007         t = QString("%1").arg(txt); break;
1008     default:
1009         t = QString("[%1]").arg(txt);
1010     }
1011     _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
1012 }
1013
1014
1015 const QString &UiStyle::StyledMessage::plainContents() const
1016 {
1017     if (_contents.plainText.isNull())
1018         style();
1019
1020     return _contents.plainText;
1021 }
1022
1023
1024 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
1025 {
1026     if (_contents.plainText.isNull())
1027         style();
1028
1029     return _contents.formatList;
1030 }
1031
1032
1033 QString UiStyle::StyledMessage::decoratedTimestamp() const
1034 {
1035     return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
1036 }
1037
1038
1039 QString UiStyle::StyledMessage::plainSender() const
1040 {
1041     switch (type()) {
1042     case Message::Plain:
1043     case Message::Notice:
1044         return nickFromMask(sender());
1045     default:
1046         return QString();
1047     }
1048 }
1049
1050
1051 QString UiStyle::StyledMessage::decoratedSender() const
1052 {
1053     QString _senderPrefixes;
1054     if (_showSenderPrefixes) {
1055         _senderPrefixes = senderPrefixes();
1056     }
1057
1058     switch (type()) {
1059     case Message::Plain:
1060         if (_showSenderBrackets)
1061             return QString("<%1%2>").arg(_senderPrefixes, plainSender());
1062         else
1063             return QString("%1%2").arg(_senderPrefixes, plainSender());
1064     case Message::Notice:
1065         return QString("[%1%2]").arg(_senderPrefixes, plainSender());
1066     case Message::Action:
1067         return "-*-";
1068     case Message::Nick:
1069         return "<->";
1070     case Message::Mode:
1071         return "***";
1072     case Message::Join:
1073         return "-->";
1074     case Message::Part:
1075         return "<--";
1076     case Message::Quit:
1077         return "<--";
1078     case Message::Kick:
1079         return "<-*";
1080     case Message::Kill:
1081         return "<-x";
1082     case Message::Server:
1083         return "*";
1084     case Message::Info:
1085         return "*";
1086     case Message::Error:
1087         return "*";
1088     case Message::DayChange:
1089         return "-";
1090     case Message::Topic:
1091         return "*";
1092     case Message::NetsplitJoin:
1093         return "=>";
1094     case Message::NetsplitQuit:
1095         return "<=";
1096     case Message::Invite:
1097         return "->";
1098     }
1099
1100     return QString("%1%2").arg(_senderPrefixes, plainSender());
1101 }
1102
1103
1104 // FIXME hardcoded to 16 sender hashes
1105 quint8 UiStyle::StyledMessage::senderHash() const
1106 {
1107     if (_senderHash != 0xff)
1108         return _senderHash;
1109
1110     QString nick;
1111
1112     // HACK: Until multiple nicknames with different colors can be solved in the theming engine,
1113     // for /nick change notifications, use the color of the new nickname (if possible), not the old
1114     // nickname.
1115     if (type() == Message::Nick) {
1116         // New nickname is given as contents.  Change to that.
1117         nick = stripFormatCodes(contents()).toLower();
1118     } else {
1119         // Just use the sender directly
1120         nick = nickFromMask(sender()).toLower();
1121     }
1122
1123     if (!nick.isEmpty()) {
1124         int chopCount = 0;
1125         while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
1126             chopCount++;
1127         if (chopCount < nick.size())
1128             nick.chop(chopCount);
1129     }
1130     quint16 hash = qChecksum(nick.toLatin1().data(), nick.toLatin1().size());
1131     return (_senderHash = (hash & 0xf) + 1);
1132 }
1133
1134 /***********************************************************************************/
1135
1136 #if QT_VERSION < 0x050000
1137 uint qHash(UiStyle::ItemFormatType key)
1138 {
1139     return qHash(static_cast<quint32>(key));
1140 }
1141
1142 #else
1143
1144 uint qHash(UiStyle::ItemFormatType key, uint seed)
1145 {
1146     return qHash(static_cast<quint32>(key), seed);
1147 }
1148 #endif
1149
1150 UiStyle::FormatType operator|(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
1151 {
1152     return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1153 }
1154
1155 UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs)
1156 {
1157     lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1158     return lhs;
1159 }
1160
1161
1162 UiStyle::FormatType operator|(UiStyle::FormatType lhs, quint32 rhs)
1163 {
1164     return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
1165 }
1166
1167
1168 UiStyle::FormatType& operator|=(UiStyle::FormatType &lhs, quint32 rhs)
1169 {
1170     lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
1171     return lhs;
1172 }
1173
1174
1175 UiStyle::FormatType operator&(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
1176 {
1177     return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1178 }
1179
1180
1181 UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
1182 {
1183     lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1184     return lhs;
1185 }
1186
1187
1188 UiStyle::FormatType operator&(UiStyle::FormatType lhs, quint32 rhs)
1189 {
1190     return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
1191 }
1192
1193
1194 UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, quint32 rhs)
1195 {
1196     lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
1197     return lhs;
1198 }
1199
1200
1201 UiStyle::FormatType& operator^=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
1202 {
1203     lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) ^ static_cast<quint32>(rhs));
1204     return lhs;
1205 }
1206
1207
1208 UiStyle::MessageLabel operator|(UiStyle::MessageLabel lhs, UiStyle::MessageLabel rhs)
1209 {
1210     return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1211 }
1212
1213
1214 UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
1215 {
1216     lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1217     return lhs;
1218 }
1219
1220
1221 UiStyle::MessageLabel operator&(UiStyle::MessageLabel lhs, quint32 rhs)
1222 {
1223     return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & rhs);
1224 }
1225
1226
1227 UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
1228 {
1229     lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1230     return lhs;
1231 }
1232
1233
1234 quint64 operator|(UiStyle::FormatType lhs, UiStyle::MessageLabel rhs)
1235 {
1236     return static_cast<quint64>(lhs) | (static_cast<quint64>(rhs) << 32ull);
1237 }
1238
1239
1240 UiStyle::ItemFormatType operator|(UiStyle::ItemFormatType lhs, UiStyle::ItemFormatType rhs)
1241 {
1242     return static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1243 }
1244
1245
1246 UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType &lhs, UiStyle::ItemFormatType rhs)
1247 {
1248     lhs = static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1249     return lhs;
1250 }
1251
1252 /***********************************************************************************/
1253
1254 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
1255 {
1256     out << static_cast<quint16>(formatList.size());
1257     UiStyle::FormatList::const_iterator it = formatList.begin();
1258     while (it != formatList.end()) {
1259         out << it->first
1260             << static_cast<quint32>(it->second.type)
1261             << it->second.foreground
1262             << it->second.background;
1263         ++it;
1264     }
1265     return out;
1266 }
1267
1268
1269 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
1270 {
1271     quint16 cnt;
1272     in >> cnt;
1273     for (quint16 i = 0; i < cnt; i++) {
1274         quint16 pos;
1275         quint32 ftype;
1276         QColor foreground;
1277         QColor background;
1278         in >> pos >> ftype >> foreground >> background;
1279         formatList.emplace_back(std::make_pair(quint16{pos}, UiStyle::Format{static_cast<UiStyle::FormatType>(ftype), foreground, background}));
1280     }
1281     return in;
1282 }