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