fixes #413 - Icons in Nicklist
[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 "quassel.h"
23 #include "uistyle.h"
24 #include "uisettings.h"
25 #include "util.h"
26
27 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
28   // register FormatList if that hasn't happened yet
29   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
30   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
31     qRegisterMetaType<FormatList>("UiStyle::FormatList");
32     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
33     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
34   }
35
36   _defaultFont = QFont("Monospace", QApplication::font().pointSize());
37
38   // Default format
39   _defaultPlainFormat.setForeground(QBrush("#000000"));
40   _defaultPlainFormat.setFont(_defaultFont);
41   _defaultPlainFormat.font().setFixedPitch(true);
42   _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
43   setFormat(None, _defaultPlainFormat, Settings::Default);
44
45   // Load saved custom formats
46   UiStyleSettings s(_settingsKey);
47   foreach(FormatType type, s.availableFormats()) {
48     _customFormats[type] = s.customFormat(type);
49   }
50
51   // Now initialize the mapping between FormatCodes and FormatTypes...
52   _formatCodes["%O"] = None;
53   _formatCodes["%B"] = Bold;
54   _formatCodes["%S"] = Italic;
55   _formatCodes["%U"] = Underline;
56   _formatCodes["%R"] = Reverse;
57
58   _formatCodes["%D0"] = PlainMsg;
59   _formatCodes["%Dn"] = NoticeMsg;
60   _formatCodes["%Ds"] = ServerMsg;
61   _formatCodes["%De"] = ErrorMsg;
62   _formatCodes["%Dj"] = JoinMsg;
63   _formatCodes["%Dp"] = PartMsg;
64   _formatCodes["%Dq"] = QuitMsg;
65   _formatCodes["%Dk"] = KickMsg;
66   _formatCodes["%Dr"] = RenameMsg;
67   _formatCodes["%Dm"] = ModeMsg;
68   _formatCodes["%Da"] = ActionMsg;
69
70   _formatCodes["%DT"] = Timestamp;
71   _formatCodes["%DS"] = Sender;
72   _formatCodes["%DN"] = Nick;
73   _formatCodes["%DH"] = Hostmask;
74   _formatCodes["%DC"] = ChannelName;
75   _formatCodes["%DM"] = ModeFlags;
76   _formatCodes["%DU"] = Url;
77
78   // Initialize color codes according to mIRC "standard"
79   QStringList colors;
80   //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
81   //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
82   colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
83   colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
84
85   // Set color formats
86   for(int i = 0; i < 16; i++) {
87     QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
88     _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
89     _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
90     QTextCharFormat fgf, bgf;
91     fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
92     bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
93   }
94
95   // Set a few more standard formats
96   QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
97   setFormat(Bold, bold, Settings::Default);
98
99   QTextCharFormat italic; italic.setFontItalic(true);
100   setFormat(Italic, italic, Settings::Default);
101
102   QTextCharFormat underline; underline.setFontUnderline(true);
103   setFormat(Underline, underline, Settings::Default);
104
105   // All other formats should be defined in derived classes.
106 }
107
108 UiStyle::~ UiStyle() {
109   qDeleteAll(_cachedFontMetrics);
110 }
111
112 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
113   if(mode == Settings::Default) {
114     _defaultFormats[ftype] = fmt;
115   } else {
116     UiStyleSettings s(_settingsKey);
117     if(fmt != _defaultFormats[ftype]) {
118       _customFormats[ftype] = fmt;
119       s.setCustomFormat(ftype, fmt);
120     } else {
121       _customFormats.remove(ftype);
122       s.removeCustomFormat(ftype);
123     }
124   }
125   // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
126   _cachedFormats.clear();
127   _cachedFontMetrics.clear();
128 }
129
130 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
131   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
132   else return _defaultFormats.value(ftype, QTextCharFormat());
133 }
134
135 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
136 //       until you _really_ know what you do!
137 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
138   if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
139   if(ftype == Invalid) return QTextCharFormat();
140   // Now we construct the merged format, starting with the default
141   QTextCharFormat fmt = format(None);
142   // First: general message format
143   fmt.merge(format((FormatType)(ftype & 0x0f)));
144   // now more specific ones
145   for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
146     if(ftype & mask) fmt.merge(format((FormatType)mask));
147   }
148   // color codes!
149   if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
150   if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
151   // URL
152   if(ftype & Url) fmt.merge(format(Url));
153   return _cachedFormats[ftype] = fmt;
154 }
155
156 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
157   // QFontMetricsF is not assignable, so we need to store pointers :/
158   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
159   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
160 }
161
162 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
163   if(_formatCodes.contains(code)) return _formatCodes.value(code);
164   return Invalid;
165 }
166
167 QString UiStyle::formatCode(FormatType ftype) const {
168   return _formatCodes.key(ftype);
169 }
170
171 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
172   QList<QTextLayout::FormatRange> formatRanges;
173   QTextLayout::FormatRange range;
174   int i = 0;
175   for(i = 0; i < formatList.count(); i++) {
176     range.format = mergedFormat(formatList.at(i).second);
177     range.start = formatList.at(i).first;
178     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
179     formatRanges.append(range);
180   }
181   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
182   return formatRanges;
183 }
184
185 // This method expects a well-formatted string, there is no error checking!
186 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
187 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
188   QString s = s_;
189   if(s.length() > 65535) {
190     qWarning() << QString("String too long to be styled: %1").arg(s);
191     return StyledString();
192   }
193   StyledString result;
194   result.formatList.append(qMakePair((quint16)0, (quint32)None));
195   quint32 curfmt = (quint32)None;
196   int pos = 0; quint16 length = 0;
197   for(;;) {
198     pos = s.indexOf('%', pos);
199     if(pos < 0) break;
200     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
201       s.remove(pos, 1);
202       pos++;
203       continue;
204     }
205     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
206       if(s[pos+3] == '-') {  // color off
207         curfmt &= 0x003fffff;
208         length = 4;
209       } else {
210         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
211         //TODO: use 99 as transparent color (re mirc color "standard")
212         color &= 0x0f;
213         if(s[pos+3] == 'f') {
214           curfmt &= 0xf0ffffff;
215           curfmt |= (color << 24) | 0x00400000;
216         } else {
217           curfmt &= 0x0fffffff;
218           curfmt |= (color << 28) | 0x00800000;
219         }
220         length = 6;
221       }
222     } else if(s[pos+1] == 'O') { // reset formatting
223       curfmt &= 0x0000000f; // we keep message type-specific formatting
224       length = 2;
225     } else if(s[pos+1] == 'R') { // reverse
226       // TODO: implement reverse formatting
227
228       length = 2;
229     } else { // all others are toggles
230       QString code = QString("%") + s[pos+1];
231       if(s[pos+1] == 'D') code += s[pos+2];
232       FormatType ftype = formatType(code);
233       if(ftype == Invalid) {
234         qWarning() << (QString("Invalid format code in string: %1").arg(s));
235         continue;
236       }
237       curfmt ^= ftype;
238       length = code.length();
239     }
240     s.remove(pos, length);
241     if(pos == result.formatList.last().first)
242       result.formatList.last().second = curfmt;
243     else
244       result.formatList.append(qMakePair((quint16)pos, curfmt));
245   }
246   result.plainText = s;
247   return result;
248 }
249
250 QString UiStyle::mircToInternal(const QString &mirc_) const {
251   QString mirc = mirc_;
252   mirc.replace('%', "%%");      // escape % just to be sure
253   mirc.replace('\x02', "%B");
254   mirc.replace('\x0f', "%O");
255   mirc.replace('\x12', "%R");
256   mirc.replace('\x16', "%R");
257   mirc.replace('\x1d', "%S");
258   mirc.replace('\x1f', "%U");
259
260   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
261   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
262   // %Dc- turns color off.
263   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
264   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
265   int pos = 0;
266   for(;;) {
267     pos = mirc.indexOf('\x03', pos);
268     if(pos < 0) break; // no more mirc color codes
269     QString ins, num;
270     int l = mirc.length();
271     int i = pos + 1;
272     // check for fg color
273     if(i < l && mirc[i].isDigit()) {
274       num = mirc[i++];
275       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
276       else num.prepend('0');
277       ins = QString("%Dcf%1").arg(num);
278
279       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
280         i++;
281         num = mirc[i++];
282         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
283         else num.prepend('0');
284         ins += QString("%Dcb%1").arg(num);
285       }
286     } else {
287       ins = "%Dc-";
288     }
289     mirc.replace(pos, i-pos, ins);
290   }
291   return mirc;
292 }
293
294 /***********************************************************************************/
295 UiStyle::StyledMessage::StyledMessage(const Message &msg)
296   : Message(msg)
297 {
298 }
299
300 void UiStyle::StyledMessage::style(UiStyle *style) const {
301   QString user = userFromMask(sender());
302   QString host = hostFromMask(sender());
303   QString nick = nickFromMask(sender());
304   QString txt = style->mircToInternal(contents());
305   QString bufferName = bufferInfo().bufferName();
306   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
307
308   QString t;
309   switch(type()) {
310     case Message::Plain:
311       t = tr("%D0%1").arg(txt); break;
312     case Message::Notice:
313       t = tr("%Dn%1").arg(txt); break;
314     case Message::Server:
315       t = tr("%Ds%1").arg(txt); break;
316     case Message::Error:
317       t = tr("%De%1").arg(txt); break;
318     case Message::Join:
319       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
320     case Message::Part:
321       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
322       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
323       break;
324     case Message::Quit:
325       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
326       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
327       break;
328     case Message::Kick: {
329         QString victim = txt.section(" ", 0, 0);
330         QString kickmsg = txt.section(" ", 1);
331         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
332         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
333       }
334       break;
335     case Message::Nick:
336       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
337       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
338       break;
339     case Message::Mode:
340       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
341       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
342       break;
343     case Message::Action:
344       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
345       break;
346     default:
347       t = tr("%De[%1]").arg(txt);
348   }
349   _contents = style->styleString(t);
350 }
351
352 QString UiStyle::StyledMessage::decoratedTimestamp() const {
353   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
354 }
355
356 QString UiStyle::StyledMessage::plainSender() const {
357   switch(type()) {
358     case Message::Plain:
359     case Message::Notice:
360       return nickFromMask(sender());
361     default:
362       return QString();
363   }
364 }
365
366 QString UiStyle::StyledMessage::decoratedSender() const {
367   switch(type()) {
368     case Message::Plain:
369       return tr("<%1>").arg(plainSender()); break;
370     case Message::Notice:
371       return tr("[%1]").arg(plainSender()); break;
372     case Message::Server:
373       return tr("*"); break;
374     case Message::Error:
375       return tr("*"); break;
376     case Message::Join:
377       return tr("-->"); break;
378     case Message::Part:
379       return tr("<--"); break;
380     case Message::Quit:
381       return tr("<--"); break;
382     case Message::Kick:
383       return tr("<-*"); break;
384     case Message::Nick:
385       return tr("<->"); break;
386     case Message::Mode:
387       return tr("***"); break;
388     case Message::Action:
389       return tr("-*-"); break;
390     default:
391       return tr("%1").arg(plainSender());
392   }
393 }
394
395 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
396   switch(type()) {
397     case Message::Plain:
398       return UiStyle::Sender; break;
399     case Message::Notice:
400       return UiStyle::NoticeMsg; break;
401     case Message::Server:
402       return UiStyle::ServerMsg; break;
403     case Message::Error:
404       return UiStyle::ErrorMsg; break;
405     case Message::Join:
406       return UiStyle::JoinMsg; break;
407     case Message::Part:
408       return UiStyle::PartMsg; break;
409     case Message::Quit:
410       return UiStyle::QuitMsg; break;
411     case Message::Kick:
412       return UiStyle::KickMsg; break;
413     case Message::Nick:
414       return UiStyle::RenameMsg; break;
415     case Message::Mode:
416       return UiStyle::ModeMsg; break;
417     case Message::Action:
418       return UiStyle::ActionMsg; break;
419     default:
420       return UiStyle::ErrorMsg;
421   }
422 }
423
424
425 /***********************************************************************************/
426
427 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
428   out << formatList.count();
429   UiStyle::FormatList::const_iterator it = formatList.begin();
430   while(it != formatList.end()) {
431     out << (*it).first << (*it).second;
432     ++it;
433   }
434   return out;
435 }
436
437 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
438   quint16 cnt;
439   in >> cnt;
440   for(quint16 i = 0; i < cnt; i++) {
441     quint16 pos; quint32 ftype;
442     in >> pos >> ftype;
443     formatList.append(qMakePair((quint16)pos, ftype));
444   }
445   return in;
446 }