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