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