1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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>
24 #include "uisettings.h"
27 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
28 // register FormatList if that hasn't happened yet
29 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
30 if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
31 qRegisterMetaType<FormatList>("UiStyle::FormatList");
32 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
33 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
36 _defaultFont = QFont("Monospace", QApplication::font().pointSize());
39 _defaultPlainFormat.setForeground(QBrush("#000000"));
40 _defaultPlainFormat.setFont(_defaultFont);
41 _defaultPlainFormat.font().setFixedPitch(true);
42 _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
43 setFormat(None, _defaultPlainFormat, Settings::Default);
45 // Load saved custom formats
46 UiStyleSettings s(_settingsKey);
47 foreach(FormatType type, s.availableFormats()) {
48 _customFormats[type] = s.customFormat(type);
51 // Now initialize the mapping between FormatCodes and FormatTypes...
52 _formatCodes["%O"] = None;
53 _formatCodes["%B"] = Bold;
54 _formatCodes["%S"] = Italic;
55 _formatCodes["%U"] = Underline;
56 _formatCodes["%R"] = Reverse;
58 _formatCodes["%D0"] = PlainMsg;
59 _formatCodes["%Dn"] = NoticeMsg;
60 _formatCodes["%Ds"] = ServerMsg;
61 _formatCodes["%De"] = ErrorMsg;
62 _formatCodes["%Dj"] = JoinMsg;
63 _formatCodes["%Dp"] = PartMsg;
64 _formatCodes["%Dq"] = QuitMsg;
65 _formatCodes["%Dk"] = KickMsg;
66 _formatCodes["%Dr"] = RenameMsg;
67 _formatCodes["%Dm"] = ModeMsg;
68 _formatCodes["%Da"] = ActionMsg;
70 _formatCodes["%DT"] = Timestamp;
71 _formatCodes["%DS"] = Sender;
72 _formatCodes["%DN"] = Nick;
73 _formatCodes["%DH"] = Hostmask;
74 _formatCodes["%DC"] = ChannelName;
75 _formatCodes["%DM"] = ModeFlags;
76 _formatCodes["%DU"] = Url;
78 // Initialize color codes according to mIRC "standard"
80 //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
81 //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
82 colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
83 colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
86 for(int i = 0; i < 16; i++) {
87 QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
88 _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
89 _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
90 QTextCharFormat fgf, bgf;
91 fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
92 bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
95 // Set a few more standard formats
96 QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
97 setFormat(Bold, bold, Settings::Default);
99 QTextCharFormat italic; italic.setFontItalic(true);
100 setFormat(Italic, italic, Settings::Default);
102 QTextCharFormat underline; underline.setFontUnderline(true);
103 setFormat(Underline, underline, Settings::Default);
105 // All other formats should be defined in derived classes.
108 UiStyle::~ UiStyle() {
109 qDeleteAll(_cachedFontMetrics);
112 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
113 if(mode == Settings::Default) {
114 _defaultFormats[ftype] = fmt;
116 UiStyleSettings s(_settingsKey);
117 if(fmt != _defaultFormats[ftype]) {
118 _customFormats[ftype] = fmt;
119 s.setCustomFormat(ftype, fmt);
121 _customFormats.remove(ftype);
122 s.removeCustomFormat(ftype);
125 // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
126 _cachedFormats.clear();
127 _cachedFontMetrics.clear();
130 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
131 if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
132 else return _defaultFormats.value(ftype, QTextCharFormat());
135 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
136 // until you _really_ know what you do!
137 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
138 if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
139 if(ftype == Invalid) return QTextCharFormat();
140 // Now we construct the merged format, starting with the default
141 QTextCharFormat fmt = format(None);
142 // First: general message format
143 fmt.merge(format((FormatType)(ftype & 0x0f)));
144 // now more specific ones
145 for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
146 if(ftype & mask) fmt.merge(format((FormatType)mask));
149 if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
150 if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
152 if(ftype & Url) fmt.merge(format(Url));
153 return _cachedFormats[ftype] = fmt;
156 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
157 // QFontMetricsF is not assignable, so we need to store pointers :/
158 if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
159 return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
162 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
163 if(_formatCodes.contains(code)) return _formatCodes.value(code);
167 QString UiStyle::formatCode(FormatType ftype) const {
168 return _formatCodes.key(ftype);
171 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
172 QList<QTextLayout::FormatRange> formatRanges;
173 QTextLayout::FormatRange range;
175 for(i = 0; i < formatList.count(); i++) {
176 range.format = mergedFormat(formatList.at(i).second);
177 range.start = formatList.at(i).first;
178 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
179 formatRanges.append(range);
181 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
185 // This method expects a well-formatted string, there is no error checking!
186 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
187 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
189 if(s.length() > 65535) {
190 qWarning() << QString("String too long to be styled: %1").arg(s);
191 return StyledString();
194 result.formatList.append(qMakePair((quint16)0, (quint32)None));
195 quint32 curfmt = (quint32)None;
196 int pos = 0; quint16 length = 0;
198 pos = s.indexOf('%', pos);
200 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
205 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
206 if(s[pos+3] == '-') { // color off
207 curfmt &= 0x003fffff;
210 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
211 //TODO: use 99 as transparent color (re mirc color "standard")
213 if(s[pos+3] == 'f') {
214 curfmt &= 0xf0ffffff;
215 curfmt |= (color << 24) | 0x00400000;
217 curfmt &= 0x0fffffff;
218 curfmt |= (color << 28) | 0x00800000;
222 } else if(s[pos+1] == 'O') { // reset formatting
223 curfmt &= 0x0000000f; // we keep message type-specific formatting
225 } else if(s[pos+1] == 'R') { // reverse
226 // TODO: implement reverse formatting
229 } else { // all others are toggles
230 QString code = QString("%") + s[pos+1];
231 if(s[pos+1] == 'D') code += s[pos+2];
232 FormatType ftype = formatType(code);
233 if(ftype == Invalid) {
234 qWarning() << (QString("Invalid format code in string: %1").arg(s));
238 length = code.length();
240 s.remove(pos, length);
241 if(pos == result.formatList.last().first)
242 result.formatList.last().second = curfmt;
244 result.formatList.append(qMakePair((quint16)pos, curfmt));
246 result.plainText = s;
250 QString UiStyle::mircToInternal(const QString &mirc_) const {
251 QString mirc = mirc_;
252 mirc.replace('%', "%%"); // escape % just to be sure
253 mirc.replace('\x02', "%B");
254 mirc.replace('\x0f', "%O");
255 mirc.replace('\x12', "%R");
256 mirc.replace('\x16', "%R");
257 mirc.replace('\x1d', "%S");
258 mirc.replace('\x1f', "%U");
260 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
261 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
262 // %Dc- turns color off.
263 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
264 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
267 pos = mirc.indexOf('\x03', pos);
268 if(pos < 0) break; // no more mirc color codes
270 int l = mirc.length();
272 // check for fg color
273 if(i < l && mirc[i].isDigit()) {
275 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
276 else num.prepend('0');
277 ins = QString("%Dcf%1").arg(num);
279 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
282 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
283 else num.prepend('0');
284 ins += QString("%Dcb%1").arg(num);
289 mirc.replace(pos, i-pos, ins);
294 /***********************************************************************************/
295 UiStyle::StyledMessage::StyledMessage(const Message &msg)
300 void UiStyle::StyledMessage::style(UiStyle *style) const {
301 QString user = userFromMask(sender());
302 QString host = hostFromMask(sender());
303 QString nick = nickFromMask(sender());
304 QString txt = style->mircToInternal(contents());
305 QString bufferName = bufferInfo().bufferName();
306 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
311 t = tr("%D0%1").arg(txt); break;
312 case Message::Notice:
313 t = tr("%Dn%1").arg(txt); break;
314 case Message::Server:
315 t = tr("%Ds%1").arg(txt); break;
317 t = tr("%De%1").arg(txt); break;
319 t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
321 t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
322 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
325 t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
326 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
328 case Message::Kick: {
329 QString victim = txt.section(" ", 0, 0);
330 QString kickmsg = txt.section(" ", 1);
331 t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
332 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
336 if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
337 else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
340 if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
341 else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
343 case Message::Action:
344 t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
347 t = tr("%De[%1]").arg(txt);
349 _contents = style->styleString(t);
352 QString UiStyle::StyledMessage::decoratedTimestamp() const {
353 return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
356 QString UiStyle::StyledMessage::plainSender() const {
359 case Message::Notice:
360 return nickFromMask(sender());
366 QString UiStyle::StyledMessage::decoratedSender() const {
369 return tr("<%1>").arg(plainSender()); break;
370 case Message::Notice:
371 return tr("[%1]").arg(plainSender()); break;
372 case Message::Server:
373 return tr("*"); break;
375 return tr("*"); break;
377 return tr("-->"); break;
379 return tr("<--"); break;
381 return tr("<--"); break;
383 return tr("<-*"); break;
385 return tr("<->"); break;
387 return tr("***"); break;
388 case Message::Action:
389 return tr("-*-"); break;
391 return tr("%1").arg(plainSender());
395 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
398 return UiStyle::Sender; break;
399 case Message::Notice:
400 return UiStyle::NoticeMsg; break;
401 case Message::Server:
402 return UiStyle::ServerMsg; break;
404 return UiStyle::ErrorMsg; break;
406 return UiStyle::JoinMsg; break;
408 return UiStyle::PartMsg; break;
410 return UiStyle::QuitMsg; break;
412 return UiStyle::KickMsg; break;
414 return UiStyle::RenameMsg; break;
416 return UiStyle::ModeMsg; break;
417 case Message::Action:
418 return UiStyle::ActionMsg; break;
420 return UiStyle::ErrorMsg;
425 /***********************************************************************************/
427 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
428 out << formatList.count();
429 UiStyle::FormatList::const_iterator it = formatList.begin();
430 while(it != formatList.end()) {
431 out << (*it).first << (*it).second;
437 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
440 for(quint16 i = 0; i < cnt; i++) {
441 quint16 pos; quint32 ftype;
443 formatList.append(qMakePair((quint16)pos, ftype));