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