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