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