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