fix compile error on non-x86_64
[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 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
29
30 UiStyle::UiStyle() {
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   // Now initialize the mapping between FormatCodes and FormatTypes...
40   _formatCodes["%O"] = None;
41   _formatCodes["%B"] = Bold;
42   _formatCodes["%S"] = Italic;
43   _formatCodes["%U"] = Underline;
44   _formatCodes["%R"] = Reverse;
45
46   _formatCodes["%DN"] = Nick;
47   _formatCodes["%DH"] = Hostmask;
48   _formatCodes["%DC"] = ChannelName;
49   _formatCodes["%DM"] = ModeFlags;
50   _formatCodes["%DU"] = Url;
51
52   loadStyleSheet();
53 }
54
55 UiStyle::~ UiStyle() {
56   qDeleteAll(_metricsCache);
57 }
58
59 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
60   return _formatCache.value(key, QTextCharFormat());
61 }
62
63 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
64   return cachedFormat(formatType | ((quint64)messageLabel << 32));
65 }
66
67 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
68   _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
69 }
70
71 // Merge a subelement format into an existing message format
72 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint32 label) {
73   quint64 key = ftype | ((quint64)label << 32);
74
75   // start with the most general format and then specialize
76   fmt.merge(cachedFormat(key & Q_UINT64_C(0x00000000fffffff0)));  // basic subelement format
77   fmt.merge(cachedFormat(key & Q_UINT64_C(0x00000000ffffffff)));  // subelement + msgtype
78   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffff0000fffffff0)));  // subelement + nickhash
79   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffff0000ffffffff)));  // subelement + nickhash + msgtype
80   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000fffffffffff0)));  // label + subelement
81   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffffffffffff)));  // label + subelement + msgtype
82   fmt.merge(cachedFormat(key & Q_UINT64_C(0xfffffffffffffff0)));  // label + subelement + nickhash
83   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffffffffffff)));  // label + subelement + nickhash + msgtype
84 }
85
86 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
87 //       until you _really_ know what you do!
88 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label) {
89   if(ftype == Invalid)
90     return QTextCharFormat();
91
92   quint64 key = ftype | ((quint64)label << 32);
93
94   // check if we have exactly this format readily cached already
95   QTextCharFormat fmt = cachedFormat(key);
96   if(fmt.properties().count())
97     return fmt;
98
99   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000000000000000)));  // basic
100   fmt.merge(cachedFormat(key & Q_UINT64_C(0x000000000000000f)));  // msgtype
101   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffff000000000000)));  // nickhash
102   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffff00000000000f)));  // nickhash + msgtype
103   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffff00000000)));  // label
104   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffff0000000f)));  // label + msgtype
105   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffff00000000)));  // label + nickhash
106   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffff0000000f)));  // label + nickhash + msgtype
107
108   // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
109   //       or "foreground 01 and background 03"
110   if((ftype & 0xfff0)) { // element format
111     for(quint32 mask = 0x10; mask <= 0x2000; mask <<= 1) {
112       if(ftype & mask) {
113         mergeSubElementFormat(fmt, ftype & 0xffff, label);
114       }
115     }
116   }
117
118   // Now we handle color codes
119   if(ftype & 0x00400000)
120     mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
121   if(ftype & 0x00800000)
122     mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
123   if((ftype & 0x00c00000) == 0x00c00000)
124     mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
125
126   // URL
127   if(ftype & Url)
128     mergeSubElementFormat(fmt, ftype & Url, label);
129
130   setCachedFormat(fmt, ftype, label);
131   return fmt;
132 }
133
134 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
135   // QFontMetricsF is not assignable, so we need to store pointers :/
136   quint64 key = ftype | ((quint64)label << 32);
137
138   if(_metricsCache.contains(key))
139     return _metricsCache.value(key);
140
141   return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
142 }
143
144 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) {
145   switch(msgType) {
146     case Message::Plain:
147       return PlainMsg;
148     case Message::Notice:
149       return NoticeMsg;
150     case Message::Action:
151       return ActionMsg;
152     case Message::Nick:
153       return NickMsg;
154     case Message::Mode:
155       return ModeMsg;
156     case Message::Join:
157       return JoinMsg;
158     case Message::Part:
159       return PartMsg;
160     case Message::Quit:
161       return QuitMsg;
162     case Message::Kick:
163       return KickMsg;
164     case Message::Kill:
165       return KillMsg;
166     case Message::Server:
167       return ServerMsg;
168     case Message::Info:
169       return InfoMsg;
170     case Message::Error:
171       return ErrorMsg;
172     case Message::DayChange:
173       return DayChangeMsg;
174   }
175   Q_ASSERT(false); // we need to handle all message types
176   return ErrorMsg;
177 }
178
179 UiStyle::FormatType UiStyle::formatType(const QString & code) {
180   if(_formatCodes.contains(code)) return _formatCodes.value(code);
181   return Invalid;
182 }
183
184 QString UiStyle::formatCode(FormatType ftype) {
185   return _formatCodes.key(ftype);
186 }
187
188 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) {
189   QList<QTextLayout::FormatRange> formatRanges;
190   QTextLayout::FormatRange range;
191   int i = 0;
192   for(i = 0; i < formatList.count(); i++) {
193     range.format = format(formatList.at(i).second, messageLabel);
194     range.start = formatList.at(i).first;
195     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
196     formatRanges.append(range);
197   }
198   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
199   return formatRanges;
200 }
201
202 // This method expects a well-formatted string, there is no error checking!
203 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
204 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
205   QString s = s_;
206   if(s.length() > 65535) {
207     qWarning() << QString("String too long to be styled: %1").arg(s);
208     return StyledString();
209   }
210   StyledString result;
211   result.formatList.append(qMakePair((quint16)0, baseFormat));
212   quint32 curfmt = baseFormat;
213   int pos = 0; quint16 length = 0;
214   for(;;) {
215     pos = s.indexOf('%', pos);
216     if(pos < 0) break;
217     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
218       s.remove(pos, 1);
219       pos++;
220       continue;
221     }
222     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
223       if(s[pos+3] == '-') {  // color off
224         curfmt &= 0x003fffff;
225         length = 4;
226       } else {
227         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
228         //TODO: use 99 as transparent color (re mirc color "standard")
229         color &= 0x0f;
230         if(s[pos+3] == 'f') {
231           curfmt &= 0xf0ffffff;
232           curfmt |= (color << 24) | 0x00400000;
233         } else {
234           curfmt &= 0x0fffffff;
235           curfmt |= (color << 28) | 0x00800000;
236         }
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() << (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_) {
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 /***********************************************************************************/
312 UiStyle::StyledMessage::StyledMessage(const Message &msg)
313   : Message(msg)
314 {
315   if(type() == Message::Plain)
316     _senderHash = 0xff;
317   else
318     _senderHash = 0x00;  // this means we never compute the hash for msgs that aren't plain
319 }
320
321 void UiStyle::StyledMessage::style() const {
322   QString user = userFromMask(sender());
323   QString host = hostFromMask(sender());
324   QString nick = nickFromMask(sender());
325   QString txt = UiStyle::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       //: Plain Message
333       t = tr("%1").arg(txt); break;
334     case Message::Notice:
335       //: Notice Message
336       t = tr("%1").arg(txt); break;
337     case Message::Action:
338       //: Action Message
339       t = tr("%DN%1%DN %2").arg(nick).arg(txt);
340       break;
341     case Message::Nick:
342       //: Nick Message
343       if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
344       else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
345       break;
346     case Message::Mode:
347       //: Mode Message
348       if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
349       else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
350       break;
351     case Message::Join:
352       //: Join Message
353       t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
354     case Message::Part:
355       //: Part Message
356       t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
357       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
358       break;
359     case Message::Quit:
360       //: Quit Message
361       t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
362       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
363       break;
364     case Message::Kick: {
365         QString victim = txt.section(" ", 0, 0);
366         QString kickmsg = txt.section(" ", 1);
367         //: Kick Message
368         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
369         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
370       }
371       break;
372     //case Message::Kill: FIXME
373
374     case Message::Server:
375       //: Server Message
376       t = tr("%1").arg(txt); break;
377     case Message::Info:
378       //: Info Message
379       t = tr("%1").arg(txt); break;
380     case Message::Error:
381       //: Error Message
382       t = tr("%1").arg(txt); break;
383     case Message::DayChange:
384       //: Day Change Message
385       t = tr("{Day changed to %1}").arg(timestamp().toString());
386       break;
387     default:
388       t = tr("[%1]").arg(txt);
389   }
390   _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
391 }
392
393 const QString &UiStyle::StyledMessage::plainContents() const {
394   if(_contents.plainText.isNull())
395     style();
396
397   return _contents.plainText;
398 }
399
400 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
401   if(_contents.plainText.isNull())
402     style();
403
404   return _contents.formatList;
405 }
406
407 QString UiStyle::StyledMessage::decoratedTimestamp() const {
408   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
409 }
410
411 QString UiStyle::StyledMessage::plainSender() const {
412   switch(type()) {
413     case Message::Plain:
414     case Message::Notice:
415       return nickFromMask(sender());
416     default:
417       return QString();
418   }
419 }
420
421 QString UiStyle::StyledMessage::decoratedSender() const {
422   switch(type()) {
423     case Message::Plain:
424       return tr("<%1>").arg(plainSender()); break;
425     case Message::Notice:
426       return tr("[%1]").arg(plainSender()); break;
427 <<<<<<< HEAD
428     case Message::Topic:
429     case Message::Server:
430       return tr("*"); break;
431     case Message::Error:
432       return tr("*"); break;
433 =======
434     case Message::Action:
435       return tr("-*-"); break;
436     case Message::Nick:
437       return tr("<->"); break;
438     case Message::Mode:
439       return tr("***"); break;
440 >>>>>>> Handle all message types properly in UiStyle; eliminate msgtype format codes
441     case Message::Join:
442       return tr("-->"); break;
443     case Message::Part:
444       return tr("<--"); break;
445     case Message::Quit:
446       return tr("<--"); break;
447     case Message::Kick:
448       return tr("<-*"); break;
449     case Message::Kill:
450       return tr("<-x"); break;
451     case Message::Server:
452       return tr("*"); break;
453     case Message::Info:
454       return tr("*"); break;
455     case Message::Error:
456       return tr("*"); break;
457     case Message::DayChange:
458       return tr("-"); break;
459     default:
460       return tr("%1").arg(plainSender());
461   }
462 }
463
464 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
465   switch(type()) {
466     case Message::Plain:
467       // To produce random like but stable nick colorings some sort of hashing should work best.
468       // In this case we just use the qt function qChecksum which produces a
469       // CRC16 hash. This should be fast and 16 bits are more than enough.
470       {
471         QString nick = nickFromMask(sender()).toLower();
472         if(!nick.isEmpty()) {
473           int chopCount = 0;
474           while(nick[nick.count() - 1 - chopCount] == '_') {
475             chopCount++;
476           }
477           nick.chop(chopCount);
478         }
479         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
480         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
481       }
482     case Message::Notice:
483       return UiStyle::NoticeMsg; break;
484     case Message::Topic:
485     case Message::Server:
486       return UiStyle::ServerMsg; break;
487     case Message::Error:
488       return UiStyle::ErrorMsg; break;
489     case Message::Join:
490       return UiStyle::JoinMsg; break;
491     case Message::Part:
492       return UiStyle::PartMsg; break;
493     case Message::Quit:
494       return UiStyle::QuitMsg; break;
495     case Message::Kick:
496       return UiStyle::KickMsg; break;
497     case Message::Nick:
498       return UiStyle::NickMsg; break;
499     case Message::Mode:
500       return UiStyle::ModeMsg; break;
501     case Message::Action:
502       return UiStyle::ActionMsg; break;
503     default:
504       return UiStyle::ErrorMsg;
505   }
506 }
507
508 // FIXME hardcoded to 16 sender hashes
509 quint8 UiStyle::StyledMessage::senderHash() const {
510   if(_senderHash != 0xff)
511     return _senderHash;
512
513   QString nick = nickFromMask(sender()).toLower();
514   if(!nick.isEmpty()) {
515     int chopCount = 0;
516     while(nick.at(nick.count() - 1 - chopCount) == '_')
517       chopCount++;
518     nick.chop(chopCount);
519   }
520   quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
521   return (_senderHash = (hash & 0xf) + 1);
522 }
523
524 /***********************************************************************************/
525
526 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
527   out << formatList.count();
528   UiStyle::FormatList::const_iterator it = formatList.begin();
529   while(it != formatList.end()) {
530     out << (*it).first << (*it).second;
531     ++it;
532   }
533   return out;
534 }
535
536 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
537   quint16 cnt;
538   in >> cnt;
539   for(quint16 i = 0; i < cnt; i++) {
540     quint16 pos; quint32 ftype;
541     in >> pos >> ftype;
542     formatList.append(qMakePair((quint16)pos, ftype));
543   }
544   return in;
545 }
546
547 /***********************************************************************************/
548 // Stylesheet handling
549 /***********************************************************************************/
550
551 void UiStyle::loadStyleSheet() {
552   QssParser parser;
553   parser.loadStyleSheet(qApp->styleSheet());
554
555   // TODO handle results
556   QApplication::setPalette(parser.palette());
557
558   qDeleteAll(_metricsCache);
559   _metricsCache.clear();
560   _formatCache = parser.formats();
561 }