10b25e7d75de0567055d9bdf06995f2d15ecb9b5
[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 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
27   // register FormatList if that hasn't happened yet
28   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
29   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
30     qRegisterMetaType<FormatList>("UiStyle::FormatList");
31     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
32     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
33   }
34
35   // Default format
36   _defaultPlainFormat.setForeground(QBrush("#000000"));
37   _defaultPlainFormat.setFont(QFont("Monospace", QApplication::font().pointSize()));
38   _defaultPlainFormat.font().setFixedPitch(true);
39   _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
40   setFormat(None, _defaultPlainFormat, Settings::Default);
41   
42   // Load saved custom formats
43   UiStyleSettings s(_settingsKey);
44   foreach(FormatType type, s.availableFormats()) {
45     _customFormats[type] = s.customFormat(type);
46   }
47
48   // Initialize color codes according to mIRC "standard"
49   QStringList colors;
50   //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
51   //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
52   colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
53   colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
54
55   // Now initialize the mapping between FormatCodes and FormatTypes...
56   _formatCodes["%O"] = None;
57   _formatCodes["%B"] = Bold;
58   _formatCodes["%S"] = Italic;
59   _formatCodes["%U"] = Underline;
60   _formatCodes["%R"] = Reverse;
61
62   _formatCodes["%D0"] = PlainMsg;
63   _formatCodes["%Dn"] = NoticeMsg;
64   _formatCodes["%Ds"] = ServerMsg;
65   _formatCodes["%De"] = ErrorMsg;
66   _formatCodes["%Dj"] = JoinMsg;
67   _formatCodes["%Dp"] = PartMsg;
68   _formatCodes["%Dq"] = QuitMsg;
69   _formatCodes["%Dk"] = KickMsg;
70   _formatCodes["%Dr"] = RenameMsg;
71   _formatCodes["%Dm"] = ModeMsg;
72   _formatCodes["%Da"] = ActionMsg;
73
74   _formatCodes["%DT"] = Timestamp;
75   _formatCodes["%DS"] = Sender;
76   _formatCodes["%DN"] = Nick;
77   _formatCodes["%DH"] = Hostmask;
78   _formatCodes["%DC"] = ChannelName;
79   _formatCodes["%DM"] = ModeFlags;
80   _formatCodes["%DU"] = Url;
81
82   // Set color formats
83   for(int i = 0; i < 16; i++) {
84     QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
85     _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 + i);
86     _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 + i);
87     QTextCharFormat fgf, bgf;
88     fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 + i), fgf, Settings::Default);
89     bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 + i), bgf, Settings::Default);
90   }
91
92   // Set a few more standard formats
93   QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
94   setFormat(Bold, bold, Settings::Default);
95
96   QTextCharFormat italic; italic.setFontItalic(true);
97   setFormat(Italic, italic, Settings::Default);
98
99   QTextCharFormat underline; underline.setFontUnderline(true);
100   setFormat(Underline, underline, Settings::Default);
101
102   // All other formats should be defined in derived classes.
103 }
104
105 UiStyle::~ UiStyle() {
106   
107 }
108
109 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
110   if(mode == Settings::Default) {
111     _defaultFormats[ftype] = fmt;
112   } else {
113     UiStyleSettings s(_settingsKey);
114     if(fmt != _defaultFormats[ftype]) {
115       _customFormats[ftype] = fmt;
116       s.setCustomFormat(ftype, fmt);
117     } else {
118       _customFormats[ftype] = QTextFormat().toCharFormat();
119       s.removeCustomFormat(ftype);
120     }
121   }
122   // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
123   _cachedFormats.clear();
124 }
125
126 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
127   if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
128   else return _defaultFormats.value(ftype, QTextCharFormat());
129 }
130
131 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
132 //       until you _really_ know what you do!
133 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
134   if(_cachedFormats.contains(ftype)) return _cachedFormats[ftype];
135   if(ftype == Invalid) return QTextCharFormat();
136   // Now we construct the merged format, starting with the default
137   QTextCharFormat fmt = format(None);
138   // First: general message format
139   fmt.merge(format((FormatType)(ftype & 0x0f)));
140   // now more specific ones
141   for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
142     if(ftype & mask) fmt.merge(format((FormatType)mask));
143   }
144   // color codes!
145   if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
146   if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
147   // URL
148   if(ftype & Url) fmt.merge(format(Url));
149   _cachedFormats[ftype] = fmt;
150   return fmt;
151 }
152
153 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
154   if(_formatCodes.contains(code)) return _formatCodes.value(code);
155   return Invalid;
156 }
157
158 QString UiStyle::formatCode(FormatType ftype) const {
159   return _formatCodes.key(ftype);
160 }
161
162 // This method expects a well-formatted string, there is no error checking!
163 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
164 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
165   QString s = s_;
166   StyledString result;
167   result.formatList.append(qMakePair(0, (quint32)None));
168   quint32 curfmt = (quint32)None;
169   int pos = 0; int length = 0;
170   for(;;) {
171     pos = s.indexOf('%', pos);
172     if(pos < 0) break;
173     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
174       s.remove(pos, 1);
175       pos++;
176       continue;
177     }
178     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
179       if(s[pos+3] == '-') {  // color off
180         curfmt &= 0x003fffff;
181         length = 4;
182       } else {
183         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
184         //TODO: use 99 as transparent color (re mirc color "standard")
185         color &= 0x0f;
186         if(pos+3 == 'f')
187           curfmt |= (color << 24) | 0x00400000;
188         else
189           curfmt |= (color << 28) | 0x00800000;
190         length = 6;
191       }
192     } else if(s[pos+1] == 'O') { // reset formatting
193       curfmt &= 0x0000000f; // we keep message type-specific formatting
194       length = 2;
195     } else if(s[pos+1] == 'R') { // reverse
196       // TODO: implement reverse formatting
197
198       length = 2;
199     } else { // all others are toggles
200       QString code = QString("%") + s[pos+1];
201       if(s[pos+1] == 'D') code += s[pos+2];
202       FormatType ftype = formatType(code);
203       if(ftype == Invalid) {
204         qWarning(qPrintable(QString("Invalid format code in string: %1").arg(s)));
205         continue;
206       }
207       curfmt ^= ftype;
208       length = code.length();
209     }
210     s.remove(pos, length);
211     if(pos == result.formatList.last().first)
212       result.formatList.last().second = curfmt;
213     else
214       result.formatList.append(qMakePair(pos, curfmt));
215   }
216   result.plainText = s;
217   return result;
218 }
219
220 QString UiStyle::mircToInternal(const QString &mirc_) {
221   QString mirc = mirc_;
222   mirc.replace('%', "%%");      // escape % just to be sure
223   mirc.replace('\x02', "%B");
224   mirc.replace('\x0f', "%O");
225   mirc.replace('\x12', "%R");
226   mirc.replace('\x16', "%R");
227   mirc.replace('\x1d', "%S");
228   mirc.replace('\x1f', "%U");
229
230   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
231   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
232   // %Dc- turns color off.
233   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
234   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
235   int pos = 0;
236   for(;;) {
237     pos = mirc.indexOf('\x03', pos);
238     if(pos < 0) break; // no more mirc color codes
239     QString ins, num;
240     int l = mirc.length();
241     int i = pos + 1;
242     // check for fg color
243     if(i < l && mirc[i].isDigit()) {
244       num = mirc[i++];
245       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
246       else num.prepend('0');
247       ins = QString("%Dcf%1").arg(num);
248
249       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
250         i++;
251         num = mirc[i++];
252         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
253         else num.prepend('0');
254         ins += QString("%Dcb%1").arg(num);
255       }
256     } else {
257       ins = "%Dc-";
258     }
259     mirc.replace(pos, i-pos, ins);
260   }
261   return mirc;
262 }
263
264 UiStyle::StyledMessage UiStyle::styleMessage(const Message &msg) {
265   QString user = userFromMask(msg.sender());
266   QString host = hostFromMask(msg.sender());
267   QString nick = nickFromMask(msg.sender());
268   QString txt = mircToInternal(msg.contents());
269   QString bufferName = msg.bufferInfo().bufferName();
270
271   StyledMessage result;
272
273   result.timestamp = styleString(tr("%DT[%1]").arg(msg.timestamp().toLocalTime().toString("hh:mm:ss")));
274
275   QString s, t;
276   switch(msg.type()) {
277     case Message::Plain:
278       s = tr("%DS<%1>").arg(nick); t = tr("%D0%1").arg(txt); break;
279     case Message::Notice:
280       s = tr("%Dn[%1]").arg(nick); t = tr("%Dn%1").arg(txt); break;
281     case Message::Server:
282       s = tr("%Ds*"); t = tr("%Ds%1").arg(txt); break;
283     case Message::Error:
284       s = tr("%De*"); t = tr("%De%1").arg(txt); break;
285     case Message::Join:
286       s = tr("%Dj-->"); t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
287     case Message::Part:
288       s = tr("%Dp<--"); t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
289       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
290       break;
291     case Message::Quit:
292       s = tr("%Dq<--"); t = tr("%Dq%DN%DU%1%DU%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
293       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
294       break;
295     case Message::Kick:
296       { s = tr("%Dk<-*");
297         QString victim = txt.section(" ", 0, 0);
298         //if(victim == ui.ownNick->currentText()) victim = tr("you");
299         QString kickmsg = txt.section(" ", 1);
300         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
301         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
302       }
303       break;
304     case Message::Nick:
305       s = tr("%Dr<->");
306       if(nick == msg.contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
307       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
308       break;
309     case Message::Mode:
310       s = tr("%Dm***");
311       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
312       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
313       break;
314     case Message::Action:
315       s = tr("%Da-*-");
316       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
317       break;
318     default:
319       s = tr("%De%1").arg(msg.sender());
320       t = tr("%De[%1]").arg(txt);
321   }
322   result.sender = styleString(s);
323   result.contents = styleString(t);
324   return result;
325 }
326
327 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
328   out << formatList.count();
329   UiStyle::FormatList::const_iterator it = formatList.begin();
330   while(it != formatList.end()) {
331     out << (*it).first << (*it).second;
332     ++it;
333   }
334   return out;
335 }
336
337 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
338   int cnt;
339   in >> cnt;
340   for(int i = 0; i < cnt; i++) {
341     int pos; quint32 ftype;
342     in >> pos >> ftype;
343     formatList.append(qMakePair(pos, ftype));
344   }
345   return in;
346 }