Work around problems in QTreeView when using Qt 4.8
[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) const {
296   _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
297 }
298
299 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const {
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_) const {
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) const {
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) const {
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     case Message::Invite:
410       return InviteMsg;
411   }
412   //Q_ASSERT(false); // we need to handle all message types
413   qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
414   return ErrorMsg;
415 }
416
417 UiStyle::FormatType UiStyle::formatType(const QString & code) {
418   if(_formatCodes.contains(code)) return _formatCodes.value(code);
419   return Invalid;
420 }
421
422 QString UiStyle::formatCode(FormatType ftype) {
423   return _formatCodes.key(ftype);
424 }
425
426 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const {
427   QList<QTextLayout::FormatRange> formatRanges;
428   QTextLayout::FormatRange range;
429   int i = 0;
430   for(i = 0; i < formatList.count(); i++) {
431     range.format = format(formatList.at(i).second, messageLabel);
432     range.start = formatList.at(i).first;
433     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
434     formatRanges.append(range);
435   }
436   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
437   return formatRanges;
438 }
439
440 // This method expects a well-formatted string, there is no error checking!
441 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
442 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
443   QString s = s_;
444   if(s.length() > 65535) {
445     qWarning() << QString("String too long to be styled: %1").arg(s);
446     return StyledString();
447   }
448   StyledString result;
449   result.formatList.append(qMakePair((quint16)0, baseFormat));
450   quint32 curfmt = baseFormat;
451   int pos = 0; quint16 length = 0;
452   for(;;) {
453     pos = s.indexOf('%', pos);
454     if(pos < 0) break;
455     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
456       s.remove(pos, 1);
457       pos++;
458       continue;
459     }
460     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
461       if(s[pos+3] == '-') {  // color off
462         curfmt &= 0x003fffff;
463         length = 4;
464       } else {
465         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
466         //TODO: use 99 as transparent color (re mirc color "standard")
467         color &= 0x0f;
468         if(s[pos+3] == 'f') {
469           curfmt &= 0xf0ffffff;
470           curfmt |= (quint32)(color << 24) | 0x00400000;
471         } else {
472           curfmt &= 0x0fffffff;
473           curfmt |= (quint32)(color << 28) | 0x00800000;
474         }
475         length = 6;
476       }
477     } else if(s[pos+1] == 'O') { // reset formatting
478       curfmt &= 0x000000ff; // we keep message type-specific formatting
479       length = 2;
480     } else if(s[pos+1] == 'R') { // reverse
481       // TODO: implement reverse formatting
482
483       length = 2;
484     } else { // all others are toggles
485       QString code = QString("%") + s[pos+1];
486       if(s[pos+1] == 'D') code += s[pos+2];
487       FormatType ftype = formatType(code);
488       if(ftype == Invalid) {
489         pos++;
490         qWarning() << (QString("Invalid format code in string: %1").arg(s));
491         continue;
492       }
493       curfmt ^= ftype;
494       length = code.length();
495     }
496     s.remove(pos, length);
497     if(pos == result.formatList.last().first)
498       result.formatList.last().second = curfmt;
499     else
500       result.formatList.append(qMakePair((quint16)pos, curfmt));
501   }
502   result.plainText = s;
503   return result;
504 }
505
506 QString UiStyle::mircToInternal(const QString &mirc_) {
507   QString mirc = mirc_;
508   mirc.replace('%', "%%");      // escape % just to be sure
509   mirc.replace('\t', "        ");      // tabs break layout, also this is italics in Konversation
510   mirc.replace('\x02', "%B");
511   mirc.replace('\x0f', "%O");
512   mirc.replace('\x12', "%R");
513   mirc.replace('\x16', "%R");
514   mirc.replace('\x1d', "%S");
515   mirc.replace('\x1f', "%U");
516
517   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
518   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
519   // %Dc- turns color off.
520   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
521   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
522   int pos = 0;
523   for(;;) {
524     pos = mirc.indexOf('\x03', pos);
525     if(pos < 0) break; // no more mirc color codes
526     QString ins, num;
527     int l = mirc.length();
528     int i = pos + 1;
529     // check for fg color
530     if(i < l && mirc[i].isDigit()) {
531       num = mirc[i++];
532       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
533       else num.prepend('0');
534       ins = QString("%Dcf%1").arg(num);
535
536       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
537         i++;
538         num = mirc[i++];
539         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
540         else num.prepend('0');
541         ins += QString("%Dcb%1").arg(num);
542       }
543     } else {
544       ins = "%Dc-";
545     }
546     mirc.replace(pos, i-pos, ins);
547   }
548   return mirc;
549 }
550
551 /***********************************************************************************/
552 UiStyle::StyledMessage::StyledMessage(const Message &msg)
553   : Message(msg)
554 {
555   if(type() == Message::Plain)
556     _senderHash = 0xff;
557   else
558     _senderHash = 0x00;  // this means we never compute the hash for msgs that aren't plain
559 }
560
561 void UiStyle::StyledMessage::style() const {
562   QString user = userFromMask(sender());
563   QString host = hostFromMask(sender());
564   QString nick = nickFromMask(sender());
565   QString txt = UiStyle::mircToInternal(contents());
566   QString bufferName = bufferInfo().bufferName();
567   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
568   host.replace('%', "%%");       // hostnames too...
569   user.replace('%', "%%");       // and the username...
570   nick.replace('%', "%%");       // ... and then there's totally RFC-violating servers like justin.tv m(
571   const int maxNetsplitNicks = 15;
572
573   QString t;
574   switch(type()) {
575     case Message::Plain:
576       //: Plain Message
577       t = tr("%1").arg(txt); break;
578     case Message::Notice:
579       //: Notice Message
580       t = tr("%1").arg(txt); break;
581     case Message::Action:
582       //: Action Message
583       t = tr("%DN%1%DN %2").arg(nick).arg(txt);
584       break;
585     case Message::Nick:
586       //: Nick Message
587       if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
588       else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
589       break;
590     case Message::Mode:
591       //: Mode Message
592       if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
593       else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
594       break;
595     case Message::Join:
596       //: Join Message
597       t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
598     case Message::Part:
599       //: Part Message
600       t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
601       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
602       break;
603     case Message::Quit:
604       //: Quit Message
605       t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
606       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
607       break;
608     case Message::Kick: {
609         QString victim = txt.section(" ", 0, 0);
610         QString kickmsg = txt.section(" ", 1);
611         //: Kick Message
612         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
613         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
614       }
615       break;
616     //case Message::Kill: FIXME
617
618     case Message::Server:
619       //: Server Message
620       t = tr("%1").arg(txt); break;
621     case Message::Info:
622       //: Info Message
623       t = tr("%1").arg(txt); break;
624     case Message::Error:
625       //: Error Message
626       t = tr("%1").arg(txt); break;
627     case Message::DayChange:
628       //: Day Change Message
629       t = tr("{Day changed to %1}").arg(timestamp().toString());
630       break;
631     case Message::Topic:
632       //: Topic Message
633       t = tr("%1").arg(txt); break;
634     case Message::NetsplitJoin: {
635       QStringList users = txt.split("#:#");
636       QStringList servers = users.takeLast().split(" ");
637
638       for(int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
639         users[i] = nickFromMask(users.at(i));
640
641       t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0),servers.at(1));
642       if(users.count() <= maxNetsplitNicks)
643         t.append(QString("%DN%1%DN").arg(users.join(", ")));
644       else
645         t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
646       }
647       break;
648     case Message::NetsplitQuit: {
649       QStringList users = txt.split("#:#");
650       QStringList servers = users.takeLast().split(" ");
651
652       for(int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
653         users[i] = nickFromMask(users.at(i));
654
655       t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0),servers.at(1));
656
657       if(users.count() <= maxNetsplitNicks)
658         t.append(QString("%DN%1%DN").arg(users.join(", ")));
659       else
660         t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
661       }
662       break;
663     case Message::Invite:
664       //: Invite Message
665       t = tr("%1").arg(txt); break;
666     default:
667       t = tr("[%1]").arg(txt);
668   }
669   _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
670 }
671
672 const QString &UiStyle::StyledMessage::plainContents() const {
673   if(_contents.plainText.isNull())
674     style();
675
676   return _contents.plainText;
677 }
678
679 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
680   if(_contents.plainText.isNull())
681     style();
682
683   return _contents.formatList;
684 }
685
686 QString UiStyle::StyledMessage::decoratedTimestamp() const {
687   return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
688 }
689
690 QString UiStyle::StyledMessage::plainSender() const {
691   switch(type()) {
692     case Message::Plain:
693     case Message::Notice:
694       return nickFromMask(sender());
695     default:
696       return QString();
697   }
698 }
699
700 QString UiStyle::StyledMessage::decoratedSender() const {
701   switch(type()) {
702     case Message::Plain:
703       return tr("<%1>").arg(plainSender()); break;
704     case Message::Notice:
705       return tr("[%1]").arg(plainSender()); break;
706     case Message::Action:
707       return "-*-"; break;
708     case Message::Nick:
709       return "<->"; break;
710     case Message::Mode:
711       return "***"; break;
712     case Message::Join:
713       return "-->"; break;
714     case Message::Part:
715       return "<--"; break;
716     case Message::Quit:
717       return "<--"; break;
718     case Message::Kick:
719       return "<-*"; break;
720     case Message::Kill:
721       return "<-x"; break;
722     case Message::Server:
723       return "*"; break;
724     case Message::Info:
725       return "*"; break;
726     case Message::Error:
727       return "*"; break;
728     case Message::DayChange:
729       return "-"; break;
730     case Message::Topic:
731       return "*"; break;
732     case Message::NetsplitJoin:
733       return "=>"; break;
734     case Message::NetsplitQuit:
735       return "<="; break;
736     case Message::Invite:
737       return "->"; break;
738     default:
739       return QString("%1").arg(plainSender());
740   }
741 }
742
743 // FIXME hardcoded to 16 sender hashes
744 quint8 UiStyle::StyledMessage::senderHash() const {
745   if(_senderHash != 0xff)
746     return _senderHash;
747
748   QString nick = nickFromMask(sender()).toLower();
749   if(!nick.isEmpty()) {
750     int chopCount = 0;
751     while(chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
752       chopCount++;
753     if(chopCount < nick.size())
754       nick.chop(chopCount);
755   }
756   quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
757   return (_senderHash = (hash & 0xf) + 1);
758 }
759
760 /***********************************************************************************/
761
762 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
763   out << formatList.count();
764   UiStyle::FormatList::const_iterator it = formatList.begin();
765   while(it != formatList.end()) {
766     out << (*it).first << (*it).second;
767     ++it;
768   }
769   return out;
770 }
771
772 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
773   quint16 cnt;
774   in >> cnt;
775   for(quint16 i = 0; i < cnt; i++) {
776     quint16 pos; quint32 ftype;
777     in >> pos >> ftype;
778     formatList.append(qMakePair((quint16)pos, ftype));
779   }
780   return in;
781 }