Make URLs stylable and fix on-hover underline
[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 if(subElement == "url")
190       fmtType |= UiStyle::Url;
191     else {
192       qWarning() << Q_FUNC_INFO << tr("Invalid subelement name in %1").arg(decl);
193       return UiStyle::Invalid;
194     }
195   }
196
197   // Now, figure out the message type
198   if(!msgType.isEmpty()) {
199     if(msgType == "plain")
200       fmtType |= UiStyle::PlainMsg;
201     else if(msgType == "notice")
202       fmtType |= UiStyle::NoticeMsg;
203     else if(msgType == "action")
204       fmtType |= UiStyle::ActionMsg;
205     else if(msgType == "nick")
206       fmtType |= UiStyle::NickMsg;
207     else if(msgType == "mode")
208       fmtType |= UiStyle::ModeMsg;
209     else if(msgType == "join")
210       fmtType |= UiStyle::JoinMsg;
211     else if(msgType == "part")
212       fmtType |= UiStyle::PartMsg;
213     else if(msgType == "quit")
214       fmtType |= UiStyle::QuitMsg;
215     else if(msgType == "kick")
216       fmtType |= UiStyle::KickMsg;
217     else if(msgType == "kill")
218       fmtType |= UiStyle::KillMsg;
219     else if(msgType == "server")
220       fmtType |= UiStyle::ServerMsg;
221     else if(msgType == "info")
222       fmtType |= UiStyle::InfoMsg;
223     else if(msgType == "error")
224       fmtType |= UiStyle::ErrorMsg;
225     else if(msgType == "daychange")
226       fmtType |= UiStyle::DayChangeMsg;
227     else if(msgType == "topic")
228       fmtType |= UiStyle::TopicMsg;
229     else {
230       qWarning() << Q_FUNC_INFO << tr("Invalid message type in %1").arg(decl);
231     }
232   }
233
234   // Next up: conditional (formats, labels, nickhash)
235   QRegExp condRx("\\s*([\\w\\-]+)\\s*=\\s*\"(\\w+)\"\\s*");
236   if(!conditions.isEmpty()) {
237     foreach(const QString &cond, conditions.split(',', QString::SkipEmptyParts)) {
238       if(!condRx.exactMatch(cond)) {
239         qWarning() << Q_FUNC_INFO << tr("Invalid condition %1").arg(cond);
240         return UiStyle::Invalid;
241       }
242       QString condName = condRx.cap(1);
243       QString condValue = condRx.cap(2);
244       if(condName == "label") {
245         quint64 labeltype = 0;
246         if(condValue == "highlight")
247           labeltype = UiStyle::Highlight;
248         else if(condValue == "selected")
249           labeltype = UiStyle::Selected;
250         else {
251           qWarning() << Q_FUNC_INFO << tr("Invalid message label: %1").arg(condValue);
252           return UiStyle::Invalid;
253         }
254         fmtType |= (labeltype << 32);
255       } else if(condName == "sender") {
256         if(condValue == "self")
257           fmtType |= (quint64)UiStyle::OwnMsg << 32; // sender="self" is actually treated as a label
258           else {
259             bool ok = true;
260             quint64 val = condValue.toUInt(&ok, 16);
261             if(!ok) {
262               qWarning() << Q_FUNC_INFO << tr("Invalid senderhash specification: %1").arg(condValue);
263               return UiStyle::Invalid;
264             }
265             if(val >= 16) {
266               qWarning() << Q_FUNC_INFO << tr("Senderhash can be at most \"0x0f\"!");
267               return UiStyle::Invalid;
268             }
269             fmtType |= ++val << 48;
270           }
271       } else if(condName == "format") {
272         if(condValue == "bold")
273           fmtType |= UiStyle::Bold;
274         else if(condValue == "italic")
275           fmtType |= UiStyle::Italic;
276         else if(condValue == "underline")
277           fmtType |= UiStyle::Underline;
278         else if(condValue == "reverse")
279           fmtType |= UiStyle::Reverse;
280         else {
281           qWarning() << Q_FUNC_INFO << tr("Invalid format name: %1").arg(condValue);
282           return UiStyle::Invalid;
283         }
284       } else if(condName == "fg-color" || condName == "bg-color") {
285         bool ok;
286         quint8 col = condValue.toUInt(&ok, 16);
287         if(!ok || col > 0x0f) {
288           qWarning() << Q_FUNC_INFO << tr("Illegal IRC color specification (must be between 00 and 0f): %1").arg(condValue);
289           return UiStyle::Invalid;
290         }
291         if(condName == "fg-color")
292           fmtType |= 0x00400000 | (col << 24);
293         else
294           fmtType |= 0x00800000 | (col << 28);
295       } else {
296         qWarning() << Q_FUNC_INFO << tr("Unhandled condition: %1").arg(condName);
297         return UiStyle::Invalid;
298       }
299     }
300   }
301
302   return fmtType;
303 }
304
305 // FIXME: Code duplication
306 quint32 QssParser::parseItemFormatType(const QString &decl) {
307   QRegExp rx("(Chat|Nick)ListItem(?:\\[([=-,\\\"\\w\\s]+)\\])?");
308   // $1: item type; $2: properties
309   if(!rx.exactMatch(decl)) {
310     qWarning() << Q_FUNC_INFO << tr("Invalid block declaration: %1").arg(decl);
311     return UiStyle::Invalid;
312   }
313   QString mainItemType = rx.cap(1);
314   QString properties = rx.cap(2);
315
316   quint32 fmtType = 0;
317
318   // Next up: properties
319   QString type, state;
320   if(!properties.isEmpty()) {
321     QHash<QString, QString> props;
322     QRegExp propRx("\\s*([\\w\\-]+)\\s*=\\s*\"([\\w\\-]+)\"\\s*");
323     foreach(const QString &prop, properties.split(',', QString::SkipEmptyParts)) {
324       if(!propRx.exactMatch(prop)) {
325         qWarning() << Q_FUNC_INFO << tr("Invalid proplist %1").arg(prop);
326         return UiStyle::Invalid;
327       }
328       props[propRx.cap(1)] = propRx.cap(2);
329     }
330     type = props.value("type");
331     state = props.value("state");
332   }
333
334   if(mainItemType == "Chat") {
335     fmtType |= UiStyle::BufferViewItem;
336     if(!type.isEmpty()) {
337       if(type == "network")
338         fmtType |= UiStyle::NetworkItem;
339       else if(type == "channel")
340         fmtType |= UiStyle::ChannelBufferItem;
341       else if(type == "query")
342         fmtType |= UiStyle::QueryBufferItem;
343       else {
344         qWarning() << Q_FUNC_INFO << tr("Invalid chatlist item type %1").arg(type);
345         return UiStyle::Invalid;
346       }
347     }
348     if(!state.isEmpty()) {
349       if(state == "inactive")
350         fmtType |= UiStyle::InactiveBuffer;
351       else if(state == "channel-event")
352         fmtType |= UiStyle::ActiveBuffer;
353       else if(state == "unread-message")
354         fmtType |= UiStyle::UnreadBuffer;
355       else if(state == "highlighted")
356         fmtType |= UiStyle::HighlightedBuffer;
357       else if(state == "away")
358         fmtType |= UiStyle::UserAway;
359       else {
360         qWarning() << Q_FUNC_INFO << tr("Invalid chatlist state %1").arg(state);
361         return UiStyle::Invalid;
362       }
363     }
364   } else { // NickList
365     fmtType |= UiStyle::NickViewItem;
366     if(!type.isEmpty()) {
367       if(type == "user") {
368         fmtType |= UiStyle::IrcUserItem;
369         if(state == "away")
370           fmtType |= UiStyle::UserAway;
371       } else if(type == "category")
372         fmtType |= UiStyle::UserCategoryItem;
373     }
374   }
375   return fmtType;
376 }
377
378 /******** Parse a whole format attribute block ********/
379
380 QTextCharFormat QssParser::parseFormat(const QString &qss) {
381   QTextCharFormat format;
382
383   foreach(QString line, qss.split(';', QString::SkipEmptyParts)) {
384     int idx = line.indexOf(':');
385     if(idx <= 0) {
386       qWarning() << Q_FUNC_INFO << tr("Invalid property declaration: %1").arg(line.trimmed());
387       continue;
388     }
389     QString property = line.left(idx).trimmed();
390     QString value = line.mid(idx + 1).simplified();
391
392     if(property == "background" || property == "background-color")
393       format.setBackground(parseBrush(value));
394     else if(property == "foreground" || property == "color")
395       format.setForeground(parseBrush(value));
396
397     // font-related properties
398     else if(property.startsWith("font")) {
399       if(property == "font")
400         parseFont(value, &format);
401       else if(property == "font-style")
402         parseFontStyle(value, &format);
403       else if(property == "font-weight")
404         parseFontWeight(value, &format);
405       else if(property == "font-size")
406         parseFontSize(value, &format);
407       else if(property == "font-family")
408         parseFontFamily(value, &format);
409       else {
410         qWarning() << Q_FUNC_INFO << tr("Invalid font property: %1").arg(line);
411         continue;
412       }
413     }
414
415     else {
416       qWarning() << Q_FUNC_INFO << tr("Unknown ChatLine property: %1").arg(property);
417     }
418   }
419
420   return format;
421 }
422
423 /******** Brush ********/
424
425 QBrush QssParser::parseBrush(const QString &str, bool *ok) {
426   if(ok)
427     *ok = false;
428   QColor c = parseColor(str);
429   if(c.isValid()) {
430     if(ok)
431       *ok = true;
432     return QBrush(c);
433   }
434
435   if(str.startsWith("palette")) { // Palette color role
436     QRegExp rx("palette\\s*\\(\\s*([a-z-]+)\\s*\\)");
437     if(!rx.exactMatch(str)) {
438       qWarning() << Q_FUNC_INFO << tr("Invalid palette color role specification: %1").arg(str);
439       return QBrush();
440     }
441     if(_paletteColorRoles.contains(rx.cap(1)))
442       return QBrush(_palette.brush(_paletteColorRoles.value(rx.cap(1))));
443     if(_uiStyleColorRoles.contains(rx.cap(1)))
444       return QBrush(_uiStylePalette.at(_uiStyleColorRoles.value(rx.cap(1))));
445     qWarning() << Q_FUNC_INFO << tr("Unknown palette color role: %1").arg(rx.cap(1));
446     return QBrush();
447
448   } else if(str.startsWith("qlineargradient")) {
449     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
450     QRegExp rx(QString("qlineargradient\\s*\\(\\s*x1:%1,\\s*y1:%1,\\s*x2:%1,\\s*y2:%1,(.+)\\)").arg(rxFloat));
451     if(!rx.exactMatch(str)) {
452       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
453       return QBrush();
454     }
455     qreal x1 = rx.cap(1).toDouble();
456     qreal y1 = rx.cap(2).toDouble();
457     qreal x2 = rx.cap(3).toDouble();
458     qreal y2 = rx.cap(4).toDouble();
459     QGradientStops stops = parseGradientStops(rx.cap(5).trimmed());
460     if(!stops.count()) {
461       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
462       return QBrush();
463     }
464     QLinearGradient gradient(x1, y1, x2, y2);
465     gradient.setStops(stops);
466     if(ok)
467       *ok = true;
468     return QBrush(gradient);
469
470   } else if(str.startsWith("qconicalgradient")) {
471     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
472     QRegExp rx(QString("qconicalgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*angle:%1,(.+)\\)").arg(rxFloat));
473     if(!rx.exactMatch(str)) {
474       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
475       return QBrush();
476     }
477     qreal cx = rx.cap(1).toDouble();
478     qreal cy = rx.cap(2).toDouble();
479     qreal angle = rx.cap(3).toDouble();
480     QGradientStops stops = parseGradientStops(rx.cap(4).trimmed());
481     if(!stops.count()) {
482       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
483       return QBrush();
484     }
485     QConicalGradient gradient(cx, cy, angle);
486     gradient.setStops(stops);
487     if(ok)
488       *ok = true;
489     return QBrush(gradient);
490
491   } else if(str.startsWith("qradialgradient")) {
492     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
493     QRegExp rx(QString("qradialgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*radius:%1,\\s*fx:%1,\\s*fy:%1,(.+)\\)").arg(rxFloat));
494     if(!rx.exactMatch(str)) {
495       qWarning() << Q_FUNC_INFO << tr("Invalid gradient declaration: %1").arg(str);
496       return QBrush();
497     }
498     qreal cx = rx.cap(1).toDouble();
499     qreal cy = rx.cap(2).toDouble();
500     qreal radius = rx.cap(3).toDouble();
501     qreal fx = rx.cap(4).toDouble();
502     qreal fy = rx.cap(5).toDouble();
503     QGradientStops stops = parseGradientStops(rx.cap(6).trimmed());
504     if(!stops.count()) {
505       qWarning() << Q_FUNC_INFO << tr("Invalid gradient stops list: %1").arg(str);
506       return QBrush();
507     }
508     QRadialGradient gradient(cx, cy, radius, fx, fy);
509     gradient.setStops(stops);
510     if(ok)
511       *ok = true;
512     return QBrush(gradient);
513   }
514
515   return QBrush();
516 }
517
518 QColor QssParser::parseColor(const QString &str) {
519   if(str.startsWith("rgba")) {
520     ColorTuple tuple = parseColorTuple(str.mid(4));
521     if(tuple.count() == 4)
522       return QColor(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
523   } else if(str.startsWith("rgb")) {
524     ColorTuple tuple = parseColorTuple(str.mid(3));
525     if(tuple.count() == 3)
526       return QColor(tuple.at(0), tuple.at(1), tuple.at(2));
527   } else if(str.startsWith("hsva")) {
528     ColorTuple tuple = parseColorTuple(str.mid(4));
529     if(tuple.count() == 4) {
530       QColor c;
531       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
532       return c;
533     }
534   } else if(str.startsWith("hsv")) {
535     ColorTuple tuple = parseColorTuple(str.mid(3));
536     if(tuple.count() == 3) {
537       QColor c;
538       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2));
539       return c;
540     }
541   } else {
542     QRegExp rx("#?[0-9A-Fa-z]+");
543     if(rx.exactMatch(str))
544       return QColor(str);
545   }
546   return QColor();
547 }
548
549 // get a list of comma-separated int values or percentages (rel to 0-255)
550 QssParser::ColorTuple QssParser::parseColorTuple(const QString &str) {
551   ColorTuple result;
552   QRegExp rx("\\(((\\s*[0-9]{1,3}%?\\s*)(,\\s*[0-9]{1,3}%?\\s*)*)\\)");
553   if(!rx.exactMatch(str.trimmed())) {
554     return ColorTuple();
555   }
556   QStringList values = rx.cap(1).split(',');
557   foreach(QString v, values) {
558     qreal val;
559     bool perc = false;
560     bool ok;
561     v = v.trimmed();
562     if(v.endsWith('%')) {
563       perc = true;
564       v.chop(1);
565     }
566     val = (qreal)v.toUInt(&ok);
567     if(!ok)
568       return ColorTuple();
569     if(perc)
570       val = 255 * val/100;
571     result.append(val);
572   }
573   return result;
574 }
575
576 QGradientStops QssParser::parseGradientStops(const QString &str_) {
577   QString str = str_;
578   QGradientStops result;
579   static QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
580   QRegExp rx(QString("\\s*,?\\s*stop:\\s*(%1)\\s+([^:]+)(,\\s*stop:|$)").arg(rxFloat));
581   int idx;
582   while((idx = rx.indexIn(str)) == 0) {
583     qreal x = rx.cap(1).toDouble();
584     QColor c = parseColor(rx.cap(3));
585     if(!c.isValid())
586       return QGradientStops();
587     result << QGradientStop(x, c);
588     str.remove(0, rx.matchedLength() - rx.cap(4).length());
589   }
590   if(!str.trimmed().isEmpty())
591     return QGradientStops();
592
593   return result;
594 }
595
596 /******** Font Properties ********/
597
598 void QssParser::parseFont(const QString& value, QTextCharFormat* format) {
599   QRegExp rx("((?:(?:normal|italic|oblique|underline|bold|100|200|300|400|500|600|700|800|900) ){0,2}) ?(\\d+)(pt|px)? \"(.*)\"");
600   if(!rx.exactMatch(value)) {
601     qWarning() << Q_FUNC_INFO << tr("Invalid font specification: %1").arg(value);
602     return;
603   }
604   format->setFontItalic(false);
605   format->setFontWeight(QFont::Normal);
606   QStringList proplist = rx.cap(1).split(' ', QString::SkipEmptyParts);
607   foreach(QString prop, proplist) {
608     if(prop == "italic")
609       format->setFontItalic(true);
610     else if(prop == "underline")
611       format->setFontUnderline(true);
612     //else if(prop == "oblique")
613     //  format->setStyle(QFont::StyleOblique);
614     else if(prop == "bold")
615       format->setFontWeight(QFont::Bold);
616     else { // number
617       int w = prop.toInt();
618       format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
619     }
620   }
621
622   if(rx.cap(3) == "px")
623     format->setProperty(QTextFormat::FontPixelSize, rx.cap(2).toInt());
624   else
625     format->setFontPointSize(rx.cap(2).toInt());
626
627   format->setFontFamily(rx.cap(4));
628 }
629
630 void QssParser::parseFontStyle(const QString& value, QTextCharFormat* format) {
631   if(value == "normal")
632     format->setFontItalic(false);
633   else if(value == "italic")
634     format->setFontItalic(true);
635   else if(value == "underline")
636     format->setFontUnderline(true);
637   //else if(value == "oblique")
638   //  format->setStyle(QFont::StyleOblique);
639   else {
640     qWarning() << Q_FUNC_INFO << tr("Invalid font style specification: %1").arg(value);
641   }
642 }
643
644 void QssParser::parseFontWeight(const QString& value, QTextCharFormat* format) {
645   if(value == "normal")
646     format->setFontWeight(QFont::Normal);
647   else if(value == "bold")
648     format->setFontWeight(QFont::Bold);
649   else {
650     bool ok;
651     int w = value.toInt(&ok);
652     if(!ok) {
653       qWarning() << Q_FUNC_INFO << tr("Invalid font weight specification: %1").arg(value);
654       return;
655     }
656     format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
657   }
658 }
659
660 void QssParser::parseFontSize(const QString& value, QTextCharFormat* format) {
661   QRegExp rx("\\(d+)(pt|px)");
662   if(!rx.exactMatch(value)) {
663     qWarning() << Q_FUNC_INFO << tr("Invalid font size specification: %1").arg(value);
664     return;
665   }
666   if(rx.cap(2) == "px")
667     format->setProperty(QTextFormat::FontPixelSize, rx.cap(1).toInt());
668   else
669     format->setFontPointSize(rx.cap(1).toInt());
670 }
671
672 void QssParser::parseFontFamily(const QString& value, QTextCharFormat* format) {
673   QString family = value;
674   if(family.startsWith('"') && family.endsWith('"')) {
675     family = family.mid(1, family.length() - 2);
676   }
677   format->setFontFamily(family);
678 }