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