Stylesheetify the marker line color
[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 "qssparser.h"
23 #include "quassel.h"
24 #include "uistyle.h"
25 #include "uisettings.h"
26 #include "util.h"
27
28 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
29 QString UiStyle::_timestampFormatString;
30
31 UiStyle::UiStyle(QObject *parent) : QObject(parent) {
32   // register FormatList if that hasn't happened yet
33   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
34   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
35     qRegisterMetaType<FormatList>("UiStyle::FormatList");
36     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
37     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
38   }
39
40   // Now initialize the mapping between FormatCodes and FormatTypes...
41   _formatCodes["%O"] = Base;
42   _formatCodes["%B"] = Bold;
43   _formatCodes["%S"] = Italic;
44   _formatCodes["%U"] = Underline;
45   _formatCodes["%R"] = Reverse;
46
47   _formatCodes["%DN"] = Nick;
48   _formatCodes["%DH"] = Hostmask;
49   _formatCodes["%DC"] = ChannelName;
50   _formatCodes["%DM"] = ModeFlags;
51   _formatCodes["%DU"] = Url;
52
53   setTimestampFormatString("[hh:mm:ss]");
54
55   loadStyleSheet();
56 }
57
58 UiStyle::~UiStyle() {
59   qDeleteAll(_metricsCache);
60 }
61
62 void UiStyle::reload() {
63   loadStyleSheet();
64 }
65
66 void UiStyle::loadStyleSheet() {
67   qDeleteAll(_metricsCache);
68   _metricsCache.clear();
69   _formatCache.clear();
70
71   UiStyleSettings s;
72
73   QString styleSheet;
74   styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("default.qss"));
75   styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
76   if(s.value("UseCustomStyleSheet", false).toBool())
77     styleSheet += loadStyleSheet("file:///" + s.value("CustomStyleSheetPath").toString(), true);
78   styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
79
80   if(!styleSheet.isEmpty()) {
81     QssParser parser;
82     parser.processStyleSheet(styleSheet);
83     QApplication::setPalette(parser.palette());
84     _markerLineBrush = parser.markerLineBrush();
85
86     QTextCharFormat baseFmt = parser.formats().value(Base);
87     foreach(quint64 fmtType, parser.formats().keys()) {
88       QTextCharFormat fmt = baseFmt;
89       fmt.merge(parser.formats().value(fmtType));
90       _formatCache[fmtType] = fmt;
91     }
92
93     qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
94   }
95
96   emit changed();
97 }
98
99 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist) {
100   QString ss = styleSheet;
101   if(ss.startsWith("file:///")) {
102     ss.remove(0, 8);
103     if(ss.isEmpty())
104       return QString();
105
106     QFile file(ss);
107     if(file.open(QFile::ReadOnly)) {
108       QTextStream stream(&file);
109       ss = stream.readAll();
110       file.close();
111     } else {
112       if(shouldExist)
113         qWarning() << "Could not open stylesheet file:" << file.fileName();
114       return QString();
115     }
116   }
117   return ss;
118 }
119
120 void UiStyle::setTimestampFormatString(const QString &format) {
121   if(_timestampFormatString != format) {
122     _timestampFormatString = format;
123     // FIXME reload
124   }
125 }
126
127 /******** Caching *******/
128
129 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
130   return _formatCache.value(key, QTextCharFormat());
131 }
132
133 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
134   return cachedFormat(formatType | ((quint64)messageLabel << 32));
135 }
136
137 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
138   _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
139 }
140
141 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
142   // QFontMetricsF is not assignable, so we need to store pointers :/
143   quint64 key = ftype | ((quint64)label << 32);
144
145   if(_metricsCache.contains(key))
146     return _metricsCache.value(key);
147
148   return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
149 }
150
151 /******** Generate formats ********/
152
153 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
154 //       until you _really_ know what you do!
155 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) {
156   if(ftype == Invalid)
157     return QTextCharFormat();
158
159   quint64 label = (quint64)label_ << 32;
160
161   // check if we have exactly this format readily cached already
162   QTextCharFormat fmt = cachedFormat(label|ftype);
163   if(fmt.properties().count())
164     return fmt;
165
166   mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
167
168   for(quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<=1) {
169     if(label & mask)
170       mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
171   }
172
173   setCachedFormat(fmt, ftype, label_);
174   return fmt;
175 }
176
177 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) {
178   mergeSubElementFormat(fmt, ftype & 0x00ff, label);
179
180   // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
181   //       or "foreground 01 and background 03"
182   if((ftype & 0xfff0)) { // element format
183     for(quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
184       if(ftype & mask) {
185         mergeSubElementFormat(fmt, mask | 0xff, label);
186       }
187     }
188   }
189
190   // Now we handle color codes
191   // We assume that those can't be combined with subelement and message types.
192   if(ftype & 0x00400000)
193     mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
194   if(ftype & 0x00800000)
195     mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
196   if((ftype & 0x00c00000) == 0x00c00000)
197     mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
198
199   // URL
200   if(ftype & Url)
201     mergeSubElementFormat(fmt, ftype & Url, label);
202 }
203
204 // Merge a subelement format into an existing message format
205 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint64 label) {
206   quint64 key = ftype | label;
207   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffffffffff00)));  // label + subelement
208   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffffffffffff)));  // label + subelement + msgtype
209   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffffffffff00)));  // label + subelement + nickhash
210   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffffffffffff)));  // label + subelement + nickhash + msgtype
211 }
212
213 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) {
214   switch(msgType) {
215     case Message::Plain:
216       return PlainMsg;
217     case Message::Notice:
218       return NoticeMsg;
219     case Message::Action:
220       return ActionMsg;
221     case Message::Nick:
222       return NickMsg;
223     case Message::Mode:
224       return ModeMsg;
225     case Message::Join:
226       return JoinMsg;
227     case Message::Part:
228       return PartMsg;
229     case Message::Quit:
230       return QuitMsg;
231     case Message::Kick:
232       return KickMsg;
233     case Message::Kill:
234       return KillMsg;
235     case Message::Server:
236       return ServerMsg;
237     case Message::Info:
238       return InfoMsg;
239     case Message::Error:
240       return ErrorMsg;
241     case Message::DayChange:
242       return DayChangeMsg;
243   }
244   //Q_ASSERT(false); // we need to handle all message types
245   qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
246   return ErrorMsg;
247 }
248
249 UiStyle::FormatType UiStyle::formatType(const QString & code) {
250   if(_formatCodes.contains(code)) return _formatCodes.value(code);
251   return Invalid;
252 }
253
254 QString UiStyle::formatCode(FormatType ftype) {
255   return _formatCodes.key(ftype);
256 }
257
258 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) {
259   QList<QTextLayout::FormatRange> formatRanges;
260   QTextLayout::FormatRange range;
261   int i = 0;
262   for(i = 0; i < formatList.count(); i++) {
263     range.format = format(formatList.at(i).second, messageLabel);
264     range.start = formatList.at(i).first;
265     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
266     formatRanges.append(range);
267   }
268   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
269   return formatRanges;
270 }
271
272 // This method expects a well-formatted string, there is no error checking!
273 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
274 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
275   QString s = s_;
276   if(s.length() > 65535) {
277     qWarning() << QString("String too long to be styled: %1").arg(s);
278     return StyledString();
279   }
280   StyledString result;
281   result.formatList.append(qMakePair((quint16)0, baseFormat));
282   quint32 curfmt = baseFormat;
283   int pos = 0; quint16 length = 0;
284   for(;;) {
285     pos = s.indexOf('%', pos);
286     if(pos < 0) break;
287     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
288       s.remove(pos, 1);
289       pos++;
290       continue;
291     }
292     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
293       if(s[pos+3] == '-') {  // color off
294         curfmt &= 0x003fffff;
295         length = 4;
296       } else {
297         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
298         //TODO: use 99 as transparent color (re mirc color "standard")
299         color &= 0x0f;
300         if(s[pos+3] == 'f') {
301           curfmt &= 0xf0ffffff;
302           curfmt |= (color << 24) | 0x00400000;
303         } else {
304           curfmt &= 0x0fffffff;
305           curfmt |= (color << 28) | 0x00800000;
306         }
307         length = 6;
308       }
309     } else if(s[pos+1] == 'O') { // reset formatting
310       curfmt &= 0x000000ff; // we keep message type-specific formatting
311       length = 2;
312     } else if(s[pos+1] == 'R') { // reverse
313       // TODO: implement reverse formatting
314
315       length = 2;
316     } else { // all others are toggles
317       QString code = QString("%") + s[pos+1];
318       if(s[pos+1] == 'D') code += s[pos+2];
319       FormatType ftype = formatType(code);
320       if(ftype == Invalid) {
321         qWarning() << (QString("Invalid format code in string: %1").arg(s));
322         continue;
323       }
324       curfmt ^= ftype;
325       length = code.length();
326     }
327     s.remove(pos, length);
328     if(pos == result.formatList.last().first)
329       result.formatList.last().second = curfmt;
330     else
331       result.formatList.append(qMakePair((quint16)pos, curfmt));
332   }
333   result.plainText = s;
334   return result;
335 }
336
337 QString UiStyle::mircToInternal(const QString &mirc_) {
338   QString mirc = mirc_;
339   mirc.replace('%', "%%");      // escape % just to be sure
340   mirc.replace('\x02', "%B");
341   mirc.replace('\x0f', "%O");
342   mirc.replace('\x12', "%R");
343   mirc.replace('\x16', "%R");
344   mirc.replace('\x1d', "%S");
345   mirc.replace('\x1f', "%U");
346
347   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
348   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
349   // %Dc- turns color off.
350   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
351   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
352   int pos = 0;
353   for(;;) {
354     pos = mirc.indexOf('\x03', pos);
355     if(pos < 0) break; // no more mirc color codes
356     QString ins, num;
357     int l = mirc.length();
358     int i = pos + 1;
359     // check for fg color
360     if(i < l && mirc[i].isDigit()) {
361       num = mirc[i++];
362       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
363       else num.prepend('0');
364       ins = QString("%Dcf%1").arg(num);
365
366       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
367         i++;
368         num = mirc[i++];
369         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
370         else num.prepend('0');
371         ins += QString("%Dcb%1").arg(num);
372       }
373     } else {
374       ins = "%Dc-";
375     }
376     mirc.replace(pos, i-pos, ins);
377   }
378   return mirc;
379 }
380
381 /***********************************************************************************/
382 UiStyle::StyledMessage::StyledMessage(const Message &msg)
383   : Message(msg)
384 {
385   if(type() == Message::Plain)
386     _senderHash = 0xff;
387   else
388     _senderHash = 0x00;  // this means we never compute the hash for msgs that aren't plain
389 }
390
391 void UiStyle::StyledMessage::style() const {
392   QString user = userFromMask(sender());
393   QString host = hostFromMask(sender());
394   QString nick = nickFromMask(sender());
395   QString txt = UiStyle::mircToInternal(contents());
396   QString bufferName = bufferInfo().bufferName();
397   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
398
399   QString t;
400   switch(type()) {
401     case Message::Plain:
402       //: Plain Message
403       t = tr("%1").arg(txt); break;
404     case Message::Notice:
405       //: Notice Message
406       t = tr("%1").arg(txt); break;
407     case Message::Action:
408       //: Action Message
409       t = tr("%DN%1%DN %2").arg(nick).arg(txt);
410       break;
411     case Message::Nick:
412       //: Nick Message
413       if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
414       else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
415       break;
416     case Message::Mode:
417       //: Mode Message
418       if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
419       else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
420       break;
421     case Message::Join:
422       //: Join Message
423       t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
424     case Message::Part:
425       //: Part Message
426       t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
427       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
428       break;
429     case Message::Quit:
430       //: Quit Message
431       t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
432       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
433       break;
434     case Message::Kick: {
435         QString victim = txt.section(" ", 0, 0);
436         QString kickmsg = txt.section(" ", 1);
437         //: Kick Message
438         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
439         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
440       }
441       break;
442     //case Message::Kill: FIXME
443
444     case Message::Server:
445       //: Server Message
446       t = tr("%1").arg(txt); break;
447     case Message::Info:
448       //: Info Message
449       t = tr("%1").arg(txt); break;
450     case Message::Error:
451       //: Error Message
452       t = tr("%1").arg(txt); break;
453     case Message::DayChange:
454       //: Day Change Message
455       t = tr("{Day changed to %1}").arg(timestamp().toString());
456       break;
457     default:
458       t = tr("[%1]").arg(txt);
459   }
460   _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
461 }
462
463 const QString &UiStyle::StyledMessage::plainContents() const {
464   if(_contents.plainText.isNull())
465     style();
466
467   return _contents.plainText;
468 }
469
470 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
471   if(_contents.plainText.isNull())
472     style();
473
474   return _contents.formatList;
475 }
476
477 QString UiStyle::StyledMessage::decoratedTimestamp() const {
478   return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
479 }
480
481 QString UiStyle::StyledMessage::plainSender() const {
482   switch(type()) {
483     case Message::Plain:
484     case Message::Notice:
485       return nickFromMask(sender());
486     default:
487       return QString();
488   }
489 }
490
491 QString UiStyle::StyledMessage::decoratedSender() const {
492   switch(type()) {
493     case Message::Plain:
494       return tr("<%1>").arg(plainSender()); break;
495     case Message::Notice:
496       return tr("[%1]").arg(plainSender()); break;
497     case Message::Action:
498       return tr("-*-"); break;
499     case Message::Nick:
500       return tr("<->"); break;
501     case Message::Mode:
502       return tr("***"); break;
503     case Message::Join:
504       return tr("-->"); break;
505     case Message::Part:
506       return tr("<--"); break;
507     case Message::Quit:
508       return tr("<--"); break;
509     case Message::Kick:
510       return tr("<-*"); break;
511     case Message::Kill:
512       return tr("<-x"); break;
513     case Message::Server:
514       return tr("*"); break;
515     case Message::Info:
516       return tr("*"); break;
517     case Message::Error:
518       return tr("*"); break;
519     case Message::DayChange:
520       return tr("-"); break;
521     default:
522       return tr("%1").arg(plainSender());
523   }
524 }
525
526 // FIXME hardcoded to 16 sender hashes
527 quint8 UiStyle::StyledMessage::senderHash() const {
528   if(_senderHash != 0xff)
529     return _senderHash;
530
531   QString nick = nickFromMask(sender()).toLower();
532   if(!nick.isEmpty()) {
533     int chopCount = 0;
534     while(nick.at(nick.count() - 1 - chopCount) == '_')
535       chopCount++;
536     nick.chop(chopCount);
537   }
538   quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
539   return (_senderHash = (hash & 0xf) + 1);
540 }
541
542 /***********************************************************************************/
543
544 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
545   out << formatList.count();
546   UiStyle::FormatList::const_iterator it = formatList.begin();
547   while(it != formatList.end()) {
548     out << (*it).first << (*it).second;
549     ++it;
550   }
551   return out;
552 }
553
554 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
555   quint16 cnt;
556   in >> cnt;
557   for(quint16 i = 0; i < cnt; i++) {
558     quint16 pos; quint32 ftype;
559     in >> pos >> ftype;
560     formatList.append(qMakePair((quint16)pos, ftype));
561   }
562   return in;
563 }