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