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