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