Kill old non-stylesheet code from UiStyle
[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 "qssparser.h"
23 #include "quassel.h"
24 #include "uistyle.h"
25 #include "uisettings.h"
26 #include "util.h"
27
28 UiStyle::UiStyle() {
29   // register FormatList if that hasn't happened yet
30   // FIXME I don't think this actually avoids double registration... then again... does it hurt?
31   if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
32     qRegisterMetaType<FormatList>("UiStyle::FormatList");
33     qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
34     Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
35   }
36
37   // Now initialize the mapping between FormatCodes and FormatTypes...
38   _formatCodes["%O"] = None;
39   _formatCodes["%B"] = Bold;
40   _formatCodes["%S"] = Italic;
41   _formatCodes["%U"] = Underline;
42   _formatCodes["%R"] = Reverse;
43
44   _formatCodes["%D0"] = PlainMsg;
45   _formatCodes["%Dn"] = NoticeMsg;
46   _formatCodes["%Ds"] = ServerMsg;
47   _formatCodes["%De"] = ErrorMsg;
48   _formatCodes["%Dj"] = JoinMsg;
49   _formatCodes["%Dp"] = PartMsg;
50   _formatCodes["%Dq"] = QuitMsg;
51   _formatCodes["%Dk"] = KickMsg;
52   _formatCodes["%Dr"] = RenameMsg;
53   _formatCodes["%Dm"] = ModeMsg;
54   _formatCodes["%Da"] = ActionMsg;
55
56   _formatCodes["%DT"] = Timestamp;
57   _formatCodes["%DS"] = Sender;
58   _formatCodes["%DN"] = Nick;
59   _formatCodes["%DH"] = Hostmask;
60   _formatCodes["%DC"] = ChannelName;
61   _formatCodes["%DM"] = ModeFlags;
62   _formatCodes["%DU"] = Url;
63
64   loadStyleSheet();
65 }
66
67 UiStyle::~ UiStyle() {
68   qDeleteAll(_metricsCache);
69 }
70
71 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
72   return _formatCache.value(key, QTextCharFormat());
73 }
74
75 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
76   return cachedFormat(formatType | ((quint64)messageLabel << 32));
77 }
78
79 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
80   _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
81 }
82
83 // Merge a subelement format into an existing message format
84 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint32 label) {
85   quint64 key = ftype | ((quint64)label << 32);
86
87   // start with the most general format and then specialize
88   fmt.merge(cachedFormat(key & 0x00000000fffffff0));  // basic subelement format
89   fmt.merge(cachedFormat(key & 0x00000000ffffffff));  // subelement + msgtype
90   fmt.merge(cachedFormat(key & 0xffff0000fffffff0));  // subelement + nickhash
91   fmt.merge(cachedFormat(key & 0xffff0000ffffffff));  // subelement + nickhash + msgtype
92   fmt.merge(cachedFormat(key & 0x0000fffffffffff0));  // label + subelement
93   fmt.merge(cachedFormat(key & 0x0000ffffffffffff));  // label + subelement + msgtype
94   fmt.merge(cachedFormat(key & 0xfffffffffffffff0));  // label + subelement + nickhash
95   fmt.merge(cachedFormat(key & 0xffffffffffffffff));  // label + subelement + nickhash + msgtype
96 }
97
98 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
99 //       until you _really_ know what you do!
100 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label) {
101   if(ftype == Invalid)
102     return QTextCharFormat();
103
104   quint64 key = ftype | ((quint64)label << 32);
105
106   // check if we have exactly this format readily cached already
107   QTextCharFormat fmt = cachedFormat(key);
108   if(fmt.isValid())
109     return fmt;
110
111   fmt.merge(cachedFormat(key & 0x0000000000000000));  // basic
112   fmt.merge(cachedFormat(key & 0x000000000000000f));  // msgtype
113   fmt.merge(cachedFormat(key & 0x0000ffff00000000));  // label
114   fmt.merge(cachedFormat(key & 0x0000ffff0000000f));  // label + msgtype
115
116   // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
117   //       or "foreground 01 and background 03"
118   if((ftype & 0xfff0)) { // element format
119     for(quint32 mask = 0x10; mask <= 0x2000; mask <<= 1) {
120       if(ftype & mask) {
121         mergeSubElementFormat(fmt, ftype & 0xffff, label);
122       }
123     }
124   }
125
126   // Now we handle color codes
127   if(ftype & 0x00400000)
128     mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
129   if(ftype & 0x00800000)
130     mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
131   if((ftype & 0x00c00000) == 0x00c00000)
132     mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
133
134   // URL
135   if(ftype & Url)
136     mergeSubElementFormat(fmt, ftype & Url, label);
137
138   setCachedFormat(fmt, ftype, label);
139   return fmt;
140 }
141
142 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
143   // QFontMetricsF is not assignable, so we need to store pointers :/
144   quint64 key = ftype | ((quint64)label << 32);
145
146   if(_metricsCache.contains(key))
147     return _metricsCache.value(key);
148
149   return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
150 }
151
152 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
153   if(_formatCodes.contains(code)) return _formatCodes.value(code);
154   return Invalid;
155 }
156
157 QString UiStyle::formatCode(FormatType ftype) const {
158   return _formatCodes.key(ftype);
159 }
160
161 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
162   QList<QTextLayout::FormatRange> formatRanges;
163   QTextLayout::FormatRange range;
164   int i = 0;
165   for(i = 0; i < formatList.count(); i++) {
166     range.format = format(formatList.at(i).second);
167     range.start = formatList.at(i).first;
168     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
169     formatRanges.append(range);
170   }
171   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
172   return formatRanges;
173 }
174
175 // This method expects a well-formatted string, there is no error checking!
176 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
177 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
178   QString s = s_;
179   if(s.length() > 65535) {
180     qWarning() << QString("String too long to be styled: %1").arg(s);
181     return StyledString();
182   }
183   StyledString result;
184   result.formatList.append(qMakePair((quint16)0, (quint32)None));
185   quint32 curfmt = (quint32)None;
186   int pos = 0; quint16 length = 0;
187   for(;;) {
188     pos = s.indexOf('%', pos);
189     if(pos < 0) break;
190     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
191       s.remove(pos, 1);
192       pos++;
193       continue;
194     }
195     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
196       if(s[pos+3] == '-') {  // color off
197         curfmt &= 0x003fffff;
198         length = 4;
199       } else {
200         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
201         //TODO: use 99 as transparent color (re mirc color "standard")
202         color &= 0x0f;
203         if(s[pos+3] == 'f') {
204           curfmt &= 0xf0ffffff;
205           curfmt |= (color << 24) | 0x00400000;
206         } else {
207           curfmt &= 0x0fffffff;
208           curfmt |= (color << 28) | 0x00800000;
209         }
210         length = 6;
211       }
212     } else if(s[pos+1] == 'O') { // reset formatting
213       curfmt &= 0x0000000f; // we keep message type-specific formatting
214       length = 2;
215     } else if(s[pos+1] == 'R') { // reverse
216       // TODO: implement reverse formatting
217
218       length = 2;
219     } else { // all others are toggles
220       QString code = QString("%") + s[pos+1];
221       if(s[pos+1] == 'D') code += s[pos+2];
222       FormatType ftype = formatType(code);
223       if(ftype == Invalid) {
224         qWarning() << (QString("Invalid format code in string: %1").arg(s));
225         continue;
226       }
227       curfmt ^= ftype;
228       length = code.length();
229     }
230     s.remove(pos, length);
231     if(pos == result.formatList.last().first)
232       result.formatList.last().second = curfmt;
233     else
234       result.formatList.append(qMakePair((quint16)pos, curfmt));
235   }
236   result.plainText = s;
237   return result;
238 }
239
240 QString UiStyle::mircToInternal(const QString &mirc_) const {
241   QString mirc = mirc_;
242   mirc.replace('%', "%%");      // escape % just to be sure
243   mirc.replace('\x02', "%B");
244   mirc.replace('\x0f', "%O");
245   mirc.replace('\x12', "%R");
246   mirc.replace('\x16', "%R");
247   mirc.replace('\x1d', "%S");
248   mirc.replace('\x1f', "%U");
249
250   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
251   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
252   // %Dc- turns color off.
253   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
254   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
255   int pos = 0;
256   for(;;) {
257     pos = mirc.indexOf('\x03', pos);
258     if(pos < 0) break; // no more mirc color codes
259     QString ins, num;
260     int l = mirc.length();
261     int i = pos + 1;
262     // check for fg color
263     if(i < l && mirc[i].isDigit()) {
264       num = mirc[i++];
265       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
266       else num.prepend('0');
267       ins = QString("%Dcf%1").arg(num);
268
269       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
270         i++;
271         num = mirc[i++];
272         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
273         else num.prepend('0');
274         ins += QString("%Dcb%1").arg(num);
275       }
276     } else {
277       ins = "%Dc-";
278     }
279     mirc.replace(pos, i-pos, ins);
280   }
281   return mirc;
282 }
283
284 /***********************************************************************************/
285 UiStyle::StyledMessage::StyledMessage(const Message &msg)
286   : Message(msg)
287 {
288 }
289
290 void UiStyle::StyledMessage::style(UiStyle *style) const {
291   QString user = userFromMask(sender());
292   QString host = hostFromMask(sender());
293   QString nick = nickFromMask(sender());
294   QString txt = style->mircToInternal(contents());
295   QString bufferName = bufferInfo().bufferName();
296   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
297
298   QString t;
299   switch(type()) {
300     case Message::Plain:
301       t = tr("%D0%1").arg(txt); break;
302     case Message::Notice:
303       t = tr("%Dn%1").arg(txt); break;
304     case Message::Topic:
305     case Message::Server:
306       t = tr("%Ds%1").arg(txt); break;
307     case Message::Error:
308       t = tr("%De%1").arg(txt); break;
309     case Message::Join:
310       t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
311     case Message::Part:
312       t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
313       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
314       break;
315     case Message::Quit:
316       t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
317       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
318       break;
319     case Message::Kick: {
320         QString victim = txt.section(" ", 0, 0);
321         QString kickmsg = txt.section(" ", 1);
322         t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
323         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
324       }
325       break;
326     case Message::Nick:
327       if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
328       else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
329       break;
330     case Message::Mode:
331       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
332       else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
333       break;
334     case Message::Action:
335       t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
336       break;
337     default:
338       t = tr("%De[%1]").arg(txt);
339   }
340   _contents = style->styleString(t);
341 }
342
343 QString UiStyle::StyledMessage::decoratedTimestamp() const {
344   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
345 }
346
347 QString UiStyle::StyledMessage::plainSender() const {
348   switch(type()) {
349     case Message::Plain:
350     case Message::Notice:
351       return nickFromMask(sender());
352     default:
353       return QString();
354   }
355 }
356
357 QString UiStyle::StyledMessage::decoratedSender() const {
358   switch(type()) {
359     case Message::Plain:
360       return tr("<%1>").arg(plainSender()); break;
361     case Message::Notice:
362       return tr("[%1]").arg(plainSender()); break;
363     case Message::Topic:
364     case Message::Server:
365       return tr("*"); break;
366     case Message::Error:
367       return tr("*"); break;
368     case Message::Join:
369       return tr("-->"); break;
370     case Message::Part:
371       return tr("<--"); break;
372     case Message::Quit:
373       return tr("<--"); break;
374     case Message::Kick:
375       return tr("<-*"); break;
376     case Message::Nick:
377       return tr("<->"); break;
378     case Message::Mode:
379       return tr("***"); break;
380     case Message::Action:
381       return tr("-*-"); break;
382     default:
383       return tr("%1").arg(plainSender());
384   }
385 }
386
387 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
388   switch(type()) {
389     case Message::Plain:
390       // To produce random like but stable nick colorings some sort of hashing should work best.
391       // In this case we just use the qt function qChecksum which produces a
392       // CRC16 hash. This should be fast and 16 bits are more than enough.
393       {
394         QString nick = nickFromMask(sender()).toLower();
395         if(!nick.isEmpty()) {
396           int chopCount = 0;
397           while(nick[nick.count() - 1 - chopCount] == '_') {
398             chopCount++;
399           }
400           nick.chop(chopCount);
401         }
402         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
403         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
404       }
405     case Message::Notice:
406       return UiStyle::NoticeMsg; break;
407     case Message::Topic:
408     case Message::Server:
409       return UiStyle::ServerMsg; break;
410     case Message::Error:
411       return UiStyle::ErrorMsg; break;
412     case Message::Join:
413       return UiStyle::JoinMsg; break;
414     case Message::Part:
415       return UiStyle::PartMsg; break;
416     case Message::Quit:
417       return UiStyle::QuitMsg; break;
418     case Message::Kick:
419       return UiStyle::KickMsg; break;
420     case Message::Nick:
421       return UiStyle::RenameMsg; break;
422     case Message::Mode:
423       return UiStyle::ModeMsg; break;
424     case Message::Action:
425       return UiStyle::ActionMsg; break;
426     default:
427       return UiStyle::ErrorMsg;
428   }
429 }
430
431
432 /***********************************************************************************/
433
434 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
435   out << formatList.count();
436   UiStyle::FormatList::const_iterator it = formatList.begin();
437   while(it != formatList.end()) {
438     out << (*it).first << (*it).second;
439     ++it;
440   }
441   return out;
442 }
443
444 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
445   quint16 cnt;
446   in >> cnt;
447   for(quint16 i = 0; i < cnt; i++) {
448     quint16 pos; quint32 ftype;
449     in >> pos >> ftype;
450     formatList.append(qMakePair((quint16)pos, ftype));
451   }
452   return in;
453 }
454
455 /***********************************************************************************/
456 // Stylesheet handling
457 /***********************************************************************************/
458
459 void UiStyle::loadStyleSheet() {
460   QssParser parser;
461   parser.loadStyleSheet(qApp->styleSheet());
462
463   // TODO handle results
464   QApplication::setPalette(parser.palette());
465   //QApplication::setStyleSheet(qApp->styleSheet()); // reload with custom palette settings
466 }