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