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