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