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