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