Fixes #572 - changes to nick coloring
[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
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(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
154   if(ftype == Invalid) return QTextCharFormat();
155   // Now we construct the merged format, starting with the default
156   QTextCharFormat fmt = format(None);
157   // First: general message format
158   fmt.merge(format((FormatType)(ftype & 0x0f)));
159   // now more specific ones
160   for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
161     if(ftype & mask) fmt.merge(format((FormatType)mask));
162   }
163   // color codes!
164   if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
165   if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
166   // Sender auto colors
167   if((ftype & 0xfff) == 0x200 && (ftype & 0xff000200) != 0x200) fmt.merge(format((FormatType)(ftype & 0xff000200)));
168   // URL
169   if(ftype & Url) fmt.merge(format(Url));
170   return _cachedFormats[ftype] = fmt;
171 }
172
173 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
174   // QFontMetricsF is not assignable, so we need to store pointers :/
175   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
176   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
177 }
178
179 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
180   if(_formatCodes.contains(code)) return _formatCodes.value(code);
181   return Invalid;
182 }
183
184 QString UiStyle::formatCode(FormatType ftype) const {
185   return _formatCodes.key(ftype);
186 }
187
188 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
189   QList<QTextLayout::FormatRange> formatRanges;
190   QTextLayout::FormatRange range;
191   int i = 0;
192   for(i = 0; i < formatList.count(); i++) {
193     range.format = mergedFormat(formatList.at(i).second);
194     range.start = formatList.at(i).first;
195     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
196     formatRanges.append(range);
197   }
198   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
199   return formatRanges;
200 }
201
202 // This method expects a well-formatted string, there is no error checking!
203 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
204 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
205   QString s = s_;
206   if(s.length() > 65535) {
207     qWarning() << QString("String too long to be styled: %1").arg(s);
208     return StyledString();
209   }
210   StyledString result;
211   result.formatList.append(qMakePair((quint16)0, (quint32)None));
212   quint32 curfmt = (quint32)None;
213   int pos = 0; quint16 length = 0;
214   for(;;) {
215     pos = s.indexOf('%', pos);
216     if(pos < 0) break;
217     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
218       s.remove(pos, 1);
219       pos++;
220       continue;
221     }
222     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
223       if(s[pos+3] == '-') {  // color off
224         curfmt &= 0x003fffff;
225         length = 4;
226       } else {
227         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
228         //TODO: use 99 as transparent color (re mirc color "standard")
229         color &= 0x0f;
230         if(s[pos+3] == 'f') {
231           curfmt &= 0xf0ffffff;
232           curfmt |= (color << 24) | 0x00400000;
233         } else {
234           curfmt &= 0x0fffffff;
235           curfmt |= (color << 28) | 0x00800000;
236         }
237         length = 6;
238       }
239     } else if(s[pos+1] == 'O') { // reset formatting
240       curfmt &= 0x0000000f; // we keep message type-specific formatting
241       length = 2;
242     } else if(s[pos+1] == 'R') { // reverse
243       // TODO: implement reverse formatting
244
245       length = 2;
246     } else { // all others are toggles
247       QString code = QString("%") + s[pos+1];
248       if(s[pos+1] == 'D') code += s[pos+2];
249       FormatType ftype = formatType(code);
250       if(ftype == Invalid) {
251         qWarning() << (QString("Invalid format code in string: %1").arg(s));
252         continue;
253       }
254       curfmt ^= ftype;
255       length = code.length();
256     }
257     s.remove(pos, length);
258     if(pos == result.formatList.last().first)
259       result.formatList.last().second = curfmt;
260     else
261       result.formatList.append(qMakePair((quint16)pos, curfmt));
262   }
263   result.plainText = s;
264   return result;
265 }
266
267 QString UiStyle::mircToInternal(const QString &mirc_) const {
268   QString mirc = mirc_;
269   mirc.replace('%', "%%");      // escape % just to be sure
270   mirc.replace('\x02', "%B");
271   mirc.replace('\x0f', "%O");
272   mirc.replace('\x12', "%R");
273   mirc.replace('\x16', "%R");
274   mirc.replace('\x1d', "%S");
275   mirc.replace('\x1f', "%U");
276
277   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
278   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
279   // %Dc- turns color off.
280   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
281   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
282   int pos = 0;
283   for(;;) {
284     pos = mirc.indexOf('\x03', pos);
285     if(pos < 0) break; // no more mirc color codes
286     QString ins, num;
287     int l = mirc.length();
288     int i = pos + 1;
289     // check for fg color
290     if(i < l && mirc[i].isDigit()) {
291       num = mirc[i++];
292       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
293       else num.prepend('0');
294       ins = QString("%Dcf%1").arg(num);
295
296       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
297         i++;
298         num = mirc[i++];
299         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
300         else num.prepend('0');
301         ins += QString("%Dcb%1").arg(num);
302       }
303     } else {
304       ins = "%Dc-";
305     }
306     mirc.replace(pos, i-pos, ins);
307   }
308   return mirc;
309 }
310
311 /***********************************************************************************/
312 UiStyle::StyledMessage::StyledMessage(const Message &msg)
313   : Message(msg)
314 {
315 }
316
317 void UiStyle::StyledMessage::style(UiStyle *style) const {
318   QString user = userFromMask(sender());
319   QString host = hostFromMask(sender());
320   QString nick = nickFromMask(sender());
321   QString txt = style->mircToInternal(contents());
322   QString bufferName = bufferInfo().bufferName();
323   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
324
325   QString t;
326   switch(type()) {
327     case Message::Plain:
328       t = tr("%D0%1").arg(txt); break;
329     case Message::Notice:
330       t = tr("%Dn%1").arg(txt); break;
331     case Message::Server:
332       t = tr("%Ds%1").arg(txt); break;
333     case Message::Error:
334       t = tr("%De%1").arg(txt); break;
335     case Message::Join:
336       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
337     case Message::Part:
338       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
339       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
340       break;
341     case Message::Quit:
342       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
343       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
344       break;
345     case Message::Kick: {
346         QString victim = txt.section(" ", 0, 0);
347         QString kickmsg = txt.section(" ", 1);
348         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
349         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
350       }
351       break;
352     case Message::Nick:
353       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
354       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
355       break;
356     case Message::Mode:
357       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
358       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
359       break;
360     case Message::Action:
361       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
362       break;
363     default:
364       t = tr("%De[%1]").arg(txt);
365   }
366   _contents = style->styleString(t);
367 }
368
369 QString UiStyle::StyledMessage::decoratedTimestamp() const {
370   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
371 }
372
373 QString UiStyle::StyledMessage::plainSender() const {
374   switch(type()) {
375     case Message::Plain:
376     case Message::Notice:
377       return nickFromMask(sender());
378     default:
379       return QString();
380   }
381 }
382
383 QString UiStyle::StyledMessage::decoratedSender() const {
384   switch(type()) {
385     case Message::Plain:
386       return tr("<%1>").arg(plainSender()); break;
387     case Message::Notice:
388       return tr("[%1]").arg(plainSender()); break;
389     case Message::Server:
390       return tr("*"); break;
391     case Message::Error:
392       return tr("*"); break;
393     case Message::Join:
394       return tr("-->"); break;
395     case Message::Part:
396       return tr("<--"); break;
397     case Message::Quit:
398       return tr("<--"); break;
399     case Message::Kick:
400       return tr("<-*"); break;
401     case Message::Nick:
402       return tr("<->"); break;
403     case Message::Mode:
404       return tr("***"); break;
405     case Message::Action:
406       return tr("-*-"); break;
407     default:
408       return tr("%1").arg(plainSender());
409   }
410 }
411
412 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
413   switch(type()) {
414     case Message::Plain:
415       // To produce random like but stable nick colorings some sort of hashing should work best.
416       // In this case we just use the qt function qChecksum which produces a
417       // CRC16 hash. This should be fast and 16 bits are more than enough.
418       {
419         QString nick = nickFromMask(sender()).toLower();
420         if(!nick.isEmpty()) {
421           int chopCount = 0;
422           while(nick[nick.count() - 1 - chopCount] == '_') {
423             chopCount++;
424           }
425           nick.chop(chopCount);
426         }
427         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
428         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
429       }
430     case Message::Notice:
431       return UiStyle::NoticeMsg; break;
432     case Message::Server:
433       return UiStyle::ServerMsg; break;
434     case Message::Error:
435       return UiStyle::ErrorMsg; break;
436     case Message::Join:
437       return UiStyle::JoinMsg; break;
438     case Message::Part:
439       return UiStyle::PartMsg; break;
440     case Message::Quit:
441       return UiStyle::QuitMsg; break;
442     case Message::Kick:
443       return UiStyle::KickMsg; break;
444     case Message::Nick:
445       return UiStyle::RenameMsg; break;
446     case Message::Mode:
447       return UiStyle::ModeMsg; break;
448     case Message::Action:
449       return UiStyle::ActionMsg; break;
450     default:
451       return UiStyle::ErrorMsg;
452   }
453 }
454
455
456 /***********************************************************************************/
457
458 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
459   out << formatList.count();
460   UiStyle::FormatList::const_iterator it = formatList.begin();
461   while(it != formatList.end()) {
462     out << (*it).first << (*it).second;
463     ++it;
464   }
465   return out;
466 }
467
468 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
469   quint16 cnt;
470   in >> cnt;
471   for(quint16 i = 0; i < cnt; i++) {
472     quint16 pos; quint32 ftype;
473     in >> pos >> ftype;
474     formatList.append(qMakePair((quint16)pos, ftype));
475   }
476   return in;
477 }