1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QApplication>
23 #include "qssparser.h"
25 QssParser::QssParser()
28 _palette = QApplication::palette();
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;
54 void QssParser::processStyleSheet(QString &ss) {
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[^{]*)\\{([^}]+)\\}");
62 while((pos = paletterx.indexIn(ss, pos)) >= 0) {
63 parsePaletteData(paletterx.cap(1).trimmed(), paletterx.cap(2).trimmed());
64 pos += paletterx.matchedLength();
67 // Now we can parse the rest of our custom blocks
68 QRegExp blockrx("((?:ChatLine|BufferList|NickList|TreeView)[^{]*)\\{([^}]+)\\}");
70 while((pos = blockrx.indexIn(ss, pos)) >= 0) {
71 //qDebug() << blockrx.cap(1) << blockrx.cap(2);
73 if(blockrx.cap(1).startsWith("ChatLine"))
74 parseChatLineData(blockrx.cap(1).trimmed(), blockrx.cap(2).trimmed());
76 // TODO: add moar here
78 pos += blockrx.matchedLength();
83 void QssParser::parseChatLineData(const QString &decl, const QString &contents) {
84 quint64 fmtType = parseFormatType(decl);
85 if(fmtType == UiStyle::Invalid)
88 QTextCharFormat format;
90 foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
91 int idx = line.indexOf(':');
93 qWarning() << Q_FUNC_INFO << tr("Invalid property declaration: %1").arg(line.trimmed());
96 QString property = line.left(idx).trimmed();
97 QString value = line.mid(idx + 1).simplified();
99 if(property == "background" || property == "background-color")
100 format.setBackground(parseBrush(value));
101 else if(property == "foreground" || property == "color")
102 format.setForeground(parseBrush(value));
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);
117 qWarning() << Q_FUNC_INFO << tr("Invalid font property: %1").arg(line);
123 qWarning() << Q_FUNC_INFO << tr("Unknown ChatLine property: %1").arg(property);
127 _formats[fmtType] = format;
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;
137 QString subElement = rx.cap(1);
138 QString msgType = rx.cap(2);
139 QString conditions = rx.cap(3);
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;
158 qWarning() << Q_FUNC_INFO << tr("Invalid subelement name in %1").arg(decl);
159 return UiStyle::Invalid;
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;
194 qWarning() << Q_FUNC_INFO << tr("Invalid message type in %1").arg(decl);
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;
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;
213 qWarning() << Q_FUNC_INFO << tr("Invalid message label: %1").arg(condValue);
214 return UiStyle::Invalid;
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
222 quint64 val = condValue.toUInt(&ok, 16);
224 qWarning() << Q_FUNC_INFO << tr("Invalid senderhash specification: %1").arg(condValue);
225 return UiStyle::Invalid;
228 qWarning() << Q_FUNC_INFO << tr("Senderhash can be at most \"0x0f\"!");
229 return UiStyle::Invalid;
231 fmtType |= val << 48;
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;
243 qWarning() << Q_FUNC_INFO << tr("Invalid format name: %1").arg(condValue);
244 return UiStyle::Invalid;
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;
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);
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);
279 // Now let's go through the roles
280 foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
281 int idx = line.indexOf(':');
283 qWarning() << Q_FUNC_INFO << tr("Invalid palette role assignment: %1").arg(line.trimmed());
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);
292 QBrush brush = parseBrush(brushstr);
293 if(colorGroups.count()) {
294 foreach(QPalette::ColorGroup group, colorGroups)
295 _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
297 _palette.setBrush(_paletteColorRoles.value(rolestr), brush);
301 QBrush QssParser::parseBrush(const QString &str, bool *ok) {
304 QColor c = parseColor(str);
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);
317 if(!_paletteColorRoles.contains(rx.cap(1))) {
318 qWarning() << Q_FUNC_INFO << tr("Unknown palette color role: %1").arg(rx.cap(1));
321 return QBrush(_palette.brush(_paletteColorRoles.value(rx.cap(1))));
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);
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());
336 qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
339 QLinearGradient gradient(x1, y1, x2, y2);
340 gradient.setStops(stops);
343 return QBrush(gradient);
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);
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());
357 qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
360 QConicalGradient gradient(cx, cy, angle);
361 gradient.setStops(stops);
364 return QBrush(gradient);
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);
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());
380 qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
383 QRadialGradient gradient(cx, cy, radius, fx, fy);
384 gradient.setStops(stops);
387 return QBrush(gradient);
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) {
406 c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
409 } else if(str.startsWith("hsv")) {
410 ColorTuple tuple = parseColorTuple(str.mid(3));
411 if(tuple.count() == 3) {
413 c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2));
417 QRegExp rx("#?[0-9A-Fa-z]+");
418 if(rx.exactMatch(str))
424 // get a list of comma-separated int values or percentages (rel to 0-255)
425 QssParser::ColorTuple QssParser::parseColorTuple(const QString &str) {
427 QRegExp rx("\\(((\\s*[0-9]{1,3}%?\\s*)(,\\s*[0-9]{1,3}%?\\s*)*)\\)");
428 if(!rx.exactMatch(str.trimmed())) {
431 QStringList values = rx.cap(1).split(',');
432 foreach(QString v, values) {
437 if(v.endsWith('%')) {
441 val = (qreal)v.toUInt(&ok);
451 QGradientStops QssParser::parseGradientStops(const QString &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));
457 while((idx = rx.indexIn(str)) == 0) {
458 qreal x = rx.cap(1).toDouble();
459 QColor c = parseColor(rx.cap(3));
461 return QGradientStops();
462 result << QGradientStop(x, c);
463 str.remove(0, rx.matchedLength() - rx.cap(4).length());
465 if(!str.trimmed().isEmpty())
466 return QGradientStops();
471 /******** Font Properties ********/
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);
479 format->setFontItalic(false);
480 format->setFontWeight(QFont::Normal);
481 QStringList proplist = rx.cap(1).split(' ', QString::SkipEmptyParts);
482 foreach(QString prop, proplist) {
484 format->setFontItalic(true);
485 //else if(prop == "oblique")
486 // format->setStyle(QFont::StyleOblique);
487 else if(prop == "bold")
488 format->setFontWeight(QFont::Bold);
490 int w = prop.toInt();
491 format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
495 if(rx.cap(3) == "px")
496 format->setProperty(QTextFormat::FontPixelSize, rx.cap(2).toInt());
498 format->setFontPointSize(rx.cap(2).toInt());
500 format->setFontFamily(rx.cap(4));
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);
511 qWarning() << Q_FUNC_INFO << tr("Invalid font style specification: %1").arg(value);
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);
522 int w = value.toInt(&ok);
524 qWarning() << Q_FUNC_INFO << tr("Invalid font weight specification: %1").arg(value);
527 format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
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);
537 if(rx.cap(2) == "px")
538 format->setProperty(QTextFormat::FontPixelSize, rx.cap(1).toInt());
540 format->setFontPointSize(rx.cap(1).toInt());
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);
548 format->setFontFamily(family);