Rework mergedFormats() to handle pre-set formats
[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 "quassel.h"
23 #include "uistyle.h"
24 #include "uisettings.h"
25 #include "util.h"
26
27 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
28   // register FormatList if that hasn't happened yet
29   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
30   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
31     qRegisterMetaType<FormatList>("UiStyle::FormatList");
32     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
33     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
34   }
35
36   _defaultFont = QFont("Monospace", QApplication::font().pointSize());
37
38   // Default format
39   _defaultPlainFormat.setForeground(QBrush("#000000"));
40   _defaultPlainFormat.setFont(_defaultFont);
41   _defaultPlainFormat.font().setFixedPitch(true);
42   _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
43   setFormat(None, _defaultPlainFormat, Settings::Default);
44
45   // Load saved custom formats
46   UiStyleSettings s(_settingsKey);
47   foreach(FormatType type, s.availableFormats()) {
48     _customFormats[type] = s.customFormat(type);
49   }
50
51   // Check for the sender auto coloring option
52   _senderAutoColor = s.value("Colors/SenderAutoColor", false).toBool();
53
54   // Now initialize the mapping between FormatCodes and FormatTypes...
55   _formatCodes["%O"] = None;
56   _formatCodes["%B"] = Bold;
57   _formatCodes["%S"] = Italic;
58   _formatCodes["%U"] = Underline;
59   _formatCodes["%R"] = Reverse;
60
61   _formatCodes["%D0"] = PlainMsg;
62   _formatCodes["%Dn"] = NoticeMsg;
63   _formatCodes["%Ds"] = ServerMsg;
64   _formatCodes["%De"] = ErrorMsg;
65   _formatCodes["%Dj"] = JoinMsg;
66   _formatCodes["%Dp"] = PartMsg;
67   _formatCodes["%Dq"] = QuitMsg;
68   _formatCodes["%Dk"] = KickMsg;
69   _formatCodes["%Dr"] = RenameMsg;
70   _formatCodes["%Dm"] = ModeMsg;
71   _formatCodes["%Da"] = ActionMsg;
72
73   _formatCodes["%DT"] = Timestamp;
74   _formatCodes["%DS"] = Sender;
75   _formatCodes["%DN"] = Nick;
76   _formatCodes["%DH"] = Hostmask;
77   _formatCodes["%DC"] = ChannelName;
78   _formatCodes["%DM"] = ModeFlags;
79   _formatCodes["%DU"] = Url;
80
81   // Initialize color codes according to mIRC "standard"
82   QStringList colors;
83   //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
84   //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
85   colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
86   colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
87
88   // Set color formats
89   for(int i = 0; i < 16; i++) {
90     QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
91     _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
92     _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
93     QTextCharFormat fgf, bgf;
94     fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
95     bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
96   }
97
98   // Set a few more standard formats
99   QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
100   setFormat(Bold, bold, Settings::Default);
101
102   QTextCharFormat italic; italic.setFontItalic(true);
103   setFormat(Italic, italic, Settings::Default);
104
105   QTextCharFormat underline; underline.setFontUnderline(true);
106   setFormat(Underline, underline, Settings::Default);
107
108   // All other formats should be defined in derived classes.
109 }
110
111 UiStyle::~ UiStyle() {
112   qDeleteAll(_cachedFontMetrics);
113 }
114
115 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
116   if(mode == Settings::Default) {
117     _defaultFormats[ftype] = fmt;
118   } else {
119     UiStyleSettings s(_settingsKey);
120     if(fmt != _defaultFormats[ftype]) {
121       _customFormats[ftype] = fmt;
122       s.setCustomFormat(ftype, fmt);
123     } else {
124       _customFormats.remove(ftype);
125       s.removeCustomFormat(ftype);
126     }
127   }
128   // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
129   _cachedFormats.clear();
130   _cachedFontMetrics.clear();
131 }
132
133 void UiStyle::setSenderAutoColor( bool state ) {
134   _senderAutoColor = state;
135   UiStyleSettings s(_settingsKey);
136   s.setValue("Colors/SenderAutoColor", QVariant(state));
137 }
138
139 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
140   // Check for enabled sender auto coloring
141   if ( (ftype & 0x00000fff) == Sender && !_senderAutoColor ) {
142     // Just use the default sender style if auto coloring is disabled FIXME
143     ftype = Sender;
144   }
145
146   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
147   else return _defaultFormats.value(ftype, QTextCharFormat());
148 }
149
150 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
151 //       until you _really_ know what you do!
152 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
153   if(ftype == Invalid)
154     return QTextCharFormat();
155   if(_cachedFormats.contains(ftype))
156     return _cachedFormats.value(ftype);
157
158   QTextCharFormat fmt;
159
160   // Check if we have a special message format stored already sans color codes
161   if(_cachedFormats.contains(ftype & 0x1fffff))
162     fmt = _cachedFormats.value(ftype &0x1fffff);
163   else {
164     // Nope, so we have to construct it...
165     // We assume that we don't mix mirc format codes and component codes, so at this point we know that it's either
166     // a stock (not stylesheeted) component, or mirc formats
167     // In both cases, we start off with the basic format for this message type and then merge the extra stuff
168
169     // Check if we at least already have something stored for the message type first
170     if(_cachedFormats.contains(ftype & 0xf))
171       fmt = _cachedFormats.value(ftype & 0xf);
172     else {
173       // Not being in the cache means it hasn't been preset via stylesheet (or used before)
174       // We might still have set something in code as a fallback, so merge
175       fmt = format(None);
176       fmt.merge(format((FormatType)(ftype & 0x0f)));
177       // This can be cached
178       _cachedFormats[ftype & 0x0f] = fmt;
179     }
180     // OK, at this point we have the message type format - now merge the rest
181     if((ftype & 0xf0)) { // mirc format
182       for(quint32 mask = 0x10; mask <= 0x80; mask <<= 1) {
183         if(!(ftype & mask))
184           continue;
185         // We need to check for overrides in the cache
186         if(_cachedFormats.contains(mask | (ftype & 0x0f)))
187           fmt.merge(_cachedFormats.value(mask | (ftype & 0x0f)));
188         else if(_cachedFormats.contains(mask))
189           fmt.merge(_cachedFormats.value(mask));
190         else // nothing in cache, use stock format
191           fmt.merge(format((FormatType)mask));
192       }
193     } else { // component
194       // We've already checked the cache for the combo of msgtype and component and failed,
195       // so we check if we defined a general format and merge this, or the stock format else
196       if(_cachedFormats.contains(ftype & 0xff00))
197         fmt.merge(_cachedFormats.value(ftype & 0xff00));
198       else
199         fmt.merge(format((FormatType)(ftype & 0xff00)));
200     }
201   }
202
203   // Now we handle color codes. We assume that those can't be combined with components
204   if(ftype & 0x00400000)
205     fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
206   if(ftype & 0x00800000)
207     fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
208
209   // Sender auto colors
210   if(_senderAutoColor && (ftype & 0x200) && (ftype & 0xff000200) != 0x200) {
211     if(_cachedFormats.contains(ftype & 0xff00020f))
212       fmt.merge(_cachedFormats.value(ftype & 0xff00020f));
213     else if(_cachedFormats.contains(ftype & 0xff000200))
214       fmt.merge(_cachedFormats.value(ftype & 0xff000200));
215     else
216       fmt.merge(format((FormatType)(ftype & 0xff000200)));
217   }
218
219   // URL
220   if(ftype & Url)
221     fmt.merge(format(Url)); // TODO handle this properly
222
223   return _cachedFormats[ftype] = fmt;
224 }
225
226 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
227   // QFontMetricsF is not assignable, so we need to store pointers :/
228   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
229   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
230 }
231
232 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
233   if(_formatCodes.contains(code)) return _formatCodes.value(code);
234   return Invalid;
235 }
236
237 QString UiStyle::formatCode(FormatType ftype) const {
238   return _formatCodes.key(ftype);
239 }
240
241 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
242   QList<QTextLayout::FormatRange> formatRanges;
243   QTextLayout::FormatRange range;
244   int i = 0;
245   for(i = 0; i < formatList.count(); i++) {
246     range.format = mergedFormat(formatList.at(i).second);
247     range.start = formatList.at(i).first;
248     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
249     formatRanges.append(range);
250   }
251   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
252   return formatRanges;
253 }
254
255 // This method expects a well-formatted string, there is no error checking!
256 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
257 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
258   QString s = s_;
259   if(s.length() > 65535) {
260     qWarning() << QString("String too long to be styled: %1").arg(s);
261     return StyledString();
262   }
263   StyledString result;
264   result.formatList.append(qMakePair((quint16)0, (quint32)None));
265   quint32 curfmt = (quint32)None;
266   int pos = 0; quint16 length = 0;
267   for(;;) {
268     pos = s.indexOf('%', pos);
269     if(pos < 0) break;
270     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
271       s.remove(pos, 1);
272       pos++;
273       continue;
274     }
275     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
276       if(s[pos+3] == '-') {  // color off
277         curfmt &= 0x003fffff;
278         length = 4;
279       } else {
280         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
281         //TODO: use 99 as transparent color (re mirc color "standard")
282         color &= 0x0f;
283         if(s[pos+3] == 'f') {
284           curfmt &= 0xf0ffffff;
285           curfmt |= (color << 24) | 0x00400000;
286         } else {
287           curfmt &= 0x0fffffff;
288           curfmt |= (color << 28) | 0x00800000;
289         }
290         length = 6;
291       }
292     } else if(s[pos+1] == 'O') { // reset formatting
293       curfmt &= 0x0000000f; // we keep message type-specific formatting
294       length = 2;
295     } else if(s[pos+1] == 'R') { // reverse
296       // TODO: implement reverse formatting
297
298       length = 2;
299     } else { // all others are toggles
300       QString code = QString("%") + s[pos+1];
301       if(s[pos+1] == 'D') code += s[pos+2];
302       FormatType ftype = formatType(code);
303       if(ftype == Invalid) {
304         qWarning() << (QString("Invalid format code in string: %1").arg(s));
305         continue;
306       }
307       curfmt ^= ftype;
308       length = code.length();
309     }
310     s.remove(pos, length);
311     if(pos == result.formatList.last().first)
312       result.formatList.last().second = curfmt;
313     else
314       result.formatList.append(qMakePair((quint16)pos, curfmt));
315   }
316   result.plainText = s;
317   return result;
318 }
319
320 QString UiStyle::mircToInternal(const QString &mirc_) const {
321   QString mirc = mirc_;
322   mirc.replace('%', "%%");      // escape % just to be sure
323   mirc.replace('\x02', "%B");
324   mirc.replace('\x0f', "%O");
325   mirc.replace('\x12', "%R");
326   mirc.replace('\x16', "%R");
327   mirc.replace('\x1d', "%S");
328   mirc.replace('\x1f', "%U");
329
330   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
331   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
332   // %Dc- turns color off.
333   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
334   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
335   int pos = 0;
336   for(;;) {
337     pos = mirc.indexOf('\x03', pos);
338     if(pos < 0) break; // no more mirc color codes
339     QString ins, num;
340     int l = mirc.length();
341     int i = pos + 1;
342     // check for fg color
343     if(i < l && mirc[i].isDigit()) {
344       num = mirc[i++];
345       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
346       else num.prepend('0');
347       ins = QString("%Dcf%1").arg(num);
348
349       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
350         i++;
351         num = mirc[i++];
352         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
353         else num.prepend('0');
354         ins += QString("%Dcb%1").arg(num);
355       }
356     } else {
357       ins = "%Dc-";
358     }
359     mirc.replace(pos, i-pos, ins);
360   }
361   return mirc;
362 }
363
364 /***********************************************************************************/
365 UiStyle::StyledMessage::StyledMessage(const Message &msg)
366   : Message(msg)
367 {
368 }
369
370 void UiStyle::StyledMessage::style(UiStyle *style) const {
371   QString user = userFromMask(sender());
372   QString host = hostFromMask(sender());
373   QString nick = nickFromMask(sender());
374   QString txt = style->mircToInternal(contents());
375   QString bufferName = bufferInfo().bufferName();
376   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
377
378   QString t;
379   switch(type()) {
380     case Message::Plain:
381       t = tr("%D0%1").arg(txt); break;
382     case Message::Notice:
383       t = tr("%Dn%1").arg(txt); break;
384     case Message::Topic:
385     case Message::Server:
386       t = tr("%Ds%1").arg(txt); break;
387     case Message::Error:
388       t = tr("%De%1").arg(txt); break;
389     case Message::Join:
390       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
391     case Message::Part:
392       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
393       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
394       break;
395     case Message::Quit:
396       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
397       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
398       break;
399     case Message::Kick: {
400         QString victim = txt.section(" ", 0, 0);
401         QString kickmsg = txt.section(" ", 1);
402         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
403         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
404       }
405       break;
406     case Message::Nick:
407       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
408       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
409       break;
410     case Message::Mode:
411       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
412       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
413       break;
414     case Message::Action:
415       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
416       break;
417     default:
418       t = tr("%De[%1]").arg(txt);
419   }
420   _contents = style->styleString(t);
421 }
422
423 QString UiStyle::StyledMessage::decoratedTimestamp() const {
424   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
425 }
426
427 QString UiStyle::StyledMessage::plainSender() const {
428   switch(type()) {
429     case Message::Plain:
430     case Message::Notice:
431       return nickFromMask(sender());
432     default:
433       return QString();
434   }
435 }
436
437 QString UiStyle::StyledMessage::decoratedSender() const {
438   switch(type()) {
439     case Message::Plain:
440       return tr("<%1>").arg(plainSender()); break;
441     case Message::Notice:
442       return tr("[%1]").arg(plainSender()); break;
443     case Message::Topic:
444     case Message::Server:
445       return tr("*"); break;
446     case Message::Error:
447       return tr("*"); break;
448     case Message::Join:
449       return tr("-->"); break;
450     case Message::Part:
451       return tr("<--"); break;
452     case Message::Quit:
453       return tr("<--"); break;
454     case Message::Kick:
455       return tr("<-*"); break;
456     case Message::Nick:
457       return tr("<->"); break;
458     case Message::Mode:
459       return tr("***"); break;
460     case Message::Action:
461       return tr("-*-"); break;
462     default:
463       return tr("%1").arg(plainSender());
464   }
465 }
466
467 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
468   switch(type()) {
469     case Message::Plain:
470       // To produce random like but stable nick colorings some sort of hashing should work best.
471       // In this case we just use the qt function qChecksum which produces a
472       // CRC16 hash. This should be fast and 16 bits are more than enough.
473       {
474         QString nick = nickFromMask(sender()).toLower();
475         if(!nick.isEmpty()) {
476           int chopCount = 0;
477           while(nick[nick.count() - 1 - chopCount] == '_') {
478             chopCount++;
479           }
480           nick.chop(chopCount);
481         }
482         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
483         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
484       }
485     case Message::Notice:
486       return UiStyle::NoticeMsg; break;
487     case Message::Topic:
488     case Message::Server:
489       return UiStyle::ServerMsg; break;
490     case Message::Error:
491       return UiStyle::ErrorMsg; break;
492     case Message::Join:
493       return UiStyle::JoinMsg; break;
494     case Message::Part:
495       return UiStyle::PartMsg; break;
496     case Message::Quit:
497       return UiStyle::QuitMsg; break;
498     case Message::Kick:
499       return UiStyle::KickMsg; break;
500     case Message::Nick:
501       return UiStyle::RenameMsg; break;
502     case Message::Mode:
503       return UiStyle::ModeMsg; break;
504     case Message::Action:
505       return UiStyle::ActionMsg; break;
506     default:
507       return UiStyle::ErrorMsg;
508   }
509 }
510
511
512 /***********************************************************************************/
513
514 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
515   out << formatList.count();
516   UiStyle::FormatList::const_iterator it = formatList.begin();
517   while(it != formatList.end()) {
518     out << (*it).first << (*it).second;
519     ++it;
520   }
521   return out;
522 }
523
524 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
525   quint16 cnt;
526   in >> cnt;
527   for(quint16 i = 0; i < cnt; i++) {
528     quint16 pos; quint32 ftype;
529     in >> pos >> ftype;
530     formatList.append(qMakePair((quint16)pos, ftype));
531   }
532   return in;
533 }