Well, if we check for a settings version, maybe we should set it too...
[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 // FIXME remove with migration code
28 #include <QSettings>
29
30 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
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   // FIXME remove migration at some point
40   // We remove old settings if we find them, since they conflict
41 #ifdef Q_WS_MAC
42   QSettings mys(QCoreApplication::organizationDomain(), Quassel::buildInfo().clientApplicationName);
43 #else
44   QSettings mys(QCoreApplication::organizationName(), Quassel::buildInfo().clientApplicationName);
45 #endif
46   mys.beginGroup("QtUi");
47   if(mys.childGroups().contains("Colors")) {
48     qDebug() << "Removing obsolete UiStyle settings!";
49     mys.endGroup();
50     mys.remove("Ui");
51     mys.remove("QtUiStyle");
52     mys.remove("QtUiStyleNew");
53     mys.remove("QtUi/Colors");
54     mys.sync();
55   }
56
57   _defaultFont = QFont("Monospace", QApplication::font().pointSize());
58
59   // Default format
60   _defaultPlainFormat.setForeground(QBrush("#000000"));
61   _defaultPlainFormat.setFont(_defaultFont);
62   _defaultPlainFormat.font().setFixedPitch(true);
63   _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
64   setFormat(None, _defaultPlainFormat, Settings::Default);
65
66   // Load saved custom formats
67   UiStyleSettings s(_settingsKey);
68   foreach(FormatType type, s.availableFormats()) {
69     _customFormats[type] = s.customFormat(type);
70   }
71
72   // Now initialize the mapping between FormatCodes and FormatTypes...
73   _formatCodes["%O"] = None;
74   _formatCodes["%B"] = Bold;
75   _formatCodes["%S"] = Italic;
76   _formatCodes["%U"] = Underline;
77   _formatCodes["%R"] = Reverse;
78
79   _formatCodes["%D0"] = PlainMsg;
80   _formatCodes["%Dn"] = NoticeMsg;
81   _formatCodes["%Ds"] = ServerMsg;
82   _formatCodes["%De"] = ErrorMsg;
83   _formatCodes["%Dj"] = JoinMsg;
84   _formatCodes["%Dp"] = PartMsg;
85   _formatCodes["%Dq"] = QuitMsg;
86   _formatCodes["%Dk"] = KickMsg;
87   _formatCodes["%Dr"] = RenameMsg;
88   _formatCodes["%Dm"] = ModeMsg;
89   _formatCodes["%Da"] = ActionMsg;
90
91   _formatCodes["%DT"] = Timestamp;
92   _formatCodes["%DS"] = Sender;
93   _formatCodes["%DN"] = Nick;
94   _formatCodes["%DH"] = Hostmask;
95   _formatCodes["%DC"] = ChannelName;
96   _formatCodes["%DM"] = ModeFlags;
97   _formatCodes["%DU"] = Url;
98
99   // Initialize color codes according to mIRC "standard"
100   QStringList colors;
101   //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
102   //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
103   colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
104   colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
105
106   // Set color formats
107   for(int i = 0; i < 16; i++) {
108     QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
109     _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
110     _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
111     QTextCharFormat fgf, bgf;
112     fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
113     bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
114   }
115
116   // Set a few more standard formats
117   QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
118   setFormat(Bold, bold, Settings::Default);
119
120   QTextCharFormat italic; italic.setFontItalic(true);
121   setFormat(Italic, italic, Settings::Default);
122
123   QTextCharFormat underline; underline.setFontUnderline(true);
124   setFormat(Underline, underline, Settings::Default);
125
126   // All other formats should be defined in derived classes.
127 }
128
129 UiStyle::~ UiStyle() {
130   qDeleteAll(_cachedFontMetrics);
131 }
132
133 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
134   if(mode == Settings::Default) {
135     _defaultFormats[ftype] = fmt;
136   } else {
137     UiStyleSettings s(_settingsKey);
138     if(fmt != _defaultFormats[ftype]) {
139       _customFormats[ftype] = fmt;
140       s.setCustomFormat(ftype, fmt);
141     } else {
142       _customFormats.remove(ftype);
143       s.removeCustomFormat(ftype);
144     }
145   }
146   // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
147   _cachedFormats.clear();
148   _cachedFontMetrics.clear();
149 }
150
151 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
152   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
153   else return _defaultFormats.value(ftype, QTextCharFormat());
154 }
155
156 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
157 //       until you _really_ know what you do!
158 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
159   if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
160   if(ftype == Invalid) return QTextCharFormat();
161   // Now we construct the merged format, starting with the default
162   QTextCharFormat fmt = format(None);
163   // First: general message format
164   fmt.merge(format((FormatType)(ftype & 0x0f)));
165   // now more specific ones
166   for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
167     if(ftype & mask) fmt.merge(format((FormatType)mask));
168   }
169   // color codes!
170   if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
171   if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
172   // URL
173   if(ftype & Url) fmt.merge(format(Url));
174   return _cachedFormats[ftype] = fmt;
175 }
176
177 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
178   // QFontMetricsF is not assignable, so we need to store pointers :/
179   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
180   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
181 }
182
183 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
184   if(_formatCodes.contains(code)) return _formatCodes.value(code);
185   return Invalid;
186 }
187
188 QString UiStyle::formatCode(FormatType ftype) const {
189   return _formatCodes.key(ftype);
190 }
191
192 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
193   QList<QTextLayout::FormatRange> formatRanges;
194   QTextLayout::FormatRange range;
195   int i = 0;
196   for(i = 0; i < formatList.count(); i++) {
197     range.format = mergedFormat(formatList.at(i).second);
198     range.start = formatList.at(i).first;
199     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
200     formatRanges.append(range);
201   }
202   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
203   return formatRanges;
204 }
205
206 // This method expects a well-formatted string, there is no error checking!
207 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
208 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
209   QString s = s_;
210   if(s.length() > 65535) {
211     qWarning() << QString("String too long to be styled: %1").arg(s);
212     return StyledString();
213   }
214   StyledString result;
215   result.formatList.append(qMakePair((quint16)0, (quint32)None));
216   quint32 curfmt = (quint32)None;
217   int pos = 0; quint16 length = 0;
218   for(;;) {
219     pos = s.indexOf('%', pos);
220     if(pos < 0) break;
221     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
222       s.remove(pos, 1);
223       pos++;
224       continue;
225     }
226     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
227       if(s[pos+3] == '-') {  // color off
228         curfmt &= 0x003fffff;
229         length = 4;
230       } else {
231         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
232         //TODO: use 99 as transparent color (re mirc color "standard")
233         color &= 0x0f;
234         if(s[pos+3] == 'f') {
235           curfmt &= 0xf0ffffff;
236           curfmt |= (color << 24) | 0x00400000;
237         } else {
238           curfmt &= 0x0fffffff;
239           curfmt |= (color << 28) | 0x00800000;
240         }
241         length = 6;
242       }
243     } else if(s[pos+1] == 'O') { // reset formatting
244       curfmt &= 0x0000000f; // we keep message type-specific formatting
245       length = 2;
246     } else if(s[pos+1] == 'R') { // reverse
247       // TODO: implement reverse formatting
248
249       length = 2;
250     } else { // all others are toggles
251       QString code = QString("%") + s[pos+1];
252       if(s[pos+1] == 'D') code += s[pos+2];
253       FormatType ftype = formatType(code);
254       if(ftype == Invalid) {
255         qWarning() << (QString("Invalid format code in string: %1").arg(s));
256         continue;
257       }
258       curfmt ^= ftype;
259       length = code.length();
260     }
261     s.remove(pos, length);
262     if(pos == result.formatList.last().first)
263       result.formatList.last().second = curfmt;
264     else
265       result.formatList.append(qMakePair((quint16)pos, curfmt));
266   }
267   result.plainText = s;
268   return result;
269 }
270
271 QString UiStyle::mircToInternal(const QString &mirc_) const {
272   QString mirc = mirc_;
273   mirc.replace('%', "%%");      // escape % just to be sure
274   mirc.replace('\x02', "%B");
275   mirc.replace('\x0f', "%O");
276   mirc.replace('\x12', "%R");
277   mirc.replace('\x16', "%R");
278   mirc.replace('\x1d', "%S");
279   mirc.replace('\x1f', "%U");
280
281   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
282   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
283   // %Dc- turns color off.
284   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
285   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
286   int pos = 0;
287   for(;;) {
288     pos = mirc.indexOf('\x03', pos);
289     if(pos < 0) break; // no more mirc color codes
290     QString ins, num;
291     int l = mirc.length();
292     int i = pos + 1;
293     // check for fg color
294     if(i < l && mirc[i].isDigit()) {
295       num = mirc[i++];
296       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
297       else num.prepend('0');
298       ins = QString("%Dcf%1").arg(num);
299
300       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
301         i++;
302         num = mirc[i++];
303         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
304         else num.prepend('0');
305         ins += QString("%Dcb%1").arg(num);
306       }
307     } else {
308       ins = "%Dc-";
309     }
310     mirc.replace(pos, i-pos, ins);
311   }
312   return mirc;
313 }
314
315 /***********************************************************************************/
316 UiStyle::StyledMessage::StyledMessage(const Message &msg)
317   : Message(msg)
318 {
319 }
320
321 void UiStyle::StyledMessage::style(UiStyle *style) const {
322   QString user = userFromMask(sender());
323   QString host = hostFromMask(sender());
324   QString nick = nickFromMask(sender());
325   QString txt = style->mircToInternal(contents());
326   QString bufferName = bufferInfo().bufferName();
327   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
328
329   QString t;
330   switch(type()) {
331     case Message::Plain:
332       t = tr("%D0%1").arg(txt); break;
333     case Message::Notice:
334       t = tr("%Dn%1").arg(txt); break;
335     case Message::Server:
336       t = tr("%Ds%1").arg(txt); break;
337     case Message::Error:
338       t = tr("%De%1").arg(txt); break;
339     case Message::Join:
340       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
341     case Message::Part:
342       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
343       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
344       break;
345     case Message::Quit:
346       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
347       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
348       break;
349     case Message::Kick: {
350         QString victim = txt.section(" ", 0, 0);
351         QString kickmsg = txt.section(" ", 1);
352         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
353         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
354       }
355       break;
356     case Message::Nick:
357       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
358       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
359       break;
360     case Message::Mode:
361       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
362       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
363       break;
364     case Message::Action:
365       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
366       break;
367     default:
368       t = tr("%De[%1]").arg(txt);
369   }
370   _contents = style->styleString(t);
371 }
372
373 QString UiStyle::StyledMessage::decoratedTimestamp() const {
374   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
375 }
376
377 QString UiStyle::StyledMessage::plainSender() const {
378   switch(type()) {
379     case Message::Plain:
380     case Message::Notice:
381       return nickFromMask(sender());
382     default:
383       return QString();
384   }
385 }
386
387 QString UiStyle::StyledMessage::decoratedSender() const {
388   switch(type()) {
389     case Message::Plain:
390       return tr("<%1>").arg(plainSender()); break;
391     case Message::Notice:
392       return tr("[%1]").arg(plainSender()); break;
393     case Message::Server:
394       return tr("*"); break;
395     case Message::Error:
396       return tr("*"); break;
397     case Message::Join:
398       return tr("-->"); break;
399     case Message::Part:
400       return tr("<--"); break;
401     case Message::Quit:
402       return tr("<--"); break;
403     case Message::Kick:
404       return tr("<-*"); break;
405     case Message::Nick:
406       return tr("<->"); break;
407     case Message::Mode:
408       return tr("***"); break;
409     case Message::Action:
410       return tr("-*-"); break;
411     default:
412       return tr("%1").arg(plainSender());
413   }
414 }
415
416 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
417   switch(type()) {
418     case Message::Plain:
419       return UiStyle::Sender; break;
420     case Message::Notice:
421       return UiStyle::NoticeMsg; break;
422     case Message::Server:
423       return UiStyle::ServerMsg; break;
424     case Message::Error:
425       return UiStyle::ErrorMsg; break;
426     case Message::Join:
427       return UiStyle::JoinMsg; break;
428     case Message::Part:
429       return UiStyle::PartMsg; break;
430     case Message::Quit:
431       return UiStyle::QuitMsg; break;
432     case Message::Kick:
433       return UiStyle::KickMsg; break;
434     case Message::Nick:
435       return UiStyle::RenameMsg; break;
436     case Message::Mode:
437       return UiStyle::ModeMsg; break;
438     case Message::Action:
439       return UiStyle::ActionMsg; break;
440     default:
441       return UiStyle::ErrorMsg;
442   }
443 }
444
445
446 /***********************************************************************************/
447
448 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
449   out << formatList.count();
450   UiStyle::FormatList::const_iterator it = formatList.begin();
451   while(it != formatList.end()) {
452     out << (*it).first << (*it).second;
453     ++it;
454   }
455   return out;
456 }
457
458 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
459   quint16 cnt;
460   in >> cnt;
461   for(quint16 i = 0; i < cnt; i++) {
462     quint16 pos; quint32 ftype;
463     in >> pos >> ftype;
464     formatList.append(qMakePair((quint16)pos, ftype));
465   }
466   return in;
467 }