Change handling of message labels
[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(QObject *parent) : QObject(parent) {
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 void UiStyle::loadStyleSheet() {
60   qDeleteAll(_metricsCache);
61   _metricsCache.clear();
62   _formatCache.clear();
63
64   QString styleSheet;
65
66   styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("default.qss"));
67   styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "custom.qss");
68   // styleSheet += loadStyleSheet("file:///" + some custom file name);  FIXME
69   styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
70
71   if(styleSheet.isEmpty())
72     return;
73
74   QssParser parser;
75   parser.processStyleSheet(styleSheet);
76   QApplication::setPalette(parser.palette());
77   _formatCache = parser.formats();
78
79   qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
80
81   emit changed();
82 }
83
84 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist) {
85   QString ss = styleSheet;
86   if(ss.startsWith("file:///")) {
87     ss.remove(0, 8);
88     if(ss.isEmpty())
89       return QString();
90
91     QFile file(ss);
92     if(file.open(QFile::ReadOnly)) {
93       QTextStream stream(&file);
94       ss = stream.readAll();
95       file.close();
96     } else {
97       if(shouldExist)
98         qWarning() << "Could not open stylesheet file:" << file.fileName();
99       return QString();
100     }
101   }
102   return ss;
103 }
104
105 /******** Caching *******/
106
107 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
108   return _formatCache.value(key, QTextCharFormat());
109 }
110
111 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
112   return cachedFormat(formatType | ((quint64)messageLabel << 32));
113 }
114
115 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
116   _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
117 }
118
119 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
120   // QFontMetricsF is not assignable, so we need to store pointers :/
121   quint64 key = ftype | ((quint64)label << 32);
122
123   if(_metricsCache.contains(key))
124     return _metricsCache.value(key);
125
126   return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
127 }
128
129 /******** Generate formats ********/
130
131 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
132 //       until you _really_ know what you do!
133 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) {
134   if(ftype == Invalid)
135     return QTextCharFormat();
136
137   quint64 label = (quint64)label_ << 32;
138
139   // check if we have exactly this format readily cached already
140   QTextCharFormat fmt = cachedFormat(label|ftype);
141   if(fmt.properties().count())
142     return fmt;
143
144   mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
145
146   for(quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<=1) {
147     if(label & mask)
148       mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
149   }
150
151   setCachedFormat(fmt, ftype, label_);
152   return fmt;
153 }
154
155 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) {
156   mergeSubElementFormat(fmt, ftype & 0x000f, label);
157
158   // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
159   //       or "foreground 01 and background 03"
160   if((ftype & 0xfff0)) { // element format
161     for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
162       if(ftype & mask) {
163         mergeSubElementFormat(fmt, mask | 0x0f, label);
164       }
165     }
166   }
167
168   // Now we handle color codes
169   // We assume that those can't be combined with subelement and message types.
170   if(ftype & 0x00400000)
171     mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
172   if(ftype & 0x00800000)
173     mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
174   if((ftype & 0x00c00000) == 0x00c00000)
175     mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
176
177   // URL
178   if(ftype & Url)
179     mergeSubElementFormat(fmt, ftype & Url, label);
180 }
181
182 // Merge a subelement format into an existing message format
183 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint64 label) {
184   quint64 key = ftype | label;
185   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000fffffffffff0)));  // label + subelement
186   fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffffffffffff)));  // label + subelement + msgtype
187   fmt.merge(cachedFormat(key & Q_UINT64_C(0xfffffffffffffff0)));  // label + subelement + nickhash
188   fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffffffffffff)));  // label + subelement + nickhash + msgtype
189 }
190
191 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) {
192   switch(msgType) {
193     case Message::Plain:
194       return PlainMsg;
195     case Message::Notice:
196       return NoticeMsg;
197     case Message::Action:
198       return ActionMsg;
199     case Message::Nick:
200       return NickMsg;
201     case Message::Mode:
202       return ModeMsg;
203     case Message::Join:
204       return JoinMsg;
205     case Message::Part:
206       return PartMsg;
207     case Message::Quit:
208       return QuitMsg;
209     case Message::Kick:
210       return KickMsg;
211     case Message::Kill:
212       return KillMsg;
213     case Message::Server:
214       return ServerMsg;
215     case Message::Info:
216       return InfoMsg;
217     case Message::Error:
218       return ErrorMsg;
219     case Message::DayChange:
220       return DayChangeMsg;
221   }
222   Q_ASSERT(false); // we need to handle all message types
223   return ErrorMsg;
224 }
225
226 UiStyle::FormatType UiStyle::formatType(const QString & code) {
227   if(_formatCodes.contains(code)) return _formatCodes.value(code);
228   return Invalid;
229 }
230
231 QString UiStyle::formatCode(FormatType ftype) {
232   return _formatCodes.key(ftype);
233 }
234
235 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) {
236   QList<QTextLayout::FormatRange> formatRanges;
237   QTextLayout::FormatRange range;
238   int i = 0;
239   for(i = 0; i < formatList.count(); i++) {
240     range.format = format(formatList.at(i).second, messageLabel);
241     range.start = formatList.at(i).first;
242     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
243     formatRanges.append(range);
244   }
245   if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
246   return formatRanges;
247 }
248
249 // This method expects a well-formatted string, there is no error checking!
250 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
251 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
252   QString s = s_;
253   if(s.length() > 65535) {
254     qWarning() << QString("String too long to be styled: %1").arg(s);
255     return StyledString();
256   }
257   StyledString result;
258   result.formatList.append(qMakePair((quint16)0, baseFormat));
259   quint32 curfmt = baseFormat;
260   int pos = 0; quint16 length = 0;
261   for(;;) {
262     pos = s.indexOf('%', pos);
263     if(pos < 0) break;
264     if(s[pos+1] == '%') { // escaped %, we just remove one and continue
265       s.remove(pos, 1);
266       pos++;
267       continue;
268     }
269     if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
270       if(s[pos+3] == '-') {  // color off
271         curfmt &= 0x003fffff;
272         length = 4;
273       } else {
274         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
275         //TODO: use 99 as transparent color (re mirc color "standard")
276         color &= 0x0f;
277         if(s[pos+3] == 'f') {
278           curfmt &= 0xf0ffffff;
279           curfmt |= (color << 24) | 0x00400000;
280         } else {
281           curfmt &= 0x0fffffff;
282           curfmt |= (color << 28) | 0x00800000;
283         }
284         length = 6;
285       }
286     } else if(s[pos+1] == 'O') { // reset formatting
287       curfmt &= 0x0000000f; // we keep message type-specific formatting
288       length = 2;
289     } else if(s[pos+1] == 'R') { // reverse
290       // TODO: implement reverse formatting
291
292       length = 2;
293     } else { // all others are toggles
294       QString code = QString("%") + s[pos+1];
295       if(s[pos+1] == 'D') code += s[pos+2];
296       FormatType ftype = formatType(code);
297       if(ftype == Invalid) {
298         qWarning() << (QString("Invalid format code in string: %1").arg(s));
299         continue;
300       }
301       curfmt ^= ftype;
302       length = code.length();
303     }
304     s.remove(pos, length);
305     if(pos == result.formatList.last().first)
306       result.formatList.last().second = curfmt;
307     else
308       result.formatList.append(qMakePair((quint16)pos, curfmt));
309   }
310   result.plainText = s;
311   return result;
312 }
313
314 QString UiStyle::mircToInternal(const QString &mirc_) {
315   QString mirc = mirc_;
316   mirc.replace('%', "%%");      // escape % just to be sure
317   mirc.replace('\x02', "%B");
318   mirc.replace('\x0f', "%O");
319   mirc.replace('\x12', "%R");
320   mirc.replace('\x16', "%R");
321   mirc.replace('\x1d', "%S");
322   mirc.replace('\x1f', "%U");
323
324   // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
325   // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
326   // %Dc- turns color off.
327   // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
328   //       This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
329   int pos = 0;
330   for(;;) {
331     pos = mirc.indexOf('\x03', pos);
332     if(pos < 0) break; // no more mirc color codes
333     QString ins, num;
334     int l = mirc.length();
335     int i = pos + 1;
336     // check for fg color
337     if(i < l && mirc[i].isDigit()) {
338       num = mirc[i++];
339       if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
340       else num.prepend('0');
341       ins = QString("%Dcf%1").arg(num);
342
343       if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
344         i++;
345         num = mirc[i++];
346         if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
347         else num.prepend('0');
348         ins += QString("%Dcb%1").arg(num);
349       }
350     } else {
351       ins = "%Dc-";
352     }
353     mirc.replace(pos, i-pos, ins);
354   }
355   return mirc;
356 }
357
358 /***********************************************************************************/
359 UiStyle::StyledMessage::StyledMessage(const Message &msg)
360   : Message(msg)
361 {
362   if(type() == Message::Plain)
363     _senderHash = 0xff;
364   else
365     _senderHash = 0x00;  // this means we never compute the hash for msgs that aren't plain
366 }
367
368 void UiStyle::StyledMessage::style() const {
369   QString user = userFromMask(sender());
370   QString host = hostFromMask(sender());
371   QString nick = nickFromMask(sender());
372   QString txt = UiStyle::mircToInternal(contents());
373   QString bufferName = bufferInfo().bufferName();
374   bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
375
376   QString t;
377   switch(type()) {
378     case Message::Plain:
379       //: Plain Message
380       t = tr("%1").arg(txt); break;
381     case Message::Notice:
382       //: Notice Message
383       t = tr("%1").arg(txt); break;
384     case Message::Action:
385       //: Action Message
386       t = tr("%DN%1%DN %2").arg(nick).arg(txt);
387       break;
388     case Message::Nick:
389       //: Nick Message
390       if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
391       else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
392       break;
393     case Message::Mode:
394       //: Mode Message
395       if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
396       else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
397       break;
398     case Message::Join:
399       //: Join Message
400       t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
401     case Message::Part:
402       //: Part Message
403       t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
404       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
405       break;
406     case Message::Quit:
407       //: Quit Message
408       t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
409       if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
410       break;
411     case Message::Kick: {
412         QString victim = txt.section(" ", 0, 0);
413         QString kickmsg = txt.section(" ", 1);
414         //: Kick Message
415         t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
416         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
417       }
418       break;
419     //case Message::Kill: FIXME
420
421     case Message::Server:
422       //: Server Message
423       t = tr("%1").arg(txt); break;
424     case Message::Info:
425       //: Info Message
426       t = tr("%1").arg(txt); break;
427     case Message::Error:
428       //: Error Message
429       t = tr("%1").arg(txt); break;
430     case Message::DayChange:
431       //: Day Change Message
432       t = tr("{Day changed to %1}").arg(timestamp().toString());
433       break;
434     default:
435       t = tr("[%1]").arg(txt);
436   }
437   _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
438 }
439
440 const QString &UiStyle::StyledMessage::plainContents() const {
441   if(_contents.plainText.isNull())
442     style();
443
444   return _contents.plainText;
445 }
446
447 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
448   if(_contents.plainText.isNull())
449     style();
450
451   return _contents.formatList;
452 }
453
454 QString UiStyle::StyledMessage::decoratedTimestamp() const {
455   return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
456 }
457
458 QString UiStyle::StyledMessage::plainSender() const {
459   switch(type()) {
460     case Message::Plain:
461     case Message::Notice:
462       return nickFromMask(sender());
463     default:
464       return QString();
465   }
466 }
467
468 QString UiStyle::StyledMessage::decoratedSender() const {
469   switch(type()) {
470     case Message::Plain:
471       return tr("<%1>").arg(plainSender()); break;
472     case Message::Notice:
473       return tr("[%1]").arg(plainSender()); break;
474 <<<<<<< HEAD
475     case Message::Topic:
476     case Message::Server:
477       return tr("*"); break;
478     case Message::Error:
479       return tr("*"); break;
480 =======
481     case Message::Action:
482       return tr("-*-"); break;
483     case Message::Nick:
484       return tr("<->"); break;
485     case Message::Mode:
486       return tr("***"); break;
487 >>>>>>> Handle all message types properly in UiStyle; eliminate msgtype format codes
488     case Message::Join:
489       return tr("-->"); break;
490     case Message::Part:
491       return tr("<--"); break;
492     case Message::Quit:
493       return tr("<--"); break;
494     case Message::Kick:
495       return tr("<-*"); break;
496     case Message::Kill:
497       return tr("<-x"); break;
498     case Message::Server:
499       return tr("*"); break;
500     case Message::Info:
501       return tr("*"); break;
502     case Message::Error:
503       return tr("*"); break;
504     case Message::DayChange:
505       return tr("-"); break;
506     default:
507       return tr("%1").arg(plainSender());
508   }
509 }
510
511 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
512   switch(type()) {
513     case Message::Plain:
514       // To produce random like but stable nick colorings some sort of hashing should work best.
515       // In this case we just use the qt function qChecksum which produces a
516       // CRC16 hash. This should be fast and 16 bits are more than enough.
517       {
518         QString nick = nickFromMask(sender()).toLower();
519         if(!nick.isEmpty()) {
520           int chopCount = 0;
521           while(nick[nick.count() - 1 - chopCount] == '_') {
522             chopCount++;
523           }
524           nick.chop(chopCount);
525         }
526         quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
527         return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
528       }
529     case Message::Notice:
530       return UiStyle::NoticeMsg; break;
531     case Message::Topic:
532     case Message::Server:
533       return UiStyle::ServerMsg; break;
534     case Message::Error:
535       return UiStyle::ErrorMsg; break;
536     case Message::Join:
537       return UiStyle::JoinMsg; break;
538     case Message::Part:
539       return UiStyle::PartMsg; break;
540     case Message::Quit:
541       return UiStyle::QuitMsg; break;
542     case Message::Kick:
543       return UiStyle::KickMsg; break;
544     case Message::Nick:
545       return UiStyle::NickMsg; break;
546     case Message::Mode:
547       return UiStyle::ModeMsg; break;
548     case Message::Action:
549       return UiStyle::ActionMsg; break;
550     default:
551       return UiStyle::ErrorMsg;
552   }
553 }
554
555 // FIXME hardcoded to 16 sender hashes
556 quint8 UiStyle::StyledMessage::senderHash() const {
557   if(_senderHash != 0xff)
558     return _senderHash;
559
560   QString nick = nickFromMask(sender()).toLower();
561   if(!nick.isEmpty()) {
562     int chopCount = 0;
563     while(nick.at(nick.count() - 1 - chopCount) == '_')
564       chopCount++;
565     nick.chop(chopCount);
566   }
567   quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
568   return (_senderHash = (hash & 0xf) + 1);
569 }
570
571 /***********************************************************************************/
572
573 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
574   out << formatList.count();
575   UiStyle::FormatList::const_iterator it = formatList.begin();
576   while(it != formatList.end()) {
577     out << (*it).first << (*it).second;
578     ++it;
579   }
580   return out;
581 }
582
583 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
584   quint16 cnt;
585   in >> cnt;
586   for(quint16 i = 0; i < cnt; i++) {
587     quint16 pos; quint32 ftype;
588     in >> pos >> ftype;
589     formatList.append(qMakePair((quint16)pos, ftype));
590   }
591   return in;
592 }