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