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