1fc19dbdf5b959af3f310f04c41cd5ef4bfc0a0d
[quassel.git] / src / uisupport / uistyle.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 #include <QApplication>
21
22 #include "quassel.h"
23 #include "uistyle.h"
24 #include "uisettings.h"
25 #include "util.h"
26
27 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
28   // register FormatList if that hasn't happened yet
29   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
30   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
31     qRegisterMetaType<FormatList>("UiStyle::FormatList");
32     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
33     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
34   }
35
36   _defaultFont = QFont("Monospace", QApplication::font().pointSize());
37
38   // Default format
39   _defaultPlainFormat.setForeground(QBrush("#000000"));
40   _defaultPlainFormat.setFont(_defaultFont);
41   _defaultPlainFormat.font().setFixedPitch(true);
42   _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
43   setFormat(None, _defaultPlainFormat, Settings::Default);
44
45   // Load saved custom formats
46   UiStyleSettings s(_settingsKey);
47   foreach(FormatType type, s.availableFormats()) {
48     _customFormats[type] = s.customFormat(type);
49   }
50
51   // Check for the sender auto coloring option
52   _senderAutoColor = s.value("Colors/SenderAutoColor", false).toBool();
53
54   // Now initialize the mapping between FormatCodes and FormatTypes...
55   _formatCodes["%O"] = None;
56   _formatCodes["%B"] = Bold;
57   _formatCodes["%S"] = Italic;
58   _formatCodes["%U"] = Underline;
59   _formatCodes["%R"] = Reverse;
60
61   _formatCodes["%D0"] = PlainMsg;
62   _formatCodes["%Dn"] = NoticeMsg;
63   _formatCodes["%Ds"] = ServerMsg;
64   _formatCodes["%De"] = ErrorMsg;
65   _formatCodes["%Dj"] = JoinMsg;
66   _formatCodes["%Dp"] = PartMsg;
67   _formatCodes["%Dq"] = QuitMsg;
68   _formatCodes["%Dk"] = KickMsg;
69   _formatCodes["%Dr"] = RenameMsg;
70   _formatCodes["%Dm"] = ModeMsg;
71   _formatCodes["%Da"] = ActionMsg;
72
73   _formatCodes["%DT"] = Timestamp;
74   _formatCodes["%DS"] = Sender;
75   _formatCodes["%DN"] = Nick;
76   _formatCodes["%DH"] = Hostmask;
77   _formatCodes["%DC"] = ChannelName;
78   _formatCodes["%DM"] = ModeFlags;
79   _formatCodes["%DU"] = Url;
80
81   // Initialize color codes according to mIRC "standard"
82   QStringList colors;
83   //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
84   //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
85   colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
86   colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
87
88   // Set color formats
89   for(int i = 0; i < 16; i++) {
90     QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
91     _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
92     _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
93     QTextCharFormat fgf, bgf;
94     fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
95     bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
96   }
97
98   // Set a few more standard formats
99   QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
100   setFormat(Bold, bold, Settings::Default);
101
102   QTextCharFormat italic; italic.setFontItalic(true);
103   setFormat(Italic, italic, Settings::Default);
104
105   QTextCharFormat underline; underline.setFontUnderline(true);
106   setFormat(Underline, underline, Settings::Default);
107
108   loadStyleSheet();
109   // All other formats should be defined in derived classes.
110 }
111
112 UiStyle::~ UiStyle() {
113   qDeleteAll(_cachedFontMetrics);
114 }
115
116 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
117   if(mode == Settings::Default) {
118     _defaultFormats[ftype] = fmt;
119   } else {
120     UiStyleSettings s(_settingsKey);
121     if(fmt != _defaultFormats[ftype]) {
122       _customFormats[ftype] = fmt;
123       s.setCustomFormat(ftype, fmt);
124     } else {
125       _customFormats.remove(ftype);
126       s.removeCustomFormat(ftype);
127     }
128   }
129   // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
130   _cachedFormats.clear();
131   _cachedFontMetrics.clear();
132 }
133
134 void UiStyle::setSenderAutoColor( bool state ) {
135   _senderAutoColor = state;
136   UiStyleSettings s(_settingsKey);
137   s.setValue("Colors/SenderAutoColor", QVariant(state));
138 }
139
140 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
141   // Check for enabled sender auto coloring
142   if ( (ftype & 0x00000fff) == Sender && !_senderAutoColor ) {
143     // Just use the default sender style if auto coloring is disabled FIXME
144     ftype = Sender;
145   }
146
147   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
148   else return _defaultFormats.value(ftype, QTextCharFormat());
149 }
150
151 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
152 //       until you _really_ know what you do!
153 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
154   if(ftype == Invalid)
155     return QTextCharFormat();
156   if(_cachedFormats.contains(ftype))
157     return _cachedFormats.value(ftype);
158
159   QTextCharFormat fmt;
160
161   // Check if we have a special message format stored already sans color codes
162   if(_cachedFormats.contains(ftype & 0x1fffff))
163     fmt = _cachedFormats.value(ftype &0x1fffff);
164   else {
165     // Nope, so we have to construct it...
166     // We assume that we don't mix mirc format codes and component codes, so at this point we know that it's either
167     // a stock (not stylesheeted) component, or mirc formats
168     // In both cases, we start off with the basic format for this message type and then merge the extra stuff
169
170     // Check if we at least already have something stored for the message type first
171     if(_cachedFormats.contains(ftype & 0xf))
172       fmt = _cachedFormats.value(ftype & 0xf);
173     else {
174       // Not being in the cache means it hasn't been preset via stylesheet (or used before)
175       // We might still have set something in code as a fallback, so merge
176       fmt = format(None);
177       fmt.merge(format((FormatType)(ftype & 0x0f)));
178       // This can be cached
179       _cachedFormats[ftype & 0x0f] = fmt;
180     }
181     // OK, at this point we have the message type format - now merge the rest
182     if((ftype & 0xf0)) { // mirc format
183       for(quint32 mask = 0x10; mask <= 0x80; mask <<= 1) {
184         if(!(ftype & mask))
185           continue;
186         // We need to check for overrides in the cache
187         if(_cachedFormats.contains(mask | (ftype & 0x0f)))
188           fmt.merge(_cachedFormats.value(mask | (ftype & 0x0f)));
189         else if(_cachedFormats.contains(mask))
190           fmt.merge(_cachedFormats.value(mask));
191         else // nothing in cache, use stock format
192           fmt.merge(format((FormatType)mask));
193       }
194     } else { // component
195       // We've already checked the cache for the combo of msgtype and component and failed,
196       // so we check if we defined a general format and merge this, or the stock format else
197       if(_cachedFormats.contains(ftype & 0xff00))
198         fmt.merge(_cachedFormats.value(ftype & 0xff00));
199       else
200         fmt.merge(format((FormatType)(ftype & 0xff00)));
201     }
202   }
203
204   // Now we handle color codes. We assume that those can't be combined with components
205   if(ftype & 0x00400000)
206     fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
207   if(ftype & 0x00800000)
208     fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
209
210   // Sender auto colors
211   if(_senderAutoColor && (ftype & 0x200) && (ftype & 0xff000200) != 0x200) {
212     if(_cachedFormats.contains(ftype & 0xff00020f))
213       fmt.merge(_cachedFormats.value(ftype & 0xff00020f));
214     else if(_cachedFormats.contains(ftype & 0xff000200))
215       fmt.merge(_cachedFormats.value(ftype & 0xff000200));
216     else
217       fmt.merge(format((FormatType)(ftype & 0xff000200)));
218   }
219
220   // URL
221   if(ftype & Url)
222     fmt.merge(format(Url)); // TODO handle this properly
223
224   return _cachedFormats[ftype] = fmt;
225 }
226
227 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
228   // QFontMetricsF is not assignable, so we need to store pointers :/
229   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
230   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
231 }
232
233 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
234   if(_formatCodes.contains(code)) return _formatCodes.value(code);
235   return Invalid;
236 }
237
238 QString UiStyle::formatCode(FormatType ftype) const {
239   return _formatCodes.key(ftype);
240 }
241
242 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
243   QList<QTextLayout::FormatRange> formatRanges;
244   QTextLayout::FormatRange range;
245   int i = 0;
246   for(i = 0; i < formatList.count(); i++) {
247     range.format = mergedFormat(formatList.at(i).second);
248     range.start = formatList.at(i).first;
249     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
250     formatRanges.append(range);
251   }
252   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
253   return formatRanges;
254 }
255
256 // This method expects a well-formatted string, there is no error checking!
257 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
258 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
259   QString s = s_;
260   if(s.length() > 65535) {
261     qWarning() << QString("String too long to be styled: %1").arg(s);
262     return StyledString();
263   }
264   StyledString result;
265   result.formatList.append(qMakePair((quint16)0, (quint32)None));
266   quint32 curfmt = (quint32)None;
267   int pos = 0; quint16 length = 0;
268   for(;;) {
269     pos = s.indexOf('%', pos);
270     if(pos < 0) break;
271     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
272       s.remove(pos, 1);
273       pos++;
274       continue;
275     }
276     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
277       if(s[pos+3] == '-') {  // color off
278         curfmt &= 0x003fffff;
279         length = 4;
280       } else {
281         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
282         //TODO: use 99 as transparent color (re mirc color "standard")
283         color &= 0x0f;
284         if(s[pos+3] == 'f') {
285           curfmt &= 0xf0ffffff;
286           curfmt |= (color << 24) | 0x00400000;
287         } else {
288           curfmt &= 0x0fffffff;
289           curfmt |= (color << 28) | 0x00800000;
290         }
291         length = 6;
292       }
293     } else if(s[pos+1] == 'O') { // reset formatting
294       curfmt &= 0x0000000f; // we keep message type-specific formatting
295       length = 2;
296     } else if(s[pos+1] == 'R') { // reverse
297       // TODO: implement reverse formatting
298
299       length = 2;
300     } else { // all others are toggles
301       QString code = QString("%") + s[pos+1];
302       if(s[pos+1] == 'D') code += s[pos+2];
303       FormatType ftype = formatType(code);
304       if(ftype == Invalid) {
305         qWarning() << (QString("Invalid format code in string: %1").arg(s));
306         continue;
307       }
308       curfmt ^= ftype;
309       length = code.length();
310     }
311     s.remove(pos, length);
312     if(pos == result.formatList.last().first)
313       result.formatList.last().second = curfmt;
314     else
315       result.formatList.append(qMakePair((quint16)pos, curfmt));
316   }
317   result.plainText = s;
318   return result;
319 }
320
321 QString UiStyle::mircToInternal(const QString &mirc_) const {
322   QString mirc = mirc_;
323   mirc.replace('%', "%%");      // escape % just to be sure
324   mirc.replace('\x02', "%B");
325   mirc.replace('\x0f', "%O");
326   mirc.replace('\x12', "%R");
327   mirc.replace('\x16', "%R");
328   mirc.replace('\x1d', "%S");
329   mirc.replace('\x1f', "%U");
330
331   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
332   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
333   // %Dc- turns color off.
334   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
335   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
336   int pos = 0;
337   for(;;) {
338     pos = mirc.indexOf('\x03', pos);
339     if(pos < 0) break; // no more mirc color codes
340     QString ins, num;
341     int l = mirc.length();
342     int i = pos + 1;
343     // check for fg color
344     if(i < l && mirc[i].isDigit()) {
345       num = mirc[i++];
346       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
347       else num.prepend('0');
348       ins = QString("%Dcf%1").arg(num);
349
350       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
351         i++;
352         num = mirc[i++];
353         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
354         else num.prepend('0');
355         ins += QString("%Dcb%1").arg(num);
356       }
357     } else {
358       ins = "%Dc-";
359     }
360     mirc.replace(pos, i-pos, ins);
361   }
362   return mirc;
363 }
364
365 /***********************************************************************************/
366 UiStyle::StyledMessage::StyledMessage(const Message &msg)
367   : Message(msg)
368 {
369 }
370
371 void UiStyle::StyledMessage::style(UiStyle *style) const {
372   QString user = userFromMask(sender());
373   QString host = hostFromMask(sender());
374   QString nick = nickFromMask(sender());
375   QString txt = style->mircToInternal(contents());
376   QString bufferName = bufferInfo().bufferName();
377   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
378
379   QString t;
380   switch(type()) {
381     case Message::Plain:
382       t = tr("%D0%1").arg(txt); break;
383     case Message::Notice:
384       t = tr("%Dn%1").arg(txt); break;
385     case Message::Topic:
386     case Message::Server:
387       t = tr("%Ds%1").arg(txt); break;
388     case Message::Error:
389       t = tr("%De%1").arg(txt); break;
390     case Message::Join:
391       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
392     case Message::Part:
393       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
394       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
395       break;
396     case Message::Quit:
397       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
398       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
399       break;
400     case Message::Kick: {
401         QString victim = txt.section(" ", 0, 0);
402         QString kickmsg = txt.section(" ", 1);
403         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
404         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
405       }
406       break;
407     case Message::Nick:
408       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
409       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
410       break;
411     case Message::Mode:
412       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
413       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
414       break;
415     case Message::Action:
416       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
417       break;
418     default:
419       t = tr("%De[%1]").arg(txt);
420   }
421   _contents = style->styleString(t);
422 }
423
424 QString UiStyle::StyledMessage::decoratedTimestamp() const {
425   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
426 }
427
428 QString UiStyle::StyledMessage::plainSender() const {
429   switch(type()) {
430     case Message::Plain:
431     case Message::Notice:
432       return nickFromMask(sender());
433     default:
434       return QString();
435   }
436 }
437
438 QString UiStyle::StyledMessage::decoratedSender() const {
439   switch(type()) {
440     case Message::Plain:
441       return tr("<%1>").arg(plainSender()); break;
442     case Message::Notice:
443       return tr("[%1]").arg(plainSender()); break;
444     case Message::Topic:
445     case Message::Server:
446       return tr("*"); break;
447     case Message::Error:
448       return tr("*"); break;
449     case Message::Join:
450       return tr("-->"); break;
451     case Message::Part:
452       return tr("<--"); break;
453     case Message::Quit:
454       return tr("<--"); break;
455     case Message::Kick:
456       return tr("<-*"); break;
457     case Message::Nick:
458       return tr("<->"); break;
459     case Message::Mode:
460       return tr("***"); break;
461     case Message::Action:
462       return tr("-*-"); break;
463     default:
464       return tr("%1").arg(plainSender());
465   }
466 }
467
468 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
469   switch(type()) {
470     case Message::Plain:
471       // To produce random like but stable nick colorings some sort of hashing should work best.
472       // In this case we just use the qt function qChecksum which produces a
473       // CRC16 hash. This should be fast and 16 bits are more than enough.
474       {
475         QString nick = nickFromMask(sender()).toLower();
476         if(!nick.isEmpty()) {
477           int chopCount = 0;
478           while(nick[nick.count() - 1 - chopCount] == '_') {
479             chopCount++;
480           }
481           nick.chop(chopCount);
482         }
483         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
484         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
485       }
486     case Message::Notice:
487       return UiStyle::NoticeMsg; break;
488     case Message::Topic:
489     case Message::Server:
490       return UiStyle::ServerMsg; break;
491     case Message::Error:
492       return UiStyle::ErrorMsg; break;
493     case Message::Join:
494       return UiStyle::JoinMsg; break;
495     case Message::Part:
496       return UiStyle::PartMsg; break;
497     case Message::Quit:
498       return UiStyle::QuitMsg; break;
499     case Message::Kick:
500       return UiStyle::KickMsg; break;
501     case Message::Nick:
502       return UiStyle::RenameMsg; break;
503     case Message::Mode:
504       return UiStyle::ModeMsg; break;
505     case Message::Action:
506       return UiStyle::ActionMsg; break;
507     default:
508       return UiStyle::ErrorMsg;
509   }
510 }
511
512
513 /***********************************************************************************/
514
515 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
516   out << formatList.count();
517   UiStyle::FormatList::const_iterator it = formatList.begin();
518   while(it != formatList.end()) {
519     out << (*it).first << (*it).second;
520     ++it;
521   }
522   return out;
523 }
524
525 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
526   quint16 cnt;
527   in >> cnt;
528   for(quint16 i = 0; i < cnt; i++) {
529     quint16 pos; quint32 ftype;
530     in >> pos >> ftype;
531     formatList.append(qMakePair((quint16)pos, ftype));
532   }
533   return in;
534 }
535
536 /***********************************************************************************/
537 // Stylesheet handling
538 /***********************************************************************************/
539
540 void UiStyle::loadStyleSheet() {
541   QssParser parser;
542   parser.loadStyleSheet(qApp->styleSheet());
543
544   // TODO handle results
545   QApplication::setPalette(parser.palette());
546 }
547
548 UiStyle::QssParser::QssParser() {
549   _palette = QApplication::palette();
550
551   // Init palette color roles
552   _paletteColorRoles["alternate-base"] = QPalette::AlternateBase;
553   _paletteColorRoles["background"] = QPalette::Background;
554   _paletteColorRoles["base"] = QPalette::Base;
555   _paletteColorRoles["bright-text"] = QPalette::BrightText;
556   _paletteColorRoles["button"] = QPalette::Button;
557   _paletteColorRoles["button-text"] = QPalette::ButtonText;
558   _paletteColorRoles["dark"] = QPalette::Dark;
559   _paletteColorRoles["foreground"] = QPalette::Foreground;
560   _paletteColorRoles["highlight"] = QPalette::Highlight;
561   _paletteColorRoles["highlighted-text"] = QPalette::HighlightedText;
562   _paletteColorRoles["light"] = QPalette::Light;
563   _paletteColorRoles["link"] = QPalette::Link;
564   _paletteColorRoles["link-visited"] = QPalette::LinkVisited;
565   _paletteColorRoles["mid"] = QPalette::Mid;
566   _paletteColorRoles["midlight"] = QPalette::Midlight;
567   _paletteColorRoles["shadow"] = QPalette::Shadow;
568   _paletteColorRoles["text"] = QPalette::Text;
569   _paletteColorRoles["tooltip-base"] = QPalette::ToolTipBase;
570   _paletteColorRoles["tooltip-text"] = QPalette::ToolTipText;
571   _paletteColorRoles["window"] = QPalette::Window;
572   _paletteColorRoles["window-text"] = QPalette::WindowText;
573 }
574
575 void UiStyle::QssParser::loadStyleSheet(const QString &styleSheet) {
576   QString ss = styleSheet;
577   ss = "file:////home/sputnick/devel/quassel/test.qss"; // FIXME
578   if(ss.startsWith("file:///")) {
579     ss.remove(0, 8);
580     QFile file(ss);
581     if(file.open(QFile::ReadOnly)) {
582       QTextStream stream(&file);
583       ss = stream.readAll();
584     } else {
585       qWarning() << tr("Could not read stylesheet \"%1\"!").arg(file.fileName());
586       return;
587     }
588   }
589   if(ss.isEmpty())
590     return;
591
592   // Now we have the stylesheet itself in ss, start parsing
593   QRegExp blockrx("((ChatLine|Palette)[^{]*)\\{([^}]+)\\}");
594   int pos = 0;
595   while((pos = blockrx.indexIn(ss, pos)) >= 0) {
596     //qDebug() << blockrx.cap(1) << blockrx.cap(3);
597
598     if(blockrx.cap(2) == "ChatLine")
599       parseChatLineData(blockrx.cap(1).trimmed(), blockrx.cap(3).trimmed());
600     else
601       parsePaletteData(blockrx.cap(1).trimmed(), blockrx.cap(3).trimmed());
602
603     pos += blockrx.matchedLength();
604   }
605
606 }
607
608 void UiStyle::QssParser::parseChatLineData(const QString &decl, const QString &contents) {
609
610
611 }
612
613 // Palette { ... } specifies the application palette
614 // ColorGroups can be specified like pseudo states, chaining is OR (contrary to normal CSS handling):
615 //   Palette:inactive:disabled { ... } applies to both the Inactive and the Disabled state
616 void UiStyle::QssParser::parsePaletteData(const QString &decl, const QString &contents) {
617   QList<QPalette::ColorGroup> colorGroups;
618
619   // Check if we want to apply this palette definition for particular ColorGroups
620   QRegExp rx("Palette((:(normal|active|inactive|disabled))*)");
621   if(!rx.exactMatch(decl)) {
622     qWarning() << tr("Invalid block declaration: %1").arg(decl);
623     return;
624   }
625   if(!rx.cap(1).isEmpty()) {
626     QStringList groups = rx.cap(1).split(':', QString::SkipEmptyParts);
627     foreach(QString g, groups) {
628       if((g == "normal" || g == "active") && !colorGroups.contains(QPalette::Active))
629         colorGroups.append(QPalette::Active);
630       else if(g == "inactive" && !colorGroups.contains(QPalette::Inactive))
631         colorGroups.append(QPalette::Inactive);
632       else if(g == "disabled" && !colorGroups.contains(QPalette::Disabled))
633         colorGroups.append(QPalette::Disabled);
634     }
635   }
636
637   // Now let's go through the roles
638   foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
639     int idx = line.indexOf(':');
640     if(idx <= 0) {
641       qWarning() << tr("Invalid palette role assignment: %1").arg(line.trimmed());
642       continue;
643     }
644     QString rolestr = line.left(idx).trimmed();
645     QString brushstr = line.mid(idx + 1).trimmed();
646     if(!_paletteColorRoles.contains(rolestr)) {
647       qWarning() << tr("Unknown palette role name: %1").arg(rolestr);
648       continue;
649     }
650     QBrush brush = parseBrushValue(brushstr);
651     if(colorGroups.count()) {
652       foreach(QPalette::ColorGroup group, colorGroups)
653         _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
654     } else
655       _palette.setBrush(_paletteColorRoles.value(rolestr), brush);
656   }
657 }
658
659 QBrush UiStyle::QssParser::parseBrushValue(const QString &str) {
660   QColor c = parseColorValue(str);
661   if(c.isValid())
662     return QBrush(c);
663
664   if(str.startsWith("palette")) { // Palette color role
665     QRegExp rx("palette\\s*\\(\\s*([a-z-]+)\\s*\\)");
666     if(!rx.exactMatch(str)) {
667       qWarning() << tr("Invalid palette color role specification: %1").arg(str);
668       return QBrush();
669     }
670     if(!_paletteColorRoles.contains(rx.cap(1))) {
671       qWarning() << tr("Unknown palette color role: %1").arg(rx.cap(1));
672       return QBrush();
673     }
674     return QBrush(_palette.brush(_paletteColorRoles.value(rx.cap(1))));
675
676   } else if(str.startsWith("qlineargradient")) {
677     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
678     QRegExp rx(QString("qlineargradient\\s*\\(\\s*x1:%1,\\s*y1:%1,\\s*x2:%1,\\s*y2:%1,(.+)\\)").arg(rxFloat));
679     if(!rx.exactMatch(str)) {
680       qWarning() << tr("Invalid gradient declaration: %1").arg(str);
681       return QBrush();
682     }
683     qreal x1 = rx.cap(1).toDouble();
684     qreal y1 = rx.cap(2).toDouble();
685     qreal x2 = rx.cap(3).toDouble();
686     qreal y2 = rx.cap(4).toDouble();
687     QGradientStops stops = parseGradientStops(rx.cap(5).trimmed());
688     if(!stops.count()) {
689       qWarning() << tr("Invalid gradient stops list: %1").arg(str);
690       return QBrush();
691     }
692     QLinearGradient gradient(x1, y1, x2, y2);
693     gradient.setStops(stops);
694     return QBrush(gradient);
695
696   } else if(str.startsWith("qconicalgradient")) {
697     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
698     QRegExp rx(QString("qconicalgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*angle:%1,(.+)\\)").arg(rxFloat));
699     if(!rx.exactMatch(str)) {
700       qWarning() << tr("Invalid gradient declaration: %1").arg(str);
701       return QBrush();
702     }
703     qreal cx = rx.cap(1).toDouble();
704     qreal cy = rx.cap(2).toDouble();
705     qreal angle = rx.cap(3).toDouble();
706     QGradientStops stops = parseGradientStops(rx.cap(4).trimmed());
707     if(!stops.count()) {
708       qWarning() << tr("Invalid gradient stops list: %1").arg(str);
709       return QBrush();
710     }
711     QConicalGradient gradient(cx, cy, angle);
712     gradient.setStops(stops);
713     return QBrush(gradient);
714
715   } else if(str.startsWith("qradialgradient")) {
716     static QString rxFloat("\\s*(-?\\s*[0-9]*\\.?[0-9]+)\\s*");
717     QRegExp rx(QString("qradialgradient\\s*\\(\\s*cx:%1,\\s*cy:%1,\\s*radius:%1,\\s*fx:%1,\\s*fy:%1,(.+)\\)").arg(rxFloat));
718     if(!rx.exactMatch(str)) {
719       qWarning() << tr("Invalid gradient declaration: %1").arg(str);
720       return QBrush();
721     }
722     qreal cx = rx.cap(1).toDouble();
723     qreal cy = rx.cap(2).toDouble();
724     qreal radius = rx.cap(3).toDouble();
725     qreal fx = rx.cap(4).toDouble();
726     qreal fy = rx.cap(5).toDouble();
727     QGradientStops stops = parseGradientStops(rx.cap(6).trimmed());
728     if(!stops.count()) {
729       qWarning() << tr("Invalid gradient stops list: %1").arg(str);
730       return QBrush();
731     }
732     QRadialGradient gradient(cx, cy, radius, fx, fy);
733     gradient.setStops(stops);
734     return QBrush(gradient);
735   }
736
737   return QBrush();
738 }
739
740 QColor UiStyle::QssParser::parseColorValue(const QString &str) {
741   if(str.startsWith("rgba")) {
742     ColorTuple tuple = parseColorTuple(str.mid(4));
743     if(tuple.count() == 4)
744       return QColor(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
745   } else if(str.startsWith("rgb")) {
746     ColorTuple tuple = parseColorTuple(str.mid(3));
747     if(tuple.count() == 3)
748       return QColor(tuple.at(0), tuple.at(1), tuple.at(2));
749   } else if(str.startsWith("hsva")) {
750     ColorTuple tuple = parseColorTuple(str.mid(4));
751     if(tuple.count() == 4) {
752       QColor c;
753       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2), tuple.at(3));
754       return c;
755     }
756   } else if(str.startsWith("hsv")) {
757     ColorTuple tuple = parseColorTuple(str.mid(3));
758     if(tuple.count() == 3) {
759       QColor c;
760       c.setHsvF(tuple.at(0), tuple.at(1), tuple.at(2));
761       return c;
762     }
763   } else {
764     QRegExp rx("#?[0-9A-Fa-z]+");
765     if(rx.exactMatch(str))
766       return QColor(str);
767   }
768   return QColor();
769 }
770
771 // get a list of comma-separated int values or percentages (rel to 0-255)
772 UiStyle::QssParser::ColorTuple UiStyle::QssParser::parseColorTuple(const QString &str) {
773   ColorTuple result;
774   QRegExp rx("\\(((\\s*[0-9]{1,3}%?\\s*)(,\\s*[0-9]{1,3}%?\\s*)*)\\)");
775   if(!rx.exactMatch(str.trimmed())) {
776     return ColorTuple();
777   }
778   QStringList values = rx.cap(1).split(',');
779   foreach(QString v, values) {
780     qreal val;
781     bool perc = false;
782     bool ok;
783     v = v.trimmed();
784     if(v.endsWith('%')) {
785       perc = true;
786       v.chop(1);
787     }
788     val = (qreal)v.toUInt(&ok);
789     if(!ok)
790       return ColorTuple();
791     if(perc)
792       val = 255 * val/100;
793     result.append(val);
794   }
795   return result;
796 }
797
798 QGradientStops UiStyle::QssParser::parseGradientStops(const QString &str_) {
799   QString str = str_;
800   QGradientStops result;
801   static QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
802   QRegExp rx(QString("\\s*,?\\s*stop:\\s*(%1)\\s+([^:]+)(,\\s*stop:|$)").arg(rxFloat));
803   int idx;
804   while((idx = rx.indexIn(str)) == 0) {
805     qreal x = rx.cap(1).toDouble();
806     QColor c = parseColorValue(rx.cap(3));
807     if(!c.isValid())
808       return QGradientStops();
809     result << QGradientStop(x, c);
810     str.remove(0, rx.matchedLength() - rx.cap(4).length());
811   }
812   if(!str.trimmed().isEmpty())
813     return QGradientStops();
814
815   return result;
816 }