Move QssParser out of UiStyle
[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(2) == "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   
102
103 }
104
105 quint64 QssParser::parseFormatType(const QString &decl) {
106   QRegExp rx("ChatLine(?:::(\\w+))?(?:#(\\w+))?(?:\\[([=-,\\\"\\w\\s]+)\\])?\\s*");
107   // $1: subelement; $2: msgtype; $3: conditionals
108   if(!rx.exactMatch(decl)) {
109     qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
110     return UiStyle::Invalid;
111   }
112   QString subElement = rx.cap(1);
113   QString msgType = rx.cap(2);
114   QString conditions = rx.cap(3);
115
116   quint64 fmtType = 0;
117
118   // First determine the subelement
119   if(!subElement.isEmpty()) {
120     if(subElement == "Timestamp")
121       fmtType |= UiStyle::Timestamp;
122     else if(subElement == "Sender")
123       fmtType |= UiStyle::Sender;
124     else if(subElement == "Nick")
125       fmtType |= UiStyle::Nick;
126     else if(subElement == "Hostmask")
127       fmtType |= UiStyle::Hostmask;
128     else if(subElement == "ModeFlags")
129       fmtType |= UiStyle::ModeFlags;
130     else {
131       qWarning() << Q_FUNC_INFO << tr("Invalid subelement name in %1").arg(decl);
132       return UiStyle::Invalid;
133     }
134   }
135
136   // Now, figure out the message type
137   if(!msgType.isEmpty()) {
138     if(msgType == "Plain")
139       fmtType |= UiStyle::PlainMsg;
140     else if(msgType == "Notice")
141       fmtType |= UiStyle::NoticeMsg;
142     else if(msgType == "Server")
143       fmtType |= UiStyle::ServerMsg;
144     else if(msgType == "Error")
145       fmtType |= UiStyle::ErrorMsg;
146     else if(msgType == "Join")
147       fmtType |= UiStyle::JoinMsg;
148     else if(msgType == "Part")
149       fmtType |= UiStyle::PartMsg;
150     else if(msgType == "Quit")
151       fmtType |= UiStyle::QuitMsg;
152     else if(msgType == "Kick")
153       fmtType |= UiStyle::KickMsg;
154     else if(msgType == "Rename")
155       fmtType |= UiStyle::RenameMsg;
156     else if(msgType == "Mode")
157       fmtType |= UiStyle::ModeMsg;
158     else if(msgType == "Action")
159       fmtType |= UiStyle::ActionMsg;
160     else {
161       qWarning() << Q_FUNC_INFO << tr("Invalid message type in %1").arg(decl);
162     }
163   }
164
165   // Next up: conditional (formats, labels, nickhash)
166   QRegExp condRx("\\s*(\\w+)\\s*=\\s*\"(\\w+)\"\\s*");
167   if(!conditions.isEmpty()) {
168     foreach(const QString &cond, conditions.split(',', QString::SkipEmptyParts)) {
169       if(!condRx.exactMatch(cond)) {
170         qWarning() << Q_FUNC_INFO << tr("Invalid condition %1").arg(cond);
171         return UiStyle::Invalid;
172       }
173       QString condName = condRx.cap(1);
174       QString condValue = condRx.cap(2);
175       if(condName == "label") {
176         quint64 labeltype = 0;
177         if(condValue == "highlight")
178           labeltype = UiStyle::Highlight;
179         else {
180           qWarning() << Q_FUNC_INFO << tr("Invalid message label: %1").arg(condValue);
181           return UiStyle::Invalid;
182         }
183         fmtType |= (labeltype << 32);
184       } else if(condName == "sender") {
185         if(condValue == "self")
186           fmtType |= (quint64)UiStyle::OwnMsg << 32; // sender="self" is actually treated as a label
187           else {
188             bool ok = true;
189             quint64 val = condValue.toUInt(&ok, 16);
190             if(!ok) {
191               qWarning() << Q_FUNC_INFO << tr("Invalid senderhash specification: %1").arg(condValue);
192               return UiStyle::Invalid;
193             }
194             if(val >= 255) {
195               qWarning() << Q_FUNC_INFO << tr("Senderhash can be at most \"fe\"!");
196               return UiStyle::Invalid;
197             }
198             fmtType |= val << 48;
199           }
200       }
201       // TODO: colors
202     }
203   }
204
205   return fmtType;
206 }
207
208 // Palette { ... } specifies the application palette
209 // ColorGroups can be specified like pseudo states, chaining is OR (contrary to normal CSS handling):
210 //   Palette:inactive:disabled { ... } applies to both the Inactive and the Disabled state
211 void QssParser::parsePaletteData(const QString &decl, const QString &contents) {
212   QList<QPalette::ColorGroup> colorGroups;
213
214   // Check if we want to apply this palette definition for particular ColorGroups
215   QRegExp rx("Palette((:(normal|active|inactive|disabled))*)");
216   if(!rx.exactMatch(decl)) {
217     qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
218     return;
219   }
220   if(!rx.cap(1).isEmpty()) {
221     QStringList groups = rx.cap(1).split(':', QString::SkipEmptyParts);
222     foreach(QString g, groups) {
223       if((g == "normal" || g == "active") && !colorGroups.contains(QPalette::Active))
224         colorGroups.append(QPalette::Active);
225       else if(g == "inactive" && !colorGroups.contains(QPalette::Inactive))
226         colorGroups.append(QPalette::Inactive);
227       else if(g == "disabled" && !colorGroups.contains(QPalette::Disabled))
228         colorGroups.append(QPalette::Disabled);
229     }
230   }
231
232   // Now let's go through the roles
233   foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
234     int idx = line.indexOf(':');
235     if(idx <= 0) {
236       qWarning() << Q_FUNC_INFO << tr("Invalid palette role assignment: %1").arg(line.trimmed());
237       continue;
238     }
239     QString rolestr = line.left(idx).trimmed();
240     QString brushstr = line.mid(idx + 1).trimmed();
241     if(!_paletteColorRoles.contains(rolestr)) {
242       qWarning() << Q_FUNC_INFO << tr("Unknown palette role name: %1").arg(rolestr);
243       continue;
244     }
245     QBrush brush = parseBrushValue(brushstr);
246     if(colorGroups.count()) {
247       foreach(QPalette::ColorGroup group, colorGroups)
248         _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
249     } else
250       _palette.setBrush(_paletteColorRoles.value(rolestr), brush);
251   }
252 }
253
254 QBrush QssParser::parseBrushValue(const QString &str) {
255   QColor c = parseColorValue(str);
256   if(c.isValid())
257     return QBrush(c);
258
259   if(str.startsWith("palette")) { // Palette color role
260     QRegExp rx("palette\\s*\\(\\s*([a-z-]+)\\s*\\)");
261     if(!rx.exactMatch(str)) {
262       qWarning() << Q_FUNC_INFO << tr("Invalid palette color role specification: %1").arg(str);
263       return QBrush();
264     }
265     if(!_paletteColorRoles.contains(rx.cap(1))) {
266       qWarning() << Q_FUNC_INFO << tr("Unknown palette color role: %1").arg(rx.cap(1));
267       return QBrush();
268     }
269     return QBrush(_palette.brush(_paletteColorRoles.value(rx.cap(1))));
270
271   } else if(str.startsWith("qlineargradient")) {
272     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
273     QRegExp rx(QString("qlineargradient\\s*\\(\\s*x1:%1,\\s*y1:%1,\\s*x2:%1,\\s*y2:%1,(.+)\\)").arg(rxFloat));
274     if(!rx.exactMatch(str)) {
275       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
276       return QBrush();
277     }
278     qreal x1 = rx.cap(1).toDouble();
279     qreal y1 = rx.cap(2).toDouble();
280     qreal x2 = rx.cap(3).toDouble();
281     qreal y2 = rx.cap(4).toDouble();
282     QGradientStops stops = parseGradientStops(rx.cap(5).trimmed());
283     if(!stops.count()) {
284       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
285       return QBrush();
286     }
287     QLinearGradient gradient(x1, y1, x2, y2);
288     gradient.setStops(stops);
289     return QBrush(gradient);
290
291   } else if(str.startsWith("qconicalgradient")) {
292     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
293     QRegExp rx(QString("qconicalgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*angle:%1,(.+)\\)").arg(rxFloat));
294     if(!rx.exactMatch(str)) {
295       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
296       return QBrush();
297     }
298     qreal cx = rx.cap(1).toDouble();
299     qreal cy = rx.cap(2).toDouble();
300     qreal angle = rx.cap(3).toDouble();
301     QGradientStops stops = parseGradientStops(rx.cap(4).trimmed());
302     if(!stops.count()) {
303       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
304       return QBrush();
305     }
306     QConicalGradient gradient(cx, cy, angle);
307     gradient.setStops(stops);
308     return QBrush(gradient);
309
310   } else if(str.startsWith("qradialgradient")) {
311     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
312     QRegExp rx(QString("qradialgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*radius:%1,\\s*fx:%1,\\s*fy:%1,(.+)\\)").arg(rxFloat));
313     if(!rx.exactMatch(str)) {
314       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
315       return QBrush();
316     }
317     qreal cx = rx.cap(1).toDouble();
318     qreal cy = rx.cap(2).toDouble();
319     qreal radius = rx.cap(3).toDouble();
320     qreal fx = rx.cap(4).toDouble();
321     qreal fy = rx.cap(5).toDouble();
322     QGradientStops stops = parseGradientStops(rx.cap(6).trimmed());
323     if(!stops.count()) {
324       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
325       return QBrush();
326     }
327     QRadialGradient gradient(cx, cy, radius, fx, fy);
328     gradient.setStops(stops);
329     return QBrush(gradient);
330   }
331
332   return QBrush();
333 }
334
335 QColor QssParser::parseColorValue(const QString &str) {
336   if(str.startsWith("rgba")) {
337     ColorTuple tuple = parseColorTuple(str.mid(4));
338     if(tuple.count() == 4)
339       return QColor(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
340   } else if(str.startsWith("rgb")) {
341     ColorTuple tuple = parseColorTuple(str.mid(3));
342     if(tuple.count() == 3)
343       return QColor(tuple.at(0), tuple.at(1), tuple.at(2));
344   } else if(str.startsWith("hsva")) {
345     ColorTuple tuple = parseColorTuple(str.mid(4));
346     if(tuple.count() == 4) {
347       QColor c;
348       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
349       return c;
350     }
351   } else if(str.startsWith("hsv")) {
352     ColorTuple tuple = parseColorTuple(str.mid(3));
353     if(tuple.count() == 3) {
354       QColor c;
355       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2));
356       return c;
357     }
358   } else {
359     QRegExp rx("#?[0-9A-Fa-z]+");
360     if(rx.exactMatch(str))
361       return QColor(str);
362   }
363   return QColor();
364 }
365
366 // get a list of comma-separated int values or percentages (rel to 0-255)
367 QssParser::ColorTuple QssParser::parseColorTuple(const QString &str) {
368   ColorTuple result;
369   QRegExp rx("\\(((\\s*[0-9]{1,3}%?\\s*)(,\\s*[0-9]{1,3}%?\\s*)*)\\)");
370   if(!rx.exactMatch(str.trimmed())) {
371     return ColorTuple();
372   }
373   QStringList values = rx.cap(1).split(',');
374   foreach(QString v, values) {
375     qreal val;
376     bool perc = false;
377     bool ok;
378     v = v.trimmed();
379     if(v.endsWith('%')) {
380       perc = true;
381       v.chop(1);
382     }
383     val = (qreal)v.toUInt(&ok);
384     if(!ok)
385       return ColorTuple();
386     if(perc)
387       val = 255 * val/100;
388     result.append(val);
389   }
390   return result;
391 }
392
393 QGradientStops QssParser::parseGradientStops(const QString &str_) {
394   QString str = str_;
395   QGradientStops result;
396   static QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
397   QRegExp rx(QString("\\s*,?\\s*stop:\\s*(%1)\\s+([^:]+)(,\\s*stop:|$)").arg(rxFloat));
398   int idx;
399   while((idx = rx.indexIn(str)) == 0) {
400     qreal x = rx.cap(1).toDouble();
401     QColor c = parseColorValue(rx.cap(3));
402     if(!c.isValid())
403       return QGradientStops();
404     result << QGradientStop(x, c);
405     str.remove(0, rx.matchedLength() - rx.cap(4).length());
406   }
407   if(!str.trimmed().isEmpty())
408     return QGradientStops();
409
410   return result;
411 }