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