Add migration code that removes obsolete style settings
[quassel.git] / src / uisupport / uistyle.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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 "uistyle.h"
23 #include "uistylesettings.h"
24 #include "util.h"
25
26 // FIXME remove with migration code
27 #include <QSettings>
28 #include "global.h"
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(), Global::clientApplicationName);
43 #else
44   QSettings mys(QCoreApplication::organizationName(), Global::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 }
149
150 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
151   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
152   else return _defaultFormats.value(ftype, QTextCharFormat());
153 }
154
155 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
156 //       until you _really_ know what you do!
157 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
158   if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
159   if(ftype == Invalid) return QTextCharFormat();
160   // Now we construct the merged format, starting with the default
161   QTextCharFormat fmt = format(None);
162   // First: general message format
163   fmt.merge(format((FormatType)(ftype & 0x0f)));
164   // now more specific ones
165   for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
166     if(ftype & mask) fmt.merge(format((FormatType)mask));
167   }
168   // color codes!
169   if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
170   if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
171   // URL
172   if(ftype & Url) fmt.merge(format(Url));
173   return _cachedFormats[ftype] = fmt;
174 }
175
176 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
177   // QFontMetricsF is not assignable, so we need to store pointers :/
178   if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
179   return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
180 }
181
182 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
183   if(_formatCodes.contains(code)) return _formatCodes.value(code);
184   return Invalid;
185 }
186
187 QString UiStyle::formatCode(FormatType ftype) const {
188   return _formatCodes.key(ftype);
189 }
190
191 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
192   QList<QTextLayout::FormatRange> formatRanges;
193   QTextLayout::FormatRange range;
194   int i = 0;
195   for(i = 0; i < formatList.count(); i++) {
196     range.format = mergedFormat(formatList.at(i).second);
197     range.start = formatList.at(i).first;
198     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
199     formatRanges.append(range);
200   }
201   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
202   return formatRanges;
203 }
204
205 // This method expects a well-formatted string, there is no error checking!
206 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
207 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
208   QString s = s_;
209   if(s.length() > 65535) {
210     qWarning() << QString("String too long to be styled: %1").arg(s);
211     return StyledString();
212   }
213   StyledString result;
214   result.formatList.append(qMakePair((quint16)0, (quint32)None));
215   quint32 curfmt = (quint32)None;
216   int pos = 0; quint16 length = 0;
217   for(;;) {
218     pos = s.indexOf('%', pos);
219     if(pos < 0) break;
220     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
221       s.remove(pos, 1);
222       pos++;
223       continue;
224     }
225     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
226       if(s[pos+3] == '-') {  // color off
227         curfmt &= 0x003fffff;
228         length = 4;
229       } else {
230         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
231         //TODO: use 99 as transparent color (re mirc color "standard")
232         color &= 0x0f;
233         if(s[pos+3] == 'f')
234           curfmt |= (color << 24) | 0x00400000;
235         else
236           curfmt |= (color << 28) | 0x00800000;
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(qPrintable(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 UiStyle::StyledMessage UiStyle::styleMessage(const Message &msg) {
312   QString user = userFromMask(msg.sender());
313   QString host = hostFromMask(msg.sender());
314   QString nick = nickFromMask(msg.sender());
315   QString txt = mircToInternal(msg.contents());
316   QString bufferName = msg.bufferInfo().bufferName();
317
318   StyledMessage result;
319
320   result.timestamp = styleString(tr("%DT[%1]").arg(msg.timestamp().toLocalTime().toString("hh:mm:ss")));
321
322   QString s, t;
323   switch(msg.type()) {
324     case Message::Plain:
325       s = tr("%DS<%1>").arg(nick); t = tr("%D0%1").arg(txt); break;
326     case Message::Notice:
327       s = tr("%Dn[%1]").arg(nick); t = tr("%Dn%1").arg(txt); break;
328     case Message::Server:
329       s = tr("%Ds*"); t = tr("%Ds%1").arg(txt); break;
330     case Message::Error:
331       s = tr("%De*"); t = tr("%De%1").arg(txt); break;
332     case Message::Join:
333       s = tr("%Dj-->"); t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
334     case Message::Part:
335       s = tr("%Dp<--"); t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
336       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
337       break;
338     case Message::Quit:
339       s = tr("%Dq<--"); t = tr("%Dq%DN%DU%1%DU%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
340       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
341       break;
342     case Message::Kick:
343       { s = tr("%Dk<-*");
344         QString victim = txt.section(" ", 0, 0);
345         //if(victim == ui.ownNick->currentText()) victim = tr("you");
346         QString kickmsg = txt.section(" ", 1);
347         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
348         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
349       }
350       break;
351     case Message::Nick:
352       s = tr("%Dr<->");
353       if(nick == msg.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       s = tr("%Dm***");
358       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
359       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
360       break;
361     case Message::Action:
362       s = tr("%Da-*-");
363       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
364       break;
365     default:
366       s = tr("%De%1").arg(msg.sender());
367       t = tr("%De[%1]").arg(txt);
368   }
369   result.sender = styleString(s);
370   result.contents = styleString(t);
371   return result;
372 }
373
374 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
375   out << formatList.count();
376   UiStyle::FormatList::const_iterator it = formatList.begin();
377   while(it != formatList.end()) {
378     out << (*it).first << (*it).second;
379     ++it;
380   }
381   return out;
382 }
383
384 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
385   quint16 cnt;
386   in >> cnt;
387   for(quint16 i = 0; i < cnt; i++) {
388     quint16 pos; quint32 ftype;
389     in >> pos >> ftype;
390     formatList.append(qMakePair((quint16)pos, ftype));
391   }
392   return in;
393 }