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