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