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