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