Add --qss parameter to load a custom stylesheet
[quassel.git] / src / uisupport / qssparser.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
21 #include <QApplication>
22
23 #include "qssparser.h"
24
25 QssParser::QssParser()
26 : _maxSenderHash(0)
27 {
28   _palette = QApplication::palette();
29
30   // Init palette color roles
31   _paletteColorRoles["alternate-base"] = QPalette::AlternateBase;
32   _paletteColorRoles["background"] = QPalette::Background;
33   _paletteColorRoles["base"] = QPalette::Base;
34   _paletteColorRoles["bright-text"] = QPalette::BrightText;
35   _paletteColorRoles["button"] = QPalette::Button;
36   _paletteColorRoles["button-text"] = QPalette::ButtonText;
37   _paletteColorRoles["dark"] = QPalette::Dark;
38   _paletteColorRoles["foreground"] = QPalette::Foreground;
39   _paletteColorRoles["highlight"] = QPalette::Highlight;
40   _paletteColorRoles["highlighted-text"] = QPalette::HighlightedText;
41   _paletteColorRoles["light"] = QPalette::Light;
42   _paletteColorRoles["link"] = QPalette::Link;
43   _paletteColorRoles["link-visited"] = QPalette::LinkVisited;
44   _paletteColorRoles["mid"] = QPalette::Mid;
45   _paletteColorRoles["midlight"] = QPalette::Midlight;
46   _paletteColorRoles["shadow"] = QPalette::Shadow;
47   _paletteColorRoles["text"] = QPalette::Text;
48   _paletteColorRoles["tooltip-base"] = QPalette::ToolTipBase;
49   _paletteColorRoles["tooltip-text"] = QPalette::ToolTipText;
50   _paletteColorRoles["window"] = QPalette::Window;
51   _paletteColorRoles["window-text"] = QPalette::WindowText;
52 }
53
54 void QssParser::processStyleSheet(QString &ss) {
55   if(ss.isEmpty())
56     return;
57
58   // Now we have the stylesheet itself in ss, start parsing
59   // Palette definitions first, so we can apply roles later on
60   QRegExp paletterx("(Palette[^{]*)\\{([^}]+)\\}");
61   int pos = 0;
62   while((pos = paletterx.indexIn(ss, pos)) >= 0) {
63     parsePaletteData(paletterx.cap(1).trimmed(), paletterx.cap(2).trimmed());
64     pos += paletterx.matchedLength();
65   }
66
67   // Now we can parse the rest of our custom blocks
68   QRegExp blockrx("((?:ChatLine|BufferList|NickList|TreeView)[^{]*)\\{([^}]+)\\}");
69   pos = 0;
70   while((pos = blockrx.indexIn(ss, pos)) >= 0) {
71     //qDebug() << blockrx.cap(1) << blockrx.cap(2);
72
73     if(blockrx.cap(1).startsWith("ChatLine"))
74       parseChatLineData(blockrx.cap(1).trimmed(), blockrx.cap(2).trimmed());
75     //else
76     // TODO: add moar here
77
78     pos += blockrx.matchedLength();
79   }
80
81 }
82
83 void QssParser::parseChatLineData(const QString &decl, const QString &contents) {
84   quint64 fmtType = parseFormatType(decl);
85   if(fmtType == UiStyle::Invalid)
86     return;
87
88   QTextCharFormat format;
89
90   foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
91     int idx = line.indexOf(':');
92     if(idx <= 0) {
93       qWarning() << Q_FUNC_INFO << tr("Invalid property declaration: %1").arg(line.trimmed());
94       continue;
95     }
96     QString property = line.left(idx).trimmed();
97     QString value = line.mid(idx + 1).simplified();
98
99     if(property == "background" || property == "background-color")
100       format.setBackground(parseBrush(value));
101     else if(property == "foreground" || property == "color")
102       format.setForeground(parseBrush(value));
103
104     // font-related properties
105     else if(property.startsWith("font")) {
106       if(property == "font")
107         parseFont(value, &format);
108       else if(property == "font-style")
109         parseFontStyle(value, &format);
110       else if(property == "font-weight")
111         parseFontWeight(value, &format);
112       else if(property == "font-size")
113         parseFontSize(value, &format);
114       else if(property == "font-family")
115         parseFontFamily(value, &format);
116       else {
117         qWarning() << Q_FUNC_INFO << tr("Invalid font property: %1").arg(line);
118         continue;
119       }
120     }
121
122     else {
123       qWarning() << Q_FUNC_INFO << tr("Unknown ChatLine property: %1").arg(property);
124     }
125   }
126
127   _formats[fmtType] = format;
128 }
129
130 quint64 QssParser::parseFormatType(const QString &decl) {
131   QRegExp rx("ChatLine(?:::(\\w+))?(?:#(\\w+))?(?:\\[([=-,\\\"\\w\\s]+)\\])?\\s*");
132   // $1: subelement; $2: msgtype; $3: conditionals
133   if(!rx.exactMatch(decl)) {
134     qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
135     return UiStyle::Invalid;
136   }
137   QString subElement = rx.cap(1);
138   QString msgType = rx.cap(2);
139   QString conditions = rx.cap(3);
140
141   quint64 fmtType = 0;
142
143   // First determine the subelement
144   if(!subElement.isEmpty()) {
145     if(subElement == "timestamp")
146       fmtType |= UiStyle::Timestamp;
147     else if(subElement == "sender")
148       fmtType |= UiStyle::Sender;
149     else if(subElement == "nick")
150       fmtType |= UiStyle::Nick;
151     else if(subElement == "contents")
152       fmtType |= UiStyle::Contents;
153     else if(subElement == "hostmask")
154       fmtType |= UiStyle::Hostmask;
155     else if(subElement == "modeflags")
156       fmtType |= UiStyle::ModeFlags;
157     else {
158       qWarning() << Q_FUNC_INFO << tr("Invalid subelement name in %1").arg(decl);
159       return UiStyle::Invalid;
160     }
161   }
162
163   // Now, figure out the message type
164   if(!msgType.isEmpty()) {
165     if(msgType == "plain")
166       fmtType |= UiStyle::PlainMsg;
167     else if(msgType == "notice")
168       fmtType |= UiStyle::NoticeMsg;
169     else if(msgType == "action")
170       fmtType |= UiStyle::ActionMsg;
171     else if(msgType == "nick")
172       fmtType |= UiStyle::NickMsg;
173     else if(msgType == "mode")
174       fmtType |= UiStyle::ModeMsg;
175     else if(msgType == "join")
176       fmtType |= UiStyle::JoinMsg;
177     else if(msgType == "part")
178       fmtType |= UiStyle::PartMsg;
179     else if(msgType == "quit")
180       fmtType |= UiStyle::QuitMsg;
181     else if(msgType == "kick")
182       fmtType |= UiStyle::KickMsg;
183     else if(msgType == "kill")
184       fmtType |= UiStyle::KillMsg;
185     else if(msgType == "server")
186       fmtType |= UiStyle::ServerMsg;
187     else if(msgType == "info")
188       fmtType |= UiStyle::InfoMsg;
189     else if(msgType == "error")
190       fmtType |= UiStyle::ErrorMsg;
191     else if(msgType == "daychange")
192       fmtType |= UiStyle::DayChangeMsg;
193     else {
194       qWarning() << Q_FUNC_INFO << tr("Invalid message type in %1").arg(decl);
195     }
196   }
197
198   // Next up: conditional (formats, labels, nickhash)
199   QRegExp condRx("\\s*(\\w+)\\s*=\\s*\"(\\w+)\"\\s*");
200   if(!conditions.isEmpty()) {
201     foreach(const QString &cond, conditions.split(',', QString::SkipEmptyParts)) {
202       if(!condRx.exactMatch(cond)) {
203         qWarning() << Q_FUNC_INFO << tr("Invalid condition %1").arg(cond);
204         return UiStyle::Invalid;
205       }
206       QString condName = condRx.cap(1);
207       QString condValue = condRx.cap(2);
208       if(condName == "label") {
209         quint64 labeltype = 0;
210         if(condValue == "highlight")
211           labeltype = UiStyle::Highlight;
212         else {
213           qWarning() << Q_FUNC_INFO << tr("Invalid message label: %1").arg(condValue);
214           return UiStyle::Invalid;
215         }
216         fmtType |= (labeltype << 32);
217       } else if(condName == "sender") {
218         if(condValue == "self")
219           fmtType |= (quint64)UiStyle::OwnMsg << 32; // sender="self" is actually treated as a label
220           else {
221             bool ok = true;
222             quint64 val = condValue.toUInt(&ok, 16);
223             if(!ok) {
224               qWarning() << Q_FUNC_INFO << tr("Invalid senderhash specification: %1").arg(condValue);
225               return UiStyle::Invalid;
226             }
227             if(val >= 16) {
228               qWarning() << Q_FUNC_INFO << tr("Senderhash can be at most \"0x0f\"!");
229               return UiStyle::Invalid;
230             }
231             fmtType |= val << 48;
232           }
233       } else if(condName == "format") {
234         if(condValue == "bold")
235           fmtType |= UiStyle::Bold;
236         if(condValue == "italic")
237           fmtType |= UiStyle::Italic;
238         if(condValue == "underline")
239           fmtType |= UiStyle::Underline;
240         if(condValue == "reverse")
241           fmtType |= UiStyle::Reverse;
242         else {
243           qWarning() << Q_FUNC_INFO << tr("Invalid format name: %1").arg(condValue);
244           return UiStyle::Invalid;
245         }
246
247       }
248       // TODO: colors
249     }
250   }
251
252   return fmtType;
253 }
254
255 // Palette { ... } specifies the application palette
256 // ColorGroups can be specified like pseudo states, chaining is OR (contrary to normal CSS handling):
257 //   Palette:inactive:disabled { ... } applies to both the Inactive and the Disabled state
258 void QssParser::parsePaletteData(const QString &decl, const QString &contents) {
259   QList<QPalette::ColorGroup> colorGroups;
260
261   // Check if we want to apply this palette definition for particular ColorGroups
262   QRegExp rx("Palette((:(normal|active|inactive|disabled))*)");
263   if(!rx.exactMatch(decl)) {
264     qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
265     return;
266   }
267   if(!rx.cap(1).isEmpty()) {
268     QStringList groups = rx.cap(1).split(':', QString::SkipEmptyParts);
269     foreach(QString g, groups) {
270       if((g == "normal" || g == "active") && !colorGroups.contains(QPalette::Active))
271         colorGroups.append(QPalette::Active);
272       else if(g == "inactive" && !colorGroups.contains(QPalette::Inactive))
273         colorGroups.append(QPalette::Inactive);
274       else if(g == "disabled" && !colorGroups.contains(QPalette::Disabled))
275         colorGroups.append(QPalette::Disabled);
276     }
277   }
278
279   // Now let's go through the roles
280   foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
281     int idx = line.indexOf(':');
282     if(idx <= 0) {
283       qWarning() << Q_FUNC_INFO << tr("Invalid palette role assignment: %1").arg(line.trimmed());
284       continue;
285     }
286     QString rolestr = line.left(idx).trimmed();
287     QString brushstr = line.mid(idx + 1).trimmed();
288     if(!_paletteColorRoles.contains(rolestr)) {
289       qWarning() << Q_FUNC_INFO << tr("Unknown palette role name: %1").arg(rolestr);
290       continue;
291     }
292     QBrush brush = parseBrush(brushstr);
293     if(colorGroups.count()) {
294       foreach(QPalette::ColorGroup group, colorGroups)
295         _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
296     } else
297       _palette.setBrush(_paletteColorRoles.value(rolestr), brush);
298   }
299 }
300
301 QBrush QssParser::parseBrush(const QString &str, bool *ok) {
302   if(ok)
303     *ok = false;
304   QColor c = parseColor(str);
305   if(c.isValid()) {
306     if(ok)
307       *ok = true;
308     return QBrush(c);
309   }
310
311   if(str.startsWith("palette")) { // Palette color role
312     QRegExp rx("palette\\s*\\(\\s*([a-z-]+)\\s*\\)");
313     if(!rx.exactMatch(str)) {
314       qWarning() << Q_FUNC_INFO << tr("Invalid palette color role specification: %1").arg(str);
315       return QBrush();
316     }
317     if(!_paletteColorRoles.contains(rx.cap(1))) {
318       qWarning() << Q_FUNC_INFO << tr("Unknown palette color role: %1").arg(rx.cap(1));
319       return QBrush();
320     }
321     return QBrush(_palette.brush(_paletteColorRoles.value(rx.cap(1))));
322
323   } else if(str.startsWith("qlineargradient")) {
324     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
325     QRegExp rx(QString("qlineargradient\\s*\\(\\s*x1:%1,\\s*y1:%1,\\s*x2:%1,\\s*y2:%1,(.+)\\)").arg(rxFloat));
326     if(!rx.exactMatch(str)) {
327       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
328       return QBrush();
329     }
330     qreal x1 = rx.cap(1).toDouble();
331     qreal y1 = rx.cap(2).toDouble();
332     qreal x2 = rx.cap(3).toDouble();
333     qreal y2 = rx.cap(4).toDouble();
334     QGradientStops stops = parseGradientStops(rx.cap(5).trimmed());
335     if(!stops.count()) {
336       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
337       return QBrush();
338     }
339     QLinearGradient gradient(x1, y1, x2, y2);
340     gradient.setStops(stops);
341     if(ok)
342       *ok = true;
343     return QBrush(gradient);
344
345   } else if(str.startsWith("qconicalgradient")) {
346     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
347     QRegExp rx(QString("qconicalgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*angle:%1,(.+)\\)").arg(rxFloat));
348     if(!rx.exactMatch(str)) {
349       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
350       return QBrush();
351     }
352     qreal cx = rx.cap(1).toDouble();
353     qreal cy = rx.cap(2).toDouble();
354     qreal angle = rx.cap(3).toDouble();
355     QGradientStops stops = parseGradientStops(rx.cap(4).trimmed());
356     if(!stops.count()) {
357       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
358       return QBrush();
359     }
360     QConicalGradient gradient(cx, cy, angle);
361     gradient.setStops(stops);
362     if(ok)
363       *ok = true;
364     return QBrush(gradient);
365
366   } else if(str.startsWith("qradialgradient")) {
367     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
368     QRegExp rx(QString("qradialgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*radius:%1,\\s*fx:%1,\\s*fy:%1,(.+)\\)").arg(rxFloat));
369     if(!rx.exactMatch(str)) {
370       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
371       return QBrush();
372     }
373     qreal cx = rx.cap(1).toDouble();
374     qreal cy = rx.cap(2).toDouble();
375     qreal radius = rx.cap(3).toDouble();
376     qreal fx = rx.cap(4).toDouble();
377     qreal fy = rx.cap(5).toDouble();
378     QGradientStops stops = parseGradientStops(rx.cap(6).trimmed());
379     if(!stops.count()) {
380       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
381       return QBrush();
382     }
383     QRadialGradient gradient(cx, cy, radius, fx, fy);
384     gradient.setStops(stops);
385     if(ok)
386       *ok = true;
387     return QBrush(gradient);
388   }
389
390   return QBrush();
391 }
392
393 QColor QssParser::parseColor(const QString &str) {
394   if(str.startsWith("rgba")) {
395     ColorTuple tuple = parseColorTuple(str.mid(4));
396     if(tuple.count() == 4)
397       return QColor(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
398   } else if(str.startsWith("rgb")) {
399     ColorTuple tuple = parseColorTuple(str.mid(3));
400     if(tuple.count() == 3)
401       return QColor(tuple.at(0), tuple.at(1), tuple.at(2));
402   } else if(str.startsWith("hsva")) {
403     ColorTuple tuple = parseColorTuple(str.mid(4));
404     if(tuple.count() == 4) {
405       QColor c;
406       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
407       return c;
408     }
409   } else if(str.startsWith("hsv")) {
410     ColorTuple tuple = parseColorTuple(str.mid(3));
411     if(tuple.count() == 3) {
412       QColor c;
413       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2));
414       return c;
415     }
416   } else {
417     QRegExp rx("#?[0-9A-Fa-z]+");
418     if(rx.exactMatch(str))
419       return QColor(str);
420   }
421   return QColor();
422 }
423
424 // get a list of comma-separated int values or percentages (rel to 0-255)
425 QssParser::ColorTuple QssParser::parseColorTuple(const QString &str) {
426   ColorTuple result;
427   QRegExp rx("\\(((\\s*[0-9]{1,3}%?\\s*)(,\\s*[0-9]{1,3}%?\\s*)*)\\)");
428   if(!rx.exactMatch(str.trimmed())) {
429     return ColorTuple();
430   }
431   QStringList values = rx.cap(1).split(',');
432   foreach(QString v, values) {
433     qreal val;
434     bool perc = false;
435     bool ok;
436     v = v.trimmed();
437     if(v.endsWith('%')) {
438       perc = true;
439       v.chop(1);
440     }
441     val = (qreal)v.toUInt(&ok);
442     if(!ok)
443       return ColorTuple();
444     if(perc)
445       val = 255 * val/100;
446     result.append(val);
447   }
448   return result;
449 }
450
451 QGradientStops QssParser::parseGradientStops(const QString &str_) {
452   QString str = str_;
453   QGradientStops result;
454   static QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
455   QRegExp rx(QString("\\s*,?\\s*stop:\\s*(%1)\\s+([^:]+)(,\\s*stop:|$)").arg(rxFloat));
456   int idx;
457   while((idx = rx.indexIn(str)) == 0) {
458     qreal x = rx.cap(1).toDouble();
459     QColor c = parseColor(rx.cap(3));
460     if(!c.isValid())
461       return QGradientStops();
462     result << QGradientStop(x, c);
463     str.remove(0, rx.matchedLength() - rx.cap(4).length());
464   }
465   if(!str.trimmed().isEmpty())
466     return QGradientStops();
467
468   return result;
469 }
470
471 /******** Font Properties ********/
472
473 void QssParser::parseFont(const QString& value, QTextCharFormat* format) {
474   QRegExp rx("((?:(?:normal|italic|oblique|bold|100|200|300|400|500|600|700|800|900) ){0,2}) ?(\\d+)(pt|px)? \"(.*)\"");
475   if(!rx.exactMatch(value)) {
476     qWarning() << Q_FUNC_INFO << tr("Invalid font specification: %1").arg(value);
477     return;
478   }
479   format->setFontItalic(false);
480   format->setFontWeight(QFont::Normal);
481   QStringList proplist = rx.cap(1).split(' ', QString::SkipEmptyParts);
482   foreach(QString prop, proplist) {
483     if(prop == "italic")
484       format->setFontItalic(true);
485     //else if(prop == "oblique")
486     //  format->setStyle(QFont::StyleOblique);
487     else if(prop == "bold")
488       format->setFontWeight(QFont::Bold);
489     else { // number
490       int w = prop.toInt();
491       format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
492     }
493   }
494
495   if(rx.cap(3) == "px")
496     format->setProperty(QTextFormat::FontPixelSize, rx.cap(2).toInt());
497   else
498     format->setFontPointSize(rx.cap(2).toInt());
499
500   format->setFontFamily(rx.cap(4));
501 }
502
503 void QssParser::parseFontStyle(const QString& value, QTextCharFormat* format) {
504   if(value == "normal")
505     format->setFontItalic(false);
506   else if(value == "italic")
507     format->setFontItalic(true);
508   //else if(value == "oblique")
509   //  format->setStyle(QFont::StyleOblique);
510   else {
511     qWarning() << Q_FUNC_INFO << tr("Invalid font style specification: %1").arg(value);
512   }
513 }
514
515 void QssParser::parseFontWeight(const QString& value, QTextCharFormat* format) {
516   if(value == "normal")
517     format->setFontWeight(QFont::Normal);
518   else if(value == "bold")
519     format->setFontWeight(QFont::Bold);
520   else {
521     bool ok;
522     int w = value.toInt(&ok);
523     if(!ok) {
524       qWarning() << Q_FUNC_INFO << tr("Invalid font weight specification: %1").arg(value);
525       return;
526     }
527     format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
528   }
529 }
530
531 void QssParser::parseFontSize(const QString& value, QTextCharFormat* format) {
532   QRegExp rx("\\(d+)(pt|px)");
533   if(!rx.exactMatch(value)) {
534     qWarning() << Q_FUNC_INFO << tr("Invalid font size specification: %1").arg(value);
535     return;
536   }
537   if(rx.cap(2) == "px")
538     format->setProperty(QTextFormat::FontPixelSize, rx.cap(1).toInt());
539   else
540     format->setFontPointSize(rx.cap(1).toInt());
541 }
542
543 void QssParser::parseFontFamily(const QString& value, QTextCharFormat* format) {
544   QString family = value;
545   if(family.startsWith('"') && family.endsWith('"')) {
546     family = family.mid(1, family.length() - 2);
547   }
548   format->setFontFamily(family);
549 }