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