Handle all message types properly in UiStyle; eliminate msgtype format codes
[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 "qssparser.h"
23 #include "quassel.h"
24 #include "uistyle.h"
25 #include "uisettings.h"
26 #include "util.h"
27
28 UiStyle::UiStyle() {
29   // register FormatList if that hasn't happened yet
30   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
31   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
32     qRegisterMetaType<FormatList>("UiStyle::FormatList");
33     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
34     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
35   }
36
37   // Now initialize the mapping between FormatCodes and FormatTypes...
38   _formatCodes["%O"] = None;
39   _formatCodes["%B"] = Bold;
40   _formatCodes["%S"] = Italic;
41   _formatCodes["%U"] = Underline;
42   _formatCodes["%R"] = Reverse;
43
44   _formatCodes["%DN"] = Nick;
45   _formatCodes["%DH"] = Hostmask;
46   _formatCodes["%DC"] = ChannelName;
47   _formatCodes["%DM"] = ModeFlags;
48   _formatCodes["%DU"] = Url;
49
50   loadStyleSheet();
51 }
52
53 UiStyle::~ UiStyle() {
54   qDeleteAll(_metricsCache);
55 }
56
57 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
58   return _formatCache.value(key, QTextCharFormat());
59 }
60
61 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
62   return cachedFormat(formatType | ((quint64)messageLabel << 32));
63 }
64
65 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
66   _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
67 }
68
69 // Merge a subelement format into an existing message format
70 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint32 label) {
71   quint64 key = ftype | ((quint64)label << 32);
72
73   // start with the most general format and then specialize
74   fmt.merge(cachedFormat(key & 0x00000000fffffff0));  // basic subelement format
75   fmt.merge(cachedFormat(key & 0x00000000ffffffff));  // subelement + msgtype
76   fmt.merge(cachedFormat(key & 0xffff0000fffffff0));  // subelement + nickhash
77   fmt.merge(cachedFormat(key & 0xffff0000ffffffff));  // subelement + nickhash + msgtype
78   fmt.merge(cachedFormat(key & 0x0000fffffffffff0));  // label + subelement
79   fmt.merge(cachedFormat(key & 0x0000ffffffffffff));  // label + subelement + msgtype
80   fmt.merge(cachedFormat(key & 0xfffffffffffffff0));  // label + subelement + nickhash
81   fmt.merge(cachedFormat(key & 0xffffffffffffffff));  // label + subelement + nickhash + msgtype
82 }
83
84 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
85 //       until you _really_ know what you do!
86 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label) {
87   if(ftype == Invalid)
88     return QTextCharFormat();
89
90   quint64 key = ftype | ((quint64)label << 32);
91
92   // check if we have exactly this format readily cached already
93   QTextCharFormat fmt = cachedFormat(key);
94   if(fmt.properties().count())
95     return fmt;
96
97   fmt.merge(cachedFormat(key & 0x0000000000000000));  // basic
98   fmt.merge(cachedFormat(key & 0x000000000000000f));  // msgtype
99   fmt.merge(cachedFormat(key & 0x0000ffff00000000));  // label
100   fmt.merge(cachedFormat(key & 0x0000ffff0000000f));  // label + msgtype
101
102   // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
103   //       or "foreground 01 and background 03"
104   if((ftype & 0xfff0)) { // element format
105     for(quint32 mask = 0x10; mask <= 0x2000; mask <<= 1) {
106       if(ftype & mask) {
107         mergeSubElementFormat(fmt, ftype & 0xffff, label);
108       }
109     }
110   }
111
112   // Now we handle color codes
113   if(ftype & 0x00400000)
114     mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
115   if(ftype & 0x00800000)
116     mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
117   if((ftype & 0x00c00000) == 0x00c00000)
118     mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
119
120   // URL
121   if(ftype & Url)
122     mergeSubElementFormat(fmt, ftype & Url, label);
123
124   setCachedFormat(fmt, ftype, label);
125   return fmt;
126 }
127
128 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
129   // QFontMetricsF is not assignable, so we need to store pointers :/
130   quint64 key = ftype | ((quint64)label << 32);
131
132   if(_metricsCache.contains(key))
133     return _metricsCache.value(key);
134
135   return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
136 }
137
138 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) const {
139   switch(msgType) {
140     case Message::Plain:
141       return PlainMsg;
142     case Message::Notice:
143       return NoticeMsg;
144     case Message::Action:
145       return ActionMsg;
146     case Message::Nick:
147       return NickMsg;
148     case Message::Mode:
149       return ModeMsg;
150     case Message::Join:
151       return JoinMsg;
152     case Message::Part:
153       return PartMsg;
154     case Message::Quit:
155       return QuitMsg;
156     case Message::Kick:
157       return KickMsg;
158     case Message::Kill:
159       return KillMsg;
160     case Message::Server:
161       return ServerMsg;
162     case Message::Info:
163       return InfoMsg;
164     case Message::Error:
165       return ErrorMsg;
166     case Message::DayChange:
167       return DayChangeMsg;
168   }
169   Q_ASSERT(false); // we need to handle all message types
170   return ErrorMsg;
171 }
172
173 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
174   if(_formatCodes.contains(code)) return _formatCodes.value(code);
175   return Invalid;
176 }
177
178 QString UiStyle::formatCode(FormatType ftype) const {
179   return _formatCodes.key(ftype);
180 }
181
182 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
183   QList<QTextLayout::FormatRange> formatRanges;
184   QTextLayout::FormatRange range;
185   int i = 0;
186   for(i = 0; i < formatList.count(); i++) {
187     range.format = format(formatList.at(i).second);
188     range.start = formatList.at(i).first;
189     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
190     formatRanges.append(range);
191   }
192   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
193   return formatRanges;
194 }
195
196 // This method expects a well-formatted string, there is no error checking!
197 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
198 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
199   QString s = s_;
200   if(s.length() > 65535) {
201     qWarning() << QString("String too long to be styled: %1").arg(s);
202     return StyledString();
203   }
204   StyledString result;
205   result.formatList.append(qMakePair((quint16)0, (quint32)None));
206   quint32 curfmt = baseFormat;
207   int pos = 0; quint16 length = 0;
208   for(;;) {
209     pos = s.indexOf('%', pos);
210     if(pos < 0) break;
211     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
212       s.remove(pos, 1);
213       pos++;
214       continue;
215     }
216     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
217       if(s[pos+3] == '-') {  // color off
218         curfmt &= 0x003fffff;
219         length = 4;
220       } else {
221         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
222         //TODO: use 99 as transparent color (re mirc color "standard")
223         color &= 0x0f;
224         if(s[pos+3] == 'f') {
225           curfmt &= 0xf0ffffff;
226           curfmt |= (color << 24) | 0x00400000;
227         } else {
228           curfmt &= 0x0fffffff;
229           curfmt |= (color << 28) | 0x00800000;
230         }
231         length = 6;
232       }
233     } else if(s[pos+1] == 'O') { // reset formatting
234       curfmt &= 0x0000000f; // we keep message type-specific formatting
235       length = 2;
236     } else if(s[pos+1] == 'R') { // reverse
237       // TODO: implement reverse formatting
238
239       length = 2;
240     } else { // all others are toggles
241       QString code = QString("%") + s[pos+1];
242       if(s[pos+1] == 'D') code += s[pos+2];
243       FormatType ftype = formatType(code);
244       if(ftype == Invalid) {
245         qWarning() << (QString("Invalid format code in string: %1").arg(s));
246         continue;
247       }
248       curfmt ^= ftype;
249       length = code.length();
250     }
251     s.remove(pos, length);
252     if(pos == result.formatList.last().first)
253       result.formatList.last().second = curfmt;
254     else
255       result.formatList.append(qMakePair((quint16)pos, curfmt));
256   }
257   result.plainText = s;
258   return result;
259 }
260
261 QString UiStyle::mircToInternal(const QString &mirc_) const {
262   QString mirc = mirc_;
263   mirc.replace('%', "%%");      // escape % just to be sure
264   mirc.replace('\x02', "%B");
265   mirc.replace('\x0f', "%O");
266   mirc.replace('\x12', "%R");
267   mirc.replace('\x16', "%R");
268   mirc.replace('\x1d', "%S");
269   mirc.replace('\x1f', "%U");
270
271   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
272   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
273   // %Dc- turns color off.
274   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
275   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
276   int pos = 0;
277   for(;;) {
278     pos = mirc.indexOf('\x03', pos);
279     if(pos < 0) break; // no more mirc color codes
280     QString ins, num;
281     int l = mirc.length();
282     int i = pos + 1;
283     // check for fg color
284     if(i < l && mirc[i].isDigit()) {
285       num = mirc[i++];
286       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
287       else num.prepend('0');
288       ins = QString("%Dcf%1").arg(num);
289
290       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
291         i++;
292         num = mirc[i++];
293         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
294         else num.prepend('0');
295         ins += QString("%Dcb%1").arg(num);
296       }
297     } else {
298       ins = "%Dc-";
299     }
300     mirc.replace(pos, i-pos, ins);
301   }
302   return mirc;
303 }
304
305 /***********************************************************************************/
306 UiStyle::StyledMessage::StyledMessage(const Message &msg)
307   : Message(msg)
308 {
309 }
310
311 void UiStyle::StyledMessage::style(UiStyle *style) const {
312   QString user = userFromMask(sender());
313   QString host = hostFromMask(sender());
314   QString nick = nickFromMask(sender());
315   QString txt = style->mircToInternal(contents());
316   QString bufferName = bufferInfo().bufferName();
317   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
318
319   QString t;
320   switch(type()) {
321     case Message::Plain:
322       //: Plain Message
323       t = tr("%1").arg(txt); break;
324     case Message::Notice:
325       //: Notice Message
326       t = tr("%1").arg(txt); break;
327     case Message::Action:
328       //: Action Message
329       t = tr("%DN%1%DN %2").arg(nick).arg(txt);
330       break;
331     case Message::Nick:
332       //: Nick Message
333       if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
334       else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
335       break;
336     case Message::Mode:
337       //: Mode Message
338       if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
339       else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
340       break;
341     case Message::Join:
342       //: Join Message
343       t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
344     case Message::Part:
345       //: Part Message
346       t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
347       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
348       break;
349     case Message::Quit:
350       //: Quit Message
351       t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
352       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
353       break;
354     case Message::Kick: {
355         QString victim = txt.section(" ", 0, 0);
356         QString kickmsg = txt.section(" ", 1);
357         //: Kick Message
358         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
359         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
360       }
361       break;
362     //case Message::Kill: FIXME
363
364     case Message::Server:
365       //: Server Message
366       t = tr("%1").arg(txt); break;
367     case Message::Info:
368       //: Info Message
369       t = tr("%1").arg(txt); break;
370     case Message::Error:
371       //: Error Message
372       t = tr("%1").arg(txt); break;
373     case Message::DayChange:
374       //: Day Change Message
375       t = tr("{Day changed to %1}").arg(timestamp().toString());
376       break;
377     default:
378       t = tr("[%1]").arg(txt);
379   }
380   _contents = style->styleString(t, style->formatType(type()));
381 }
382
383 QString UiStyle::StyledMessage::decoratedTimestamp() const {
384   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
385 }
386
387 QString UiStyle::StyledMessage::plainSender() const {
388   switch(type()) {
389     case Message::Plain:
390     case Message::Notice:
391       return nickFromMask(sender());
392     default:
393       return QString();
394   }
395 }
396
397 QString UiStyle::StyledMessage::decoratedSender() const {
398   switch(type()) {
399     case Message::Plain:
400       return tr("<%1>").arg(plainSender()); break;
401     case Message::Notice:
402       return tr("[%1]").arg(plainSender()); break;
403 <<<<<<< HEAD
404     case Message::Topic:
405     case Message::Server:
406       return tr("*"); break;
407     case Message::Error:
408       return tr("*"); break;
409 =======
410     case Message::Action:
411       return tr("-*-"); break;
412     case Message::Nick:
413       return tr("<->"); break;
414     case Message::Mode:
415       return tr("***"); break;
416 >>>>>>> Handle all message types properly in UiStyle; eliminate msgtype format codes
417     case Message::Join:
418       return tr("-->"); break;
419     case Message::Part:
420       return tr("<--"); break;
421     case Message::Quit:
422       return tr("<--"); break;
423     case Message::Kick:
424       return tr("<-*"); break;
425     case Message::Kill:
426       return tr("<-x"); break;
427     case Message::Server:
428       return tr("*"); break;
429     case Message::Info:
430       return tr("*"); break;
431     case Message::Error:
432       return tr("*"); break;
433     case Message::DayChange:
434       return tr("-"); break;
435     default:
436       return tr("%1").arg(plainSender());
437   }
438 }
439
440 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
441   switch(type()) {
442     case Message::Plain:
443       // To produce random like but stable nick colorings some sort of hashing should work best.
444       // In this case we just use the qt function qChecksum which produces a
445       // CRC16 hash. This should be fast and 16 bits are more than enough.
446       {
447         QString nick = nickFromMask(sender()).toLower();
448         if(!nick.isEmpty()) {
449           int chopCount = 0;
450           while(nick[nick.count() - 1 - chopCount] == '_') {
451             chopCount++;
452           }
453           nick.chop(chopCount);
454         }
455         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
456         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
457       }
458     case Message::Notice:
459       return UiStyle::NoticeMsg; break;
460     case Message::Topic:
461     case Message::Server:
462       return UiStyle::ServerMsg; break;
463     case Message::Error:
464       return UiStyle::ErrorMsg; break;
465     case Message::Join:
466       return UiStyle::JoinMsg; break;
467     case Message::Part:
468       return UiStyle::PartMsg; break;
469     case Message::Quit:
470       return UiStyle::QuitMsg; break;
471     case Message::Kick:
472       return UiStyle::KickMsg; break;
473     case Message::Nick:
474       return UiStyle::NickMsg; break;
475     case Message::Mode:
476       return UiStyle::ModeMsg; break;
477     case Message::Action:
478       return UiStyle::ActionMsg; break;
479     default:
480       return UiStyle::ErrorMsg;
481   }
482 }
483
484 /***********************************************************************************/
485
486 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
487   out << formatList.count();
488   UiStyle::FormatList::const_iterator it = formatList.begin();
489   while(it != formatList.end()) {
490     out << (*it).first << (*it).second;
491     ++it;
492   }
493   return out;
494 }
495
496 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
497   quint16 cnt;
498   in >> cnt;
499   for(quint16 i = 0; i < cnt; i++) {
500     quint16 pos; quint32 ftype;
501     in >> pos >> ftype;
502     formatList.append(qMakePair((quint16)pos, ftype));
503   }
504   return in;
505 }
506
507 /***********************************************************************************/
508 // Stylesheet handling
509 /***********************************************************************************/
510
511 void UiStyle::loadStyleSheet() {
512   QssParser parser;
513   parser.loadStyleSheet(qApp->styleSheet());
514
515   // TODO handle results
516   QApplication::setPalette(parser.palette());
517
518   qDeleteAll(_metricsCache);
519   _metricsCache.clear();
520   _formatCache = parser.formats();
521 }