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;
53 _uiStylePalette = QVector<QBrush>(UiStyle::NumRoles, QBrush());
55 _uiStyleColorRoles["marker-line"] = UiStyle::MarkerLine;
56 _uiStyleColorRoles["active-nick"] = UiStyle::ActiveNick;
57 _uiStyleColorRoles["inactive-nick"] = UiStyle::InactiveNick;
58 _uiStyleColorRoles["channel"] = UiStyle::Channel;
59 _uiStyleColorRoles["inactive-channel"] = UiStyle::InactiveChannel;
60 _uiStyleColorRoles["active-channel"] = UiStyle::ActiveChannel;
61 _uiStyleColorRoles["unread-channel"] = UiStyle::UnreadChannel;
62 _uiStyleColorRoles["highlighted-channel"] = UiStyle::HighlightedChannel;
63 _uiStyleColorRoles["query"] = UiStyle::Query;
64 _uiStyleColorRoles["inactive-query"] = UiStyle::InactiveQuery;
65 _uiStyleColorRoles["active-query"] = UiStyle::ActiveQuery;
66 _uiStyleColorRoles["unread-query"] = UiStyle::UnreadQuery;
67 _uiStyleColorRoles["highlighted-query"] = UiStyle::HighlightedQuery;
70 void QssParser::processStyleSheet(QString &ss) {
74 // Remove C-style comments /* */ or //
75 QRegExp commentRx("(//.*(\\n|$)|/\\*.*\\*/)");
76 commentRx.setMinimal(true);
79 // Palette definitions first, so we can apply roles later on
80 QRegExp paletterx("(Palette[^{]*)\\{([^}]+)\\}");
82 while((pos = paletterx.indexIn(ss, pos)) >= 0) {
83 parsePaletteData(paletterx.cap(1).trimmed(), paletterx.cap(2).trimmed());
84 ss.remove(pos, paletterx.matchedLength());
87 // Now we can parse the rest of our custom blocks
88 QRegExp blockrx("((?:ChatLine|BufferList|NickList|TreeView)[^{]*)\\{([^}]+)\\}");
90 while((pos = blockrx.indexIn(ss, pos)) >= 0) {
91 //qDebug() << blockrx.cap(1) << blockrx.cap(2);
93 if(blockrx.cap(1).startsWith("ChatLine"))
94 parseChatLineData(blockrx.cap(1).trimmed(), blockrx.cap(2).trimmed());
96 // TODO: add moar here
98 ss.remove(pos, blockrx.matchedLength());
102 void QssParser::parseChatLineData(const QString &decl, const QString &contents) {
103 quint64 fmtType = parseFormatType(decl);
104 if(fmtType == UiStyle::Invalid)
107 QTextCharFormat format;
109 foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
110 int idx = line.indexOf(':');
112 qWarning() << Q_FUNC_INFO << tr("Invalid property declaration: %1").arg(line.trimmed());
115 QString property = line.left(idx).trimmed();
116 QString value = line.mid(idx + 1).simplified();
118 if(property == "background" || property == "background-color")
119 format.setBackground(parseBrush(value));
120 else if(property == "foreground" || property == "color")
121 format.setForeground(parseBrush(value));
123 // font-related properties
124 else if(property.startsWith("font")) {
125 if(property == "font")
126 parseFont(value, &format);
127 else if(property == "font-style")
128 parseFontStyle(value, &format);
129 else if(property == "font-weight")
130 parseFontWeight(value, &format);
131 else if(property == "font-size")
132 parseFontSize(value, &format);
133 else if(property == "font-family")
134 parseFontFamily(value, &format);
136 qWarning() << Q_FUNC_INFO << tr("Invalid font property: %1").arg(line);
142 qWarning() << Q_FUNC_INFO << tr("Unknown ChatLine property: %1").arg(property);
146 _formats[fmtType].merge(format);
149 quint64 QssParser::parseFormatType(const QString &decl) {
150 QRegExp rx("ChatLine(?:::(\\w+))?(?:#(\\w+))?(?:\\[([=-,\\\"\\w\\s]+)\\])?\\s*");
151 // $1: subelement; $2: msgtype; $3: conditionals
152 if(!rx.exactMatch(decl)) {
153 qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
154 return UiStyle::Invalid;
156 QString subElement = rx.cap(1);
157 QString msgType = rx.cap(2);
158 QString conditions = rx.cap(3);
162 // First determine the subelement
163 if(!subElement.isEmpty()) {
164 if(subElement == "timestamp")
165 fmtType |= UiStyle::Timestamp;
166 else if(subElement == "sender")
167 fmtType |= UiStyle::Sender;
168 else if(subElement == "nick")
169 fmtType |= UiStyle::Nick;
170 else if(subElement == "contents")
171 fmtType |= UiStyle::Contents;
172 else if(subElement == "hostmask")
173 fmtType |= UiStyle::Hostmask;
174 else if(subElement == "modeflags")
175 fmtType |= UiStyle::ModeFlags;
177 qWarning() << Q_FUNC_INFO << tr("Invalid subelement name in %1").arg(decl);
178 return UiStyle::Invalid;
182 // Now, figure out the message type
183 if(!msgType.isEmpty()) {
184 if(msgType == "plain")
185 fmtType |= UiStyle::PlainMsg;
186 else if(msgType == "notice")
187 fmtType |= UiStyle::NoticeMsg;
188 else if(msgType == "action")
189 fmtType |= UiStyle::ActionMsg;
190 else if(msgType == "nick")
191 fmtType |= UiStyle::NickMsg;
192 else if(msgType == "mode")
193 fmtType |= UiStyle::ModeMsg;
194 else if(msgType == "join")
195 fmtType |= UiStyle::JoinMsg;
196 else if(msgType == "part")
197 fmtType |= UiStyle::PartMsg;
198 else if(msgType == "quit")
199 fmtType |= UiStyle::QuitMsg;
200 else if(msgType == "kick")
201 fmtType |= UiStyle::KickMsg;
202 else if(msgType == "kill")
203 fmtType |= UiStyle::KillMsg;
204 else if(msgType == "server")
205 fmtType |= UiStyle::ServerMsg;
206 else if(msgType == "info")
207 fmtType |= UiStyle::InfoMsg;
208 else if(msgType == "error")
209 fmtType |= UiStyle::ErrorMsg;
210 else if(msgType == "daychange")
211 fmtType |= UiStyle::DayChangeMsg;
213 qWarning() << Q_FUNC_INFO << tr("Invalid message type in %1").arg(decl);
217 // Next up: conditional (formats, labels, nickhash)
218 QRegExp condRx("\\s*([\\w\\-]+)\\s*=\\s*\"(\\w+)\"\\s*");
219 if(!conditions.isEmpty()) {
220 foreach(const QString &cond, conditions.split(',', QString::SkipEmptyParts)) {
221 if(!condRx.exactMatch(cond)) {
222 qWarning() << Q_FUNC_INFO << tr("Invalid condition %1").arg(cond);
223 return UiStyle::Invalid;
225 QString condName = condRx.cap(1);
226 QString condValue = condRx.cap(2);
227 if(condName == "label") {
228 quint64 labeltype = 0;
229 if(condValue == "highlight")
230 labeltype = UiStyle::Highlight;
231 else if(condValue == "selected")
232 labeltype = UiStyle::Selected;
234 qWarning() << Q_FUNC_INFO << tr("Invalid message label: %1").arg(condValue);
235 return UiStyle::Invalid;
237 fmtType |= (labeltype << 32);
238 } else if(condName == "sender") {
239 if(condValue == "self")
240 fmtType |= (quint64)UiStyle::OwnMsg << 32; // sender="self" is actually treated as a label
243 quint64 val = condValue.toUInt(&ok, 16);
245 qWarning() << Q_FUNC_INFO << tr("Invalid senderhash specification: %1").arg(condValue);
246 return UiStyle::Invalid;
249 qWarning() << Q_FUNC_INFO << tr("Senderhash can be at most \"0x0f\"!");
250 return UiStyle::Invalid;
252 fmtType |= val << 48;
254 } else if(condName == "format") {
255 if(condValue == "bold")
256 fmtType |= UiStyle::Bold;
257 else if(condValue == "italic")
258 fmtType |= UiStyle::Italic;
259 else if(condValue == "underline")
260 fmtType |= UiStyle::Underline;
261 else if(condValue == "reverse")
262 fmtType |= UiStyle::Reverse;
264 qWarning() << Q_FUNC_INFO << tr("Invalid format name: %1").arg(condValue);
265 return UiStyle::Invalid;
267 } else if(condName == "fg-color" || condName == "bg-color") {
269 quint8 col = condValue.toUInt(&ok, 16);
270 if(!ok || col > 0x0f) {
271 qWarning() << Q_FUNC_INFO << tr("Illegal IRC color specification (must be between 00 and 0f): %1").arg(condValue);
272 return UiStyle::Invalid;
274 if(condName == "fg-color")
275 fmtType |= 0x00400000 | (col << 24);
277 fmtType |= 0x00800000 | (col << 28);
279 qWarning() << Q_FUNC_INFO << tr("Unhandled condition: %1").arg(condName);
280 return UiStyle::Invalid;
288 // Palette { ... } specifies the application palette
289 // ColorGroups can be specified like pseudo states, chaining is OR (contrary to normal CSS handling):
290 // Palette:inactive:disabled { ... } applies to both the Inactive and the Disabled state
291 void QssParser::parsePaletteData(const QString &decl, const QString &contents) {
292 QList<QPalette::ColorGroup> colorGroups;
294 // Check if we want to apply this palette definition for particular ColorGroups
295 QRegExp rx("Palette((:(normal|active|inactive|disabled))*)");
296 if(!rx.exactMatch(decl)) {
297 qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
300 if(!rx.cap(1).isEmpty()) {
301 QStringList groups = rx.cap(1).split(':', QString::SkipEmptyParts);
302 foreach(QString g, groups) {
303 if((g == "normal" || g == "active") && !colorGroups.contains(QPalette::Active))
304 colorGroups.append(QPalette::Active);
305 else if(g == "inactive" && !colorGroups.contains(QPalette::Inactive))
306 colorGroups.append(QPalette::Inactive);
307 else if(g == "disabled" && !colorGroups.contains(QPalette::Disabled))
308 colorGroups.append(QPalette::Disabled);
312 // Now let's go through the roles
313 foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
314 int idx = line.indexOf(':');
316 qWarning() << Q_FUNC_INFO << tr("Invalid palette role assignment: %1").arg(line.trimmed());
319 QString rolestr = line.left(idx).trimmed();
320 QString brushstr = line.mid(idx + 1).trimmed();
322 if(_paletteColorRoles.contains(rolestr)) {
323 QBrush brush = parseBrush(brushstr);
324 if(colorGroups.count()) {
325 foreach(QPalette::ColorGroup group, colorGroups)
326 _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
328 _palette.setBrush(_paletteColorRoles.value(rolestr), brush);
329 } else if(_uiStyleColorRoles.contains(rolestr)) {
330 _uiStylePalette[_uiStyleColorRoles.value(rolestr)] = parseBrush(brushstr);
332 qWarning() << Q_FUNC_INFO << tr("Unknown palette role name: %1").arg(rolestr);
336 QBrush QssParser::parseBrush(const QString &str, bool *ok) {
339 QColor c = parseColor(str);
346 if(str.startsWith("palette")) { // Palette color role
347 QRegExp rx("palette\\s*\\(\\s*([a-z-]+)\\s*\\)");
348 if(!rx.exactMatch(str)) {
349 qWarning() << Q_FUNC_INFO << tr("Invalid palette color role specification: %1").arg(str);
352 if(_paletteColorRoles.contains(rx.cap(1)))
353 return QBrush(_palette.brush(_paletteColorRoles.value(rx.cap(1))));
354 if(_uiStyleColorRoles.contains(rx.cap(1)))
355 return QBrush(_uiStylePalette.at(_uiStyleColorRoles.value(rx.cap(1))));
356 qWarning() << Q_FUNC_INFO << tr("Unknown palette color role: %1").arg(rx.cap(1));
359 } else if(str.startsWith("qlineargradient")) {
360 static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
361 QRegExp rx(QString("qlineargradient\\s*\\(\\s*x1:%1,\\s*y1:%1,\\s*x2:%1,\\s*y2:%1,(.+)\\)").arg(rxFloat));
362 if(!rx.exactMatch(str)) {
363 qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
366 qreal x1 = rx.cap(1).toDouble();
367 qreal y1 = rx.cap(2).toDouble();
368 qreal x2 = rx.cap(3).toDouble();
369 qreal y2 = rx.cap(4).toDouble();
370 QGradientStops stops = parseGradientStops(rx.cap(5).trimmed());
372 qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
375 QLinearGradient gradient(x1, y1, x2, y2);
376 gradient.setStops(stops);
379 return QBrush(gradient);
381 } else if(str.startsWith("qconicalgradient")) {
382 static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
383 QRegExp rx(QString("qconicalgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*angle:%1,(.+)\\)").arg(rxFloat));
384 if(!rx.exactMatch(str)) {
385 qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
388 qreal cx = rx.cap(1).toDouble();
389 qreal cy = rx.cap(2).toDouble();
390 qreal angle = rx.cap(3).toDouble();
391 QGradientStops stops = parseGradientStops(rx.cap(4).trimmed());
393 qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
396 QConicalGradient gradient(cx, cy, angle);
397 gradient.setStops(stops);
400 return QBrush(gradient);
402 } else if(str.startsWith("qradialgradient")) {
403 static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
404 QRegExp rx(QString("qradialgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*radius:%1,\\s*fx:%1,\\s*fy:%1,(.+)\\)").arg(rxFloat));
405 if(!rx.exactMatch(str)) {
406 qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
409 qreal cx = rx.cap(1).toDouble();
410 qreal cy = rx.cap(2).toDouble();
411 qreal radius = rx.cap(3).toDouble();
412 qreal fx = rx.cap(4).toDouble();
413 qreal fy = rx.cap(5).toDouble();
414 QGradientStops stops = parseGradientStops(rx.cap(6).trimmed());
416 qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
419 QRadialGradient gradient(cx, cy, radius, fx, fy);
420 gradient.setStops(stops);
423 return QBrush(gradient);
429 QColor QssParser::parseColor(const QString &str) {
430 if(str.startsWith("rgba")) {
431 ColorTuple tuple = parseColorTuple(str.mid(4));
432 if(tuple.count() == 4)
433 return QColor(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
434 } else if(str.startsWith("rgb")) {
435 ColorTuple tuple = parseColorTuple(str.mid(3));
436 if(tuple.count() == 3)
437 return QColor(tuple.at(0), tuple.at(1), tuple.at(2));
438 } else if(str.startsWith("hsva")) {
439 ColorTuple tuple = parseColorTuple(str.mid(4));
440 if(tuple.count() == 4) {
442 c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
445 } else if(str.startsWith("hsv")) {
446 ColorTuple tuple = parseColorTuple(str.mid(3));
447 if(tuple.count() == 3) {
449 c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2));
453 QRegExp rx("#?[0-9A-Fa-z]+");
454 if(rx.exactMatch(str))
460 // get a list of comma-separated int values or percentages (rel to 0-255)
461 QssParser::ColorTuple QssParser::parseColorTuple(const QString &str) {
463 QRegExp rx("\\(((\\s*[0-9]{1,3}%?\\s*)(,\\s*[0-9]{1,3}%?\\s*)*)\\)");
464 if(!rx.exactMatch(str.trimmed())) {
467 QStringList values = rx.cap(1).split(',');
468 foreach(QString v, values) {
473 if(v.endsWith('%')) {
477 val = (qreal)v.toUInt(&ok);
487 QGradientStops QssParser::parseGradientStops(const QString &str_) {
489 QGradientStops result;
490 static QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
491 QRegExp rx(QString("\\s*,?\\s*stop:\\s*(%1)\\s+([^:]+)(,\\s*stop:|$)").arg(rxFloat));
493 while((idx = rx.indexIn(str)) == 0) {
494 qreal x = rx.cap(1).toDouble();
495 QColor c = parseColor(rx.cap(3));
497 return QGradientStops();
498 result << QGradientStop(x, c);
499 str.remove(0, rx.matchedLength() - rx.cap(4).length());
501 if(!str.trimmed().isEmpty())
502 return QGradientStops();
507 /******** Font Properties ********/
509 void QssParser::parseFont(const QString& value, QTextCharFormat* format) {
510 QRegExp rx("((?:(?:normal|italic|oblique|underline|bold|100|200|300|400|500|600|700|800|900) ){0,2}) ?(\\d+)(pt|px)? \"(.*)\"");
511 if(!rx.exactMatch(value)) {
512 qWarning() << Q_FUNC_INFO << tr("Invalid font specification: %1").arg(value);
515 format->setFontItalic(false);
516 format->setFontWeight(QFont::Normal);
517 QStringList proplist = rx.cap(1).split(' ', QString::SkipEmptyParts);
518 foreach(QString prop, proplist) {
520 format->setFontItalic(true);
521 else if(prop == "underline")
522 format->setFontUnderline(true);
523 //else if(prop == "oblique")
524 // format->setStyle(QFont::StyleOblique);
525 else if(prop == "bold")
526 format->setFontWeight(QFont::Bold);
528 int w = prop.toInt();
529 format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
533 if(rx.cap(3) == "px")
534 format->setProperty(QTextFormat::FontPixelSize, rx.cap(2).toInt());
536 format->setFontPointSize(rx.cap(2).toInt());
538 format->setFontFamily(rx.cap(4));
541 void QssParser::parseFontStyle(const QString& value, QTextCharFormat* format) {
542 if(value == "normal")
543 format->setFontItalic(false);
544 else if(value == "italic")
545 format->setFontItalic(true);
546 else if(value == "underline")
547 format->setFontUnderline(true);
548 //else if(value == "oblique")
549 // format->setStyle(QFont::StyleOblique);
551 qWarning() << Q_FUNC_INFO << tr("Invalid font style specification: %1").arg(value);
555 void QssParser::parseFontWeight(const QString& value, QTextCharFormat* format) {
556 if(value == "normal")
557 format->setFontWeight(QFont::Normal);
558 else if(value == "bold")
559 format->setFontWeight(QFont::Bold);
562 int w = value.toInt(&ok);
564 qWarning() << Q_FUNC_INFO << tr("Invalid font weight specification: %1").arg(value);
567 format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
571 void QssParser::parseFontSize(const QString& value, QTextCharFormat* format) {
572 QRegExp rx("\\(d+)(pt|px)");
573 if(!rx.exactMatch(value)) {
574 qWarning() << Q_FUNC_INFO << tr("Invalid font size specification: %1").arg(value);
577 if(rx.cap(2) == "px")
578 format->setProperty(QTextFormat::FontPixelSize, rx.cap(1).toInt());
580 format->setFontPointSize(rx.cap(1).toInt());
583 void QssParser::parseFontFamily(const QString& value, QTextCharFormat* format) {
584 QString family = value;
585 if(family.startsWith('"') && family.endsWith('"')) {
586 family = family.mid(1, family.length() - 2);
588 format->setFontFamily(family);