Optionally use system locale for chat timestamp
[quassel.git] / src / uisupport / uistyle.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <QApplication>
22 #include <QIcon>
23
24 #include "buffersettings.h"
25 #include "qssparser.h"
26 #include "quassel.h"
27 #include "uistyle.h"
28 #include "uisettings.h"
29 #include "util.h"
30
31 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
32 bool UiStyle::_useCustomTimestampFormat;       /// If true, use the custom timestamp format
33 QString UiStyle::_timestampFormatString;       /// Timestamp format
34 QString UiStyle::_systemTimestampFormatString; /// Cached copy of system locale timestamp format
35 bool UiStyle::_showSenderBrackets;             /// If true, show brackets around sender names
36
37 UiStyle::UiStyle(QObject *parent)
38     : QObject(parent),
39     _channelJoinedIcon(QIcon::fromTheme("irc-channel-joined", QIcon(":/icons/irc-channel-joined.png"))),
40     _channelPartedIcon(QIcon::fromTheme("irc-channel-parted", QIcon(":/icons/irc-channel-parted.png"))),
41     _userOfflineIcon(QIcon::fromTheme("im-user-offline", QIcon::fromTheme("user-offline", QIcon(":/icons/im-user-offline.png")))),
42     _userOnlineIcon(QIcon::fromTheme("im-user", QIcon::fromTheme("user-available", QIcon(":/icons/im-user.png")))), // im-user-* are non-standard oxygen extensions
43     _userAwayIcon(QIcon::fromTheme("im-user-away", QIcon::fromTheme("user-away", QIcon(":/icons/im-user-away.png")))),
44     _categoryOpIcon(QIcon::fromTheme("irc-operator")),
45     _categoryVoiceIcon(QIcon::fromTheme("irc-voice")),
46     _opIconLimit(UserCategoryItem::categoryFromModes("o")),
47     _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
48 {
49     // register FormatList if that hasn't happened yet
50     // FIXME I don't think this actually avoids double registration... then again... does it hurt?
51     if (QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
52         qRegisterMetaType<FormatList>("UiStyle::FormatList");
53         qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
54         Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
55     }
56
57     _uiStylePalette = QVector<QBrush>(NumRoles, QBrush());
58
59     // Now initialize the mapping between FormatCodes and FormatTypes...
60     _formatCodes["%O"] = Base;
61     _formatCodes["%B"] = Bold;
62     _formatCodes["%S"] = Italic;
63     _formatCodes["%U"] = Underline;
64     _formatCodes["%R"] = Reverse;
65
66     _formatCodes["%DN"] = Nick;
67     _formatCodes["%DH"] = Hostmask;
68     _formatCodes["%DC"] = ChannelName;
69     _formatCodes["%DM"] = ModeFlags;
70     _formatCodes["%DU"] = Url;
71
72     // Initialize fallback defaults
73     // NOTE: If you change this, update qtui/chatviewsettings.h, too.  More explanations available
74     // in there.
75     setUseCustomTimestampFormat(false);
76     setTimestampFormatString(" hh:mm:ss");
77     enableSenderBrackets(true);
78
79     // BufferView / NickView settings
80     UiStyleSettings s;
81     _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
82     s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
83
84     _allowMircColors = s.value("AllowMircColors", true).toBool();
85     s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
86
87     loadStyleSheet();
88 }
89
90
91 UiStyle::~UiStyle()
92 {
93     qDeleteAll(_metricsCache);
94 }
95
96
97 void UiStyle::reload()
98 {
99     loadStyleSheet();
100 }
101
102
103 void UiStyle::loadStyleSheet()
104 {
105     qDeleteAll(_metricsCache);
106     _metricsCache.clear();
107     _formatCache.clear();
108     _formats.clear();
109
110     UiStyleSettings s;
111
112     QString styleSheet;
113     styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
114     styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
115     if (s.value("UseCustomStyleSheet", false).toBool()) {
116         QString customSheetPath(s.value("CustomStyleSheetPath").toString());
117         QString customSheet = loadStyleSheet("file:///" + customSheetPath, true);
118         if (customSheet.isEmpty()) {
119             // MIGRATION: changed default install path for data from /usr/share/apps to /usr/share
120             if (customSheetPath.startsWith("/usr/share/apps/quassel")) {
121                 customSheetPath.replace(QRegExp("^/usr/share/apps"), "/usr/share");
122                 customSheet = loadStyleSheet("file:///" + customSheetPath, true);
123                 if (!customSheet.isEmpty()) {
124                     s.setValue("CustomStyleSheetPath", customSheetPath);
125                     qDebug() << "Custom stylesheet path migrated to" << customSheetPath;
126                 }
127             }
128         }
129         styleSheet += customSheet;
130     }
131     styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
132
133     if (!styleSheet.isEmpty()) {
134         QssParser parser;
135         parser.processStyleSheet(styleSheet);
136         QApplication::setPalette(parser.palette());
137
138         _uiStylePalette = parser.uiStylePalette();
139         _formats = parser.formats();
140         _listItemFormats = parser.listItemFormats();
141
142         styleSheet = styleSheet.trimmed();
143         if (!styleSheet.isEmpty())
144             qApp->setStyleSheet(styleSheet);  // pass the remaining sections to the application
145     }
146
147     emit changed();
148 }
149
150
151 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
152 {
153     QString ss = styleSheet;
154     if (ss.startsWith("file:///")) {
155         ss.remove(0, 8);
156         if (ss.isEmpty())
157             return QString();
158
159         QFile file(ss);
160         if (file.open(QFile::ReadOnly)) {
161             QTextStream stream(&file);
162             ss = stream.readAll();
163             file.close();
164         }
165         else {
166             if (shouldExist)
167                 qWarning() << "Could not open stylesheet file:" << file.fileName();
168             return QString();
169         }
170     }
171     return ss;
172 }
173
174
175 void UiStyle::updateSystemTimestampFormat()
176 {
177     // Does the system locale use AM/PM designators?  For example:
178     // AM/PM:    h:mm AP
179     // AM/PM:    hh:mm a
180     // 24-hour:  h:mm
181     // 24-hour:  hh:mm ADD things
182     // For timestamp format, see https://doc.qt.io/qt-5/qdatetime.html#toString
183     // This won't update if the system locale is changed while Quassel is running.  If need be,
184     // Quassel could hook into notifications of changing system locale to update this.
185     //
186     // Match any AP or A designation if on a word boundary, including underscores.
187     //   .*(\b|_)(A|AP)(\b|_).*
188     //   .*         Match any number of characters
189     //   \b         Match a word boundary, i.e. "AAA.BBB", "." is matched
190     //   _          Match the literal character '_' (not considered a word boundary)
191     //   (X|Y)  Match either X or Y, exactly
192     //
193     // Note that '\' must be escaped as '\\'
194     // QRegExp does not support (?> ...), so it's replaced with standard matching, (...)
195     // Helpful interactive website for debugging and explaining:  https://regex101.com/
196     const QRegExp regExpMatchAMPM(".*(\\b|_)(A|AP)(\\b|_).*", Qt::CaseInsensitive);
197
198     if (regExpMatchAMPM.exactMatch(QLocale::system().timeFormat(QLocale::ShortFormat))) {
199         // AM/PM style used
200         _systemTimestampFormatString = " h:mm:ss ap";
201     } else {
202         // 24-hour style used
203         _systemTimestampFormatString = " hh:mm:ss";
204     }
205     // Include a space to give the timestamp a small bit of padding between the border of the chat
206     // buffer window and the numbers.  Helps with readability.
207     // If you change this to include brackets, e.g. "[hh:mm:ss]", also update
208     // ChatScene::updateTimestampHasBrackets() to true or false as needed!
209 }
210
211
212 // FIXME The following should trigger a reload/refresh of the chat view.
213 void UiStyle::setUseCustomTimestampFormat(bool enabled)
214 {
215     if (_useCustomTimestampFormat != enabled) {
216         _useCustomTimestampFormat = enabled;
217     }
218 }
219
220 void UiStyle::setTimestampFormatString(const QString &format)
221 {
222     if (_timestampFormatString != format) {
223         _timestampFormatString = format;
224     }
225 }
226
227 void UiStyle::enableSenderBrackets(bool enabled)
228 {
229     if (_showSenderBrackets != enabled) {
230         _showSenderBrackets = enabled;
231     }
232 }
233
234
235 void UiStyle::allowMircColorsChanged(const QVariant &v)
236 {
237     _allowMircColors = v.toBool();
238     emit changed();
239 }
240
241
242 /******** ItemView Styling *******/
243
244 void UiStyle::showItemViewIconsChanged(const QVariant &v)
245 {
246     _showBufferViewIcons = _showNickViewIcons = v.toBool();
247 }
248
249
250 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
251 {
252     BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
253     bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
254
255     if (role == Qt::DecorationRole) {
256         if (!_showBufferViewIcons)
257             return QVariant();
258
259         switch (type) {
260         case BufferInfo::ChannelBuffer:
261             if (isActive)
262                 return _channelJoinedIcon;
263             else
264                 return _channelPartedIcon;
265         case BufferInfo::QueryBuffer:
266             if (!isActive)
267                 return _userOfflineIcon;
268             if (index.data(NetworkModel::UserAwayRole).toBool())
269                 return _userAwayIcon;
270             else
271                 return _userOnlineIcon;
272         default:
273             return QVariant();
274         }
275     }
276
277     quint32 fmtType = BufferViewItem;
278     switch (type) {
279     case BufferInfo::StatusBuffer:
280         fmtType |= NetworkItem;
281         break;
282     case BufferInfo::ChannelBuffer:
283         fmtType |= ChannelBufferItem;
284         break;
285     case BufferInfo::QueryBuffer:
286         fmtType |= QueryBufferItem;
287         break;
288     default:
289         return QVariant();
290     }
291
292     QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
293     fmt.merge(_listItemFormats.value(fmtType));
294
295     BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
296     if (activity & BufferInfo::Highlight) {
297         fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
298         fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
299     }
300     else if (activity & BufferInfo::NewMessage) {
301         fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
302         fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
303     }
304     else if (activity & BufferInfo::OtherActivity) {
305         fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
306         fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
307     }
308     else if (!isActive) {
309         fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
310         fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
311     }
312     else if (index.data(NetworkModel::UserAwayRole).toBool()) {
313         fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
314         fmt.merge(_listItemFormats.value(fmtType | UserAway));
315     }
316
317     return itemData(role, fmt);
318 }
319
320
321 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
322 {
323     NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
324
325     if (role == Qt::DecorationRole) {
326         if (!_showNickViewIcons)
327             return QVariant();
328
329         switch (type) {
330         case NetworkModel::UserCategoryItemType:
331         {
332             int categoryId = index.data(TreeModel::SortRole).toInt();
333             if (categoryId <= _opIconLimit)
334                 return _categoryOpIcon;
335             if (categoryId <= _voiceIconLimit)
336                 return _categoryVoiceIcon;
337             return _userOnlineIcon;
338         }
339         case NetworkModel::IrcUserItemType:
340             if (index.data(NetworkModel::ItemActiveRole).toBool())
341                 return _userOnlineIcon;
342             else
343                 return _userAwayIcon;
344         default:
345             return QVariant();
346         }
347     }
348
349     QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
350
351     switch (type) {
352     case NetworkModel::IrcUserItemType:
353         fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
354         if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
355             fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
356             fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
357         }
358         break;
359     case NetworkModel::UserCategoryItemType:
360         fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
361         break;
362     default:
363         return QVariant();
364     }
365
366     return itemData(role, fmt);
367 }
368
369
370 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
371 {
372     switch (role) {
373     case Qt::FontRole:
374         return format.font();
375     case Qt::ForegroundRole:
376         return format.property(QTextFormat::ForegroundBrush);
377     case Qt::BackgroundRole:
378         return format.property(QTextFormat::BackgroundBrush);
379     default:
380         return QVariant();
381     }
382 }
383
384
385 /******** Caching *******/
386
387 QTextCharFormat UiStyle::format(quint64 key) const
388 {
389     return _formats.value(key, QTextCharFormat());
390 }
391
392
393 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const
394 {
395     return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
396 }
397
398
399 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) const
400 {
401     _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
402 }
403
404
405 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const
406 {
407     // QFontMetricsF is not assignable, so we need to store pointers :/
408     quint64 key = ftype | ((quint64)label << 32);
409
410     if (_metricsCache.contains(key))
411         return _metricsCache.value(key);
412
413     return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
414 }
415
416
417 /******** Generate formats ********/
418
419 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
420 //       until you _really_ know what you do!
421 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const
422 {
423     if (ftype == Invalid)
424         return QTextCharFormat();
425
426     quint64 label = (quint64)label_ << 32;
427
428     // check if we have exactly this format readily cached already
429     QTextCharFormat fmt = cachedFormat(ftype, label_);
430     if (fmt.properties().count())
431         return fmt;
432
433     mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
434
435     for (quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<= 1) {
436         if (label & mask)
437             mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
438     }
439
440     setCachedFormat(fmt, ftype, label_);
441     return fmt;
442 }
443
444
445 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
446 {
447     mergeSubElementFormat(fmt, ftype & 0x00ff, label);
448
449     // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
450     //       or "foreground 01 and background 03"
451     if ((ftype & 0xfff00)) { // element format
452         for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
453             if (ftype & mask) {
454                 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
455             }
456         }
457     }
458
459     // Now we handle color codes
460     // We assume that those can't be combined with subelement and message types.
461     if (_allowMircColors) {
462         if (ftype & 0x00400000)
463             mergeSubElementFormat(fmt, ftype & 0x0f400000, label);  // foreground
464         if (ftype & 0x00800000)
465             mergeSubElementFormat(fmt, ftype & 0xf0800000, label);  // background
466         if ((ftype & 0x00c00000) == 0x00c00000)
467             mergeSubElementFormat(fmt, ftype & 0xffc00000, label);  // combination
468     }
469
470     // URL
471     if (ftype & Url)
472         mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
473 }
474
475
476 // Merge a subelement format into an existing message format
477 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
478 {
479     quint64 key = ftype | label;
480     fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
481     fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
482     fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
483     fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
484 }
485
486
487 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
488 {
489     switch (msgType) {
490     case Message::Plain:
491         return PlainMsg;
492     case Message::Notice:
493         return NoticeMsg;
494     case Message::Action:
495         return ActionMsg;
496     case Message::Nick:
497         return NickMsg;
498     case Message::Mode:
499         return ModeMsg;
500     case Message::Join:
501         return JoinMsg;
502     case Message::Part:
503         return PartMsg;
504     case Message::Quit:
505         return QuitMsg;
506     case Message::Kick:
507         return KickMsg;
508     case Message::Kill:
509         return KillMsg;
510     case Message::Server:
511         return ServerMsg;
512     case Message::Info:
513         return InfoMsg;
514     case Message::Error:
515         return ErrorMsg;
516     case Message::DayChange:
517         return DayChangeMsg;
518     case Message::Topic:
519         return TopicMsg;
520     case Message::NetsplitJoin:
521         return NetsplitJoinMsg;
522     case Message::NetsplitQuit:
523         return NetsplitQuitMsg;
524     case Message::Invite:
525         return InviteMsg;
526     }
527     //Q_ASSERT(false); // we need to handle all message types
528     qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
529     return ErrorMsg;
530 }
531
532
533 UiStyle::FormatType UiStyle::formatType(const QString &code)
534 {
535     if (_formatCodes.contains(code)) return _formatCodes.value(code);
536     return Invalid;
537 }
538
539
540 QString UiStyle::formatCode(FormatType ftype)
541 {
542     return _formatCodes.key(ftype);
543 }
544
545
546 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const
547 {
548     QList<QTextLayout::FormatRange> formatRanges;
549     QTextLayout::FormatRange range;
550     int i = 0;
551     for (i = 0; i < formatList.count(); i++) {
552         range.format = format(formatList.at(i).second, messageLabel);
553         range.start = formatList.at(i).first;
554         if (i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
555         formatRanges.append(range);
556     }
557     if (i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
558     return formatRanges;
559 }
560
561
562 // This method expects a well-formatted string, there is no error checking!
563 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
564 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat)
565 {
566     QString s = s_;
567     StyledString result;
568     result.formatList.append(qMakePair((quint16)0, baseFormat));
569
570     if (s.length() > 65535) {
571         // We use quint16 for indexes
572         qWarning() << QString("String too long to be styled: %1").arg(s);
573         result.plainText = s;
574         return result;
575     }
576
577     quint32 curfmt = baseFormat;
578     int pos = 0; quint16 length = 0;
579     for (;;) {
580         pos = s.indexOf('%', pos);
581         if (pos < 0) break;
582         if (s[pos+1] == '%') { // escaped %, we just remove one and continue
583             s.remove(pos, 1);
584             pos++;
585             continue;
586         }
587         if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
588             if (s[pos+3] == '-') { // color off
589                 curfmt &= 0x003fffff;
590                 length = 4;
591             }
592             else {
593                 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
594                 //TODO: use 99 as transparent color (re mirc color "standard")
595                 color &= 0x0f;
596                 if (s[pos+3] == 'f') {
597                     curfmt &= 0xf0ffffff;
598                     curfmt |= (quint32)(color << 24) | 0x00400000;
599                 }
600                 else {
601                     curfmt &= 0x0fffffff;
602                     curfmt |= (quint32)(color << 28) | 0x00800000;
603                 }
604                 length = 6;
605             }
606         }
607         else if (s[pos+1] == 'O') { // reset formatting
608             curfmt &= 0x000000ff; // we keep message type-specific formatting
609             length = 2;
610         }
611         else if (s[pos+1] == 'R') { // reverse
612             // TODO: implement reverse formatting
613
614             length = 2;
615         }
616         else { // all others are toggles
617             QString code = QString("%") + s[pos+1];
618             if (s[pos+1] == 'D') code += s[pos+2];
619             FormatType ftype = formatType(code);
620             if (ftype == Invalid) {
621                 pos++;
622                 qWarning() << (QString("Invalid format code in string: %1").arg(s));
623                 continue;
624             }
625             curfmt ^= ftype;
626             length = code.length();
627         }
628         s.remove(pos, length);
629         if (pos == result.formatList.last().first)
630             result.formatList.last().second = curfmt;
631         else
632             result.formatList.append(qMakePair((quint16)pos, curfmt));
633     }
634     result.plainText = s;
635     return result;
636 }
637
638
639 QString UiStyle::mircToInternal(const QString &mirc_)
640 {
641     QString mirc;
642     mirc.reserve(mirc_.size());
643     foreach (const QChar &c, mirc_) {
644         if ((c < '\x20' || c == '\x7f') && c != '\x03') {
645             switch (c.unicode()) {
646                 case '\x02':
647                     mirc += "%B";
648                     break;
649                 case '\x0f':
650                     mirc += "%O";
651                     break;
652                 case '\x09':
653                     mirc += "        ";
654                     break;
655                 case '\x12':
656                 case '\x16':
657                     mirc += "%R";
658                     break;
659                 case '\x1d':
660                     mirc += "%S";
661                     break;
662                 case '\x1f':
663                     mirc += "%U";
664                     break;
665                 case '\x7f':
666                     mirc += QChar(0x2421);
667                     break;
668                 default:
669                     mirc += QChar(0x2400 + c.unicode());
670             }
671         } else {
672             if (c == '%')
673                 mirc += c;
674             mirc += c;
675         }
676     }
677
678     // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
679     // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
680     // %Dc- turns color off.
681     // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
682     //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
683     int pos = 0;
684     for (;;) {
685         pos = mirc.indexOf('\x03', pos);
686         if (pos < 0) break;  // no more mirc color codes
687         QString ins, num;
688         int l = mirc.length();
689         int i = pos + 1;
690         // check for fg color
691         if (i < l && mirc[i].isDigit()) {
692             num = mirc[i++];
693             if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
694             else num.prepend('0');
695             ins = QString("%Dcf%1").arg(num);
696
697             if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
698                 i++;
699                 num = mirc[i++];
700                 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
701                 else num.prepend('0');
702                 ins += QString("%Dcb%1").arg(num);
703             }
704         }
705         else {
706             ins = "%Dc-";
707         }
708         mirc.replace(pos, i-pos, ins);
709     }
710     return mirc;
711 }
712
713
714 QString UiStyle::systemTimestampFormatString()
715 {
716     if (_systemTimestampFormatString.isEmpty()) {
717         // Calculate and cache the system timestamp format string
718         updateSystemTimestampFormat();
719     }
720     return _systemTimestampFormatString;
721 }
722
723
724 QString UiStyle::timestampFormatString()
725 {
726     if (useCustomTimestampFormat()) {
727         return _timestampFormatString;
728     } else {
729         return systemTimestampFormatString();
730     }
731 }
732
733
734 /***********************************************************************************/
735 UiStyle::StyledMessage::StyledMessage(const Message &msg)
736     : Message(msg)
737 {
738     if (type() == Message::Plain || type() == Message::Action)
739         _senderHash = 0xff;
740     else
741         _senderHash = 0x00;
742     // This means we never compute the hash for msgs that aren't Plain or Action
743 }
744
745
746 void UiStyle::StyledMessage::style() const
747 {
748     QString user = userFromMask(sender());
749     QString host = hostFromMask(sender());
750     QString nick = nickFromMask(sender());
751     QString txt = UiStyle::mircToInternal(contents());
752     QString bufferName = bufferInfo().bufferName();
753     bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
754     host.replace('%', "%%");     // hostnames too...
755     user.replace('%', "%%");     // and the username...
756     nick.replace('%', "%%");     // ... and then there's totally RFC-violating servers like justin.tv m(
757     const int maxNetsplitNicks = 15;
758
759     QString t;
760     switch (type()) {
761     case Message::Plain:
762         t = QString("%1").arg(txt); break;
763     case Message::Notice:
764         t = QString("%1").arg(txt); break;
765     case Message::Action:
766         t = QString("%DN%1%DN %2").arg(nick).arg(txt);
767         break;
768     case Message::Nick:
769         //: Nick Message
770         if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
771         else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
772         break;
773     case Message::Mode:
774         //: Mode Message
775         if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
776         else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
777         break;
778     case Message::Join:
779         //: Join Message
780         t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
781     case Message::Part:
782         //: Part Message
783         t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
784         if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
785         break;
786     case Message::Quit:
787         //: Quit Message
788         t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
789         if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
790         break;
791     case Message::Kick:
792     {
793         QString victim = txt.section(" ", 0, 0);
794         QString kickmsg = txt.section(" ", 1);
795         //: Kick Message
796         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
797         if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
798     }
799     break;
800     //case Message::Kill: FIXME
801
802     case Message::Server:
803         t = QString("%1").arg(txt); break;
804     case Message::Info:
805         t = QString("%1").arg(txt); break;
806     case Message::Error:
807         t = QString("%1").arg(txt); break;
808     case Message::DayChange:
809     {
810         //: Day Change Message
811         t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
812     }
813         break;
814     case Message::Topic:
815         t = QString("%1").arg(txt); break;
816     case Message::NetsplitJoin:
817     {
818         QStringList users = txt.split("#:#");
819         QStringList servers = users.takeLast().split(" ");
820
821         for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
822             users[i] = nickFromMask(users.at(i));
823
824         t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
825         if (users.count() <= maxNetsplitNicks)
826             t.append(QString("%DN%1%DN").arg(users.join(", ")));
827         else
828             t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
829     }
830     break;
831     case Message::NetsplitQuit:
832     {
833         QStringList users = txt.split("#:#");
834         QStringList servers = users.takeLast().split(" ");
835
836         for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
837             users[i] = nickFromMask(users.at(i));
838
839         t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
840
841         if (users.count() <= maxNetsplitNicks)
842             t.append(QString("%DN%1%DN").arg(users.join(", ")));
843         else
844             t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
845     }
846     break;
847     case Message::Invite:
848         t = QString("%1").arg(txt); break;
849     default:
850         t = QString("[%1]").arg(txt);
851     }
852     _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
853 }
854
855
856 const QString &UiStyle::StyledMessage::plainContents() const
857 {
858     if (_contents.plainText.isNull())
859         style();
860
861     return _contents.plainText;
862 }
863
864
865 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
866 {
867     if (_contents.plainText.isNull())
868         style();
869
870     return _contents.formatList;
871 }
872
873
874 QString UiStyle::StyledMessage::decoratedTimestamp() const
875 {
876     return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
877 }
878
879
880 QString UiStyle::StyledMessage::plainSender() const
881 {
882     switch (type()) {
883     case Message::Plain:
884     case Message::Notice:
885         return nickFromMask(sender());
886     default:
887         return QString();
888     }
889 }
890
891
892 QString UiStyle::StyledMessage::decoratedSender() const
893 {
894     switch (type()) {
895     case Message::Plain:
896         if (_showSenderBrackets)
897             return QString("<%1>").arg(plainSender());
898         else
899             return QString("%1").arg(plainSender());
900         break;
901     case Message::Notice:
902         return QString("[%1]").arg(plainSender()); break;
903     case Message::Action:
904         return "-*-"; break;
905     case Message::Nick:
906         return "<->"; break;
907     case Message::Mode:
908         return "***"; break;
909     case Message::Join:
910         return "-->"; break;
911     case Message::Part:
912         return "<--"; break;
913     case Message::Quit:
914         return "<--"; break;
915     case Message::Kick:
916         return "<-*"; break;
917     case Message::Kill:
918         return "<-x"; break;
919     case Message::Server:
920         return "*"; break;
921     case Message::Info:
922         return "*"; break;
923     case Message::Error:
924         return "*"; break;
925     case Message::DayChange:
926         return "-"; break;
927     case Message::Topic:
928         return "*"; break;
929     case Message::NetsplitJoin:
930         return "=>"; break;
931     case Message::NetsplitQuit:
932         return "<="; break;
933     case Message::Invite:
934         return "->"; break;
935     default:
936         return QString("%1").arg(plainSender());
937     }
938 }
939
940
941 // FIXME hardcoded to 16 sender hashes
942 quint8 UiStyle::StyledMessage::senderHash() const
943 {
944     if (_senderHash != 0xff)
945         return _senderHash;
946
947     QString nick = nickFromMask(sender()).toLower();
948     if (!nick.isEmpty()) {
949         int chopCount = 0;
950         while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
951             chopCount++;
952         if (chopCount < nick.size())
953             nick.chop(chopCount);
954     }
955     quint16 hash = qChecksum(nick.toLatin1().data(), nick.toLatin1().size());
956     return (_senderHash = (hash & 0xf) + 1);
957 }
958
959
960 /***********************************************************************************/
961
962 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
963 {
964     out << formatList.count();
965     UiStyle::FormatList::const_iterator it = formatList.begin();
966     while (it != formatList.end()) {
967         out << (*it).first << (*it).second;
968         ++it;
969     }
970     return out;
971 }
972
973
974 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
975 {
976     quint16 cnt;
977     in >> cnt;
978     for (quint16 i = 0; i < cnt; i++) {
979         quint16 pos; quint32 ftype;
980         in >> pos >> ftype;
981         formatList.append(qMakePair((quint16)pos, ftype));
982     }
983     return in;
984 }