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