f610e6243f6450d1c76d4a6f20d794a33266383e
[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   // TODO: implement setting for nick autocoloring and make a check for it here
132   if ( (ftype & 0x00000fff) == Sender ) 
133   {
134     // If it is not enabled just set ftype to Sender and go on
135   }
136
137   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
138   else return _defaultFormats.value(ftype, QTextCharFormat());
139 }
140
141 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
142 //       until you _really_ know what you do!
143 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
144   if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
145   if(ftype == Invalid) return QTextCharFormat();
146   // Now we construct the merged format, starting with the default
147   QTextCharFormat fmt = format(None);
148   // First: general message format
149   fmt.merge(format((FormatType)(ftype & 0x0f)));
150   // now more specific ones
151   for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
152     if(ftype & mask) fmt.merge(format((FormatType)mask));
153   }
154   // color codes!
155   if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
156   if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
157   // Sender auto colors
158   if((ftype & 0xfff) == 0x200 && (ftype & 0xff000200) != 0x200) fmt.merge(format((FormatType)(ftype & 0xff000200)));
159   // URL
160   if(ftype & Url) fmt.merge(format(Url));
161   return _cachedFormats[ftype] = fmt;
162 }
163
164 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
165   // QFontMetricsF is not assignable, so we need to store pointers :/
166   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
167   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
168 }
169
170 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
171   if(_formatCodes.contains(code)) return _formatCodes.value(code);
172   return Invalid;
173 }
174
175 QString UiStyle::formatCode(FormatType ftype) const {
176   return _formatCodes.key(ftype);
177 }
178
179 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
180   QList<QTextLayout::FormatRange> formatRanges;
181   QTextLayout::FormatRange range;
182   int i = 0;
183   for(i = 0; i < formatList.count(); i++) {
184     range.format = mergedFormat(formatList.at(i).second);
185     range.start = formatList.at(i).first;
186     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
187     formatRanges.append(range);
188   }
189   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
190   return formatRanges;
191 }
192
193 // This method expects a well-formatted string, there is no error checking!
194 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
195 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
196   QString s = s_;
197   if(s.length() > 65535) {
198     qWarning() << QString("String too long to be styled: %1").arg(s);
199     return StyledString();
200   }
201   StyledString result;
202   result.formatList.append(qMakePair((quint16)0, (quint32)None));
203   quint32 curfmt = (quint32)None;
204   int pos = 0; quint16 length = 0;
205   for(;;) {
206     pos = s.indexOf('%', pos);
207     if(pos < 0) break;
208     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
209       s.remove(pos, 1);
210       pos++;
211       continue;
212     }
213     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
214       if(s[pos+3] == '-') {  // color off
215         curfmt &= 0x003fffff;
216         length = 4;
217       } else {
218         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
219         //TODO: use 99 as transparent color (re mirc color "standard")
220         color &= 0x0f;
221         if(s[pos+3] == 'f') {
222           curfmt &= 0xf0ffffff;
223           curfmt |= (color << 24) | 0x00400000;
224         } else {
225           curfmt &= 0x0fffffff;
226           curfmt |= (color << 28) | 0x00800000;
227         }
228         length = 6;
229       }
230     } else if(s[pos+1] == 'O') { // reset formatting
231       curfmt &= 0x0000000f; // we keep message type-specific formatting
232       length = 2;
233     } else if(s[pos+1] == 'R') { // reverse
234       // TODO: implement reverse formatting
235
236       length = 2;
237     } else { // all others are toggles
238       QString code = QString("%") + s[pos+1];
239       if(s[pos+1] == 'D') code += s[pos+2];
240       FormatType ftype = formatType(code);
241       if(ftype == Invalid) {
242         qWarning() << (QString("Invalid format code in string: %1").arg(s));
243         continue;
244       }
245       curfmt ^= ftype;
246       length = code.length();
247     }
248     s.remove(pos, length);
249     if(pos == result.formatList.last().first)
250       result.formatList.last().second = curfmt;
251     else
252       result.formatList.append(qMakePair((quint16)pos, curfmt));
253   }
254   result.plainText = s;
255   return result;
256 }
257
258 QString UiStyle::mircToInternal(const QString &mirc_) const {
259   QString mirc = mirc_;
260   mirc.replace('%', "%%");      // escape % just to be sure
261   mirc.replace('\x02', "%B");
262   mirc.replace('\x0f', "%O");
263   mirc.replace('\x12', "%R");
264   mirc.replace('\x16', "%R");
265   mirc.replace('\x1d', "%S");
266   mirc.replace('\x1f', "%U");
267
268   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
269   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
270   // %Dc- turns color off.
271   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
272   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
273   int pos = 0;
274   for(;;) {
275     pos = mirc.indexOf('\x03', pos);
276     if(pos < 0) break; // no more mirc color codes
277     QString ins, num;
278     int l = mirc.length();
279     int i = pos + 1;
280     // check for fg color
281     if(i < l && mirc[i].isDigit()) {
282       num = mirc[i++];
283       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
284       else num.prepend('0');
285       ins = QString("%Dcf%1").arg(num);
286
287       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
288         i++;
289         num = mirc[i++];
290         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
291         else num.prepend('0');
292         ins += QString("%Dcb%1").arg(num);
293       }
294     } else {
295       ins = "%Dc-";
296     }
297     mirc.replace(pos, i-pos, ins);
298   }
299   return mirc;
300 }
301
302 /***********************************************************************************/
303 UiStyle::StyledMessage::StyledMessage(const Message &msg)
304   : Message(msg)
305 {
306 }
307
308 void UiStyle::StyledMessage::style(UiStyle *style) const {
309   QString user = userFromMask(sender());
310   QString host = hostFromMask(sender());
311   QString nick = nickFromMask(sender());
312   QString txt = style->mircToInternal(contents());
313   QString bufferName = bufferInfo().bufferName();
314   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
315
316   QString t;
317   switch(type()) {
318     case Message::Plain:
319       t = tr("%D0%1").arg(txt); break;
320     case Message::Notice:
321       t = tr("%Dn%1").arg(txt); break;
322     case Message::Server:
323       t = tr("%Ds%1").arg(txt); break;
324     case Message::Error:
325       t = tr("%De%1").arg(txt); break;
326     case Message::Join:
327       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
328     case Message::Part:
329       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
330       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
331       break;
332     case Message::Quit:
333       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
334       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
335       break;
336     case Message::Kick: {
337         QString victim = txt.section(" ", 0, 0);
338         QString kickmsg = txt.section(" ", 1);
339         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
340         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
341       }
342       break;
343     case Message::Nick:
344       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
345       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
346       break;
347     case Message::Mode:
348       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
349       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
350       break;
351     case Message::Action:
352       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
353       break;
354     default:
355       t = tr("%De[%1]").arg(txt);
356   }
357   _contents = style->styleString(t);
358 }
359
360 QString UiStyle::StyledMessage::decoratedTimestamp() const {
361   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
362 }
363
364 QString UiStyle::StyledMessage::plainSender() const {
365   switch(type()) {
366     case Message::Plain:
367     case Message::Notice:
368       return nickFromMask(sender());
369     default:
370       return QString();
371   }
372 }
373
374 QString UiStyle::StyledMessage::decoratedSender() const {
375   switch(type()) {
376     case Message::Plain:
377       return tr("<%1>").arg(plainSender()); break;
378     case Message::Notice:
379       return tr("[%1]").arg(plainSender()); break;
380     case Message::Server:
381       return tr("*"); break;
382     case Message::Error:
383       return tr("*"); break;
384     case Message::Join:
385       return tr("-->"); break;
386     case Message::Part:
387       return tr("<--"); break;
388     case Message::Quit:
389       return tr("<--"); break;
390     case Message::Kick:
391       return tr("<-*"); break;
392     case Message::Nick:
393       return tr("<->"); break;
394     case Message::Mode:
395       return tr("***"); break;
396     case Message::Action:
397       return tr("-*-"); break;
398     default:
399       return tr("%1").arg(plainSender());
400   }
401 }
402
403 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
404   quint16 hash;
405   switch(type()) {
406     case Message::Plain:
407     // To produce random like but stable nick colorings some sort of hashing should work best.
408     // In this case we just use the qt function qChecksum which produces a
409     // CRC16 hash. This should be fast and 16 bits are more than enough.
410     hash = qChecksum(_sender.toAscii().data(), _sender.toAscii().size());
411     return (UiStyle::FormatType)((((hash % 21) + 1) << 24) + 0x200);
412     case Message::Notice:
413       return UiStyle::NoticeMsg; break;
414     case Message::Server:
415       return UiStyle::ServerMsg; break;
416     case Message::Error:
417       return UiStyle::ErrorMsg; break;
418     case Message::Join:
419       return UiStyle::JoinMsg; break;
420     case Message::Part:
421       return UiStyle::PartMsg; break;
422     case Message::Quit:
423       return UiStyle::QuitMsg; break;
424     case Message::Kick:
425       return UiStyle::KickMsg; break;
426     case Message::Nick:
427       return UiStyle::RenameMsg; break;
428     case Message::Mode:
429       return UiStyle::ModeMsg; break;
430     case Message::Action:
431       return UiStyle::ActionMsg; break;
432     default:
433       return UiStyle::ErrorMsg;
434   }
435 }
436
437
438 /***********************************************************************************/
439
440 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
441   out << formatList.count();
442   UiStyle::FormatList::const_iterator it = formatList.begin();
443   while(it != formatList.end()) {
444     out << (*it).first << (*it).second;
445     ++it;
446   }
447   return out;
448 }
449
450 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
451   quint16 cnt;
452   in >> cnt;
453   for(quint16 i = 0; i < cnt; i++) {
454     quint16 pos; quint32 ftype;
455     in >> pos >> ftype;
456     formatList.append(qMakePair((quint16)pos, ftype));
457   }
458   return in;
459 }