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 // Check for the sender auto coloring option
52 _senderAutoColor = s.value("Colors/SenderAutoColor", false).toBool();
54 // Now initialize the mapping between FormatCodes and FormatTypes...
55 _formatCodes["%O"] = None;
56 _formatCodes["%B"] = Bold;
57 _formatCodes["%S"] = Italic;
58 _formatCodes["%U"] = Underline;
59 _formatCodes["%R"] = Reverse;
61 _formatCodes["%D0"] = PlainMsg;
62 _formatCodes["%Dn"] = NoticeMsg;
63 _formatCodes["%Ds"] = ServerMsg;
64 _formatCodes["%De"] = ErrorMsg;
65 _formatCodes["%Dj"] = JoinMsg;
66 _formatCodes["%Dp"] = PartMsg;
67 _formatCodes["%Dq"] = QuitMsg;
68 _formatCodes["%Dk"] = KickMsg;
69 _formatCodes["%Dr"] = RenameMsg;
70 _formatCodes["%Dm"] = ModeMsg;
71 _formatCodes["%Da"] = ActionMsg;
73 _formatCodes["%DT"] = Timestamp;
74 _formatCodes["%DS"] = Sender;
75 _formatCodes["%DN"] = Nick;
76 _formatCodes["%DH"] = Hostmask;
77 _formatCodes["%DC"] = ChannelName;
78 _formatCodes["%DM"] = ModeFlags;
79 _formatCodes["%DU"] = Url;
81 // Initialize color codes according to mIRC "standard"
83 //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
84 //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
85 colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
86 colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
89 for(int i = 0; i < 16; i++) {
90 QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
91 _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
92 _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
93 QTextCharFormat fgf, bgf;
94 fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
95 bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
98 // Set a few more standard formats
99 QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
100 setFormat(Bold, bold, Settings::Default);
102 QTextCharFormat italic; italic.setFontItalic(true);
103 setFormat(Italic, italic, Settings::Default);
105 QTextCharFormat underline; underline.setFontUnderline(true);
106 setFormat(Underline, underline, Settings::Default);
108 // All other formats should be defined in derived classes.
111 UiStyle::~ UiStyle() {
112 qDeleteAll(_cachedFontMetrics);
115 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
116 if(mode == Settings::Default) {
117 _defaultFormats[ftype] = fmt;
119 UiStyleSettings s(_settingsKey);
120 if(fmt != _defaultFormats[ftype]) {
121 _customFormats[ftype] = fmt;
122 s.setCustomFormat(ftype, fmt);
124 _customFormats.remove(ftype);
125 s.removeCustomFormat(ftype);
128 // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
129 _cachedFormats.clear();
130 _cachedFontMetrics.clear();
133 void UiStyle::setSenderAutoColor( bool state ) {
134 _senderAutoColor = state;
135 UiStyleSettings s(_settingsKey);
136 s.setValue("Colors/SenderAutoColor", QVariant(state));
139 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
140 // Check for enabled sender auto coloring
141 if ( (ftype & 0x00000fff) == Sender && !_senderAutoColor ) {
142 // Just use the default sender style if auto coloring is disabled
146 if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
147 else return _defaultFormats.value(ftype, QTextCharFormat());
150 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
151 // until you _really_ know what you do!
152 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
153 if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
154 if(ftype == Invalid) return QTextCharFormat();
155 // Now we construct the merged format, starting with the default
156 QTextCharFormat fmt = format(None);
157 // First: general message format
158 fmt.merge(format((FormatType)(ftype & 0x0f)));
159 // now more specific ones
160 for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
161 if(ftype & mask) fmt.merge(format((FormatType)mask));
164 if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
165 if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
166 // Sender auto colors
167 if((ftype & 0xfff) == 0x200 && (ftype & 0xff000200) != 0x200) fmt.merge(format((FormatType)(ftype & 0xff000200)));
169 if(ftype & Url) fmt.merge(format(Url));
170 return _cachedFormats[ftype] = fmt;
173 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
174 // QFontMetricsF is not assignable, so we need to store pointers :/
175 if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
176 return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
179 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
180 if(_formatCodes.contains(code)) return _formatCodes.value(code);
184 QString UiStyle::formatCode(FormatType ftype) const {
185 return _formatCodes.key(ftype);
188 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
189 QList<QTextLayout::FormatRange> formatRanges;
190 QTextLayout::FormatRange range;
192 for(i = 0; i < formatList.count(); i++) {
193 range.format = mergedFormat(formatList.at(i).second);
194 range.start = formatList.at(i).first;
195 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
196 formatRanges.append(range);
198 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
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_) {
206 if(s.length() > 65535) {
207 qWarning() << QString("String too long to be styled: %1").arg(s);
208 return StyledString();
211 result.formatList.append(qMakePair((quint16)0, (quint32)None));
212 quint32 curfmt = (quint32)None;
213 int pos = 0; quint16 length = 0;
215 pos = s.indexOf('%', pos);
217 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
222 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
223 if(s[pos+3] == '-') { // color off
224 curfmt &= 0x003fffff;
227 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
228 //TODO: use 99 as transparent color (re mirc color "standard")
230 if(s[pos+3] == 'f') {
231 curfmt &= 0xf0ffffff;
232 curfmt |= (color << 24) | 0x00400000;
234 curfmt &= 0x0fffffff;
235 curfmt |= (color << 28) | 0x00800000;
239 } else if(s[pos+1] == 'O') { // reset formatting
240 curfmt &= 0x0000000f; // we keep message type-specific formatting
242 } else if(s[pos+1] == 'R') { // reverse
243 // TODO: implement reverse formatting
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));
255 length = code.length();
257 s.remove(pos, length);
258 if(pos == result.formatList.last().first)
259 result.formatList.last().second = curfmt;
261 result.formatList.append(qMakePair((quint16)pos, curfmt));
263 result.plainText = s;
267 QString UiStyle::mircToInternal(const QString &mirc_) const {
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");
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).
284 pos = mirc.indexOf('\x03', pos);
285 if(pos < 0) break; // no more mirc color codes
287 int l = mirc.length();
289 // check for fg color
290 if(i < l && mirc[i].isDigit()) {
292 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
293 else num.prepend('0');
294 ins = QString("%Dcf%1").arg(num);
296 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
299 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
300 else num.prepend('0');
301 ins += QString("%Dcb%1").arg(num);
306 mirc.replace(pos, i-pos, ins);
311 /***********************************************************************************/
312 UiStyle::StyledMessage::StyledMessage(const Message &msg)
317 void UiStyle::StyledMessage::style(UiStyle *style) const {
318 QString user = userFromMask(sender());
319 QString host = hostFromMask(sender());
320 QString nick = nickFromMask(sender());
321 QString txt = style->mircToInternal(contents());
322 QString bufferName = bufferInfo().bufferName();
323 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
328 t = tr("%D0%1").arg(txt); break;
329 case Message::Notice:
330 t = tr("%Dn%1").arg(txt); break;
331 case Message::Server:
332 t = tr("%Ds%1").arg(txt); break;
334 t = tr("%De%1").arg(txt); break;
336 t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
338 t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
339 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
342 t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
343 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
345 case Message::Kick: {
346 QString victim = txt.section(" ", 0, 0);
347 QString kickmsg = txt.section(" ", 1);
348 t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
349 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
353 if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
354 else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
357 if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
358 else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
360 case Message::Action:
361 t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
364 t = tr("%De[%1]").arg(txt);
366 _contents = style->styleString(t);
369 QString UiStyle::StyledMessage::decoratedTimestamp() const {
370 return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
373 QString UiStyle::StyledMessage::plainSender() const {
376 case Message::Notice:
377 return nickFromMask(sender());
383 QString UiStyle::StyledMessage::decoratedSender() const {
386 return tr("<%1>").arg(plainSender()); break;
387 case Message::Notice:
388 return tr("[%1]").arg(plainSender()); break;
389 case Message::Server:
390 return tr("*"); break;
392 return tr("*"); break;
394 return tr("-->"); break;
396 return tr("<--"); break;
398 return tr("<--"); break;
400 return tr("<-*"); break;
402 return tr("<->"); break;
404 return tr("***"); break;
405 case Message::Action:
406 return tr("-*-"); break;
408 return tr("%1").arg(plainSender());
412 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
416 // To produce random like but stable nick colorings some sort of hashing should work best.
417 // In this case we just use the qt function qChecksum which produces a
418 // CRC16 hash. This should be fast and 16 bits are more than enough.
419 hash = qChecksum(sender().toAscii().data(), sender().toAscii().size());
420 return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
421 case Message::Notice:
422 return UiStyle::NoticeMsg; break;
423 case Message::Server:
424 return UiStyle::ServerMsg; break;
426 return UiStyle::ErrorMsg; break;
428 return UiStyle::JoinMsg; break;
430 return UiStyle::PartMsg; break;
432 return UiStyle::QuitMsg; break;
434 return UiStyle::KickMsg; break;
436 return UiStyle::RenameMsg; break;
438 return UiStyle::ModeMsg; break;
439 case Message::Action:
440 return UiStyle::ActionMsg; break;
442 return UiStyle::ErrorMsg;
447 /***********************************************************************************/
449 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
450 out << formatList.count();
451 UiStyle::FormatList::const_iterator it = formatList.begin();
452 while(it != formatList.end()) {
453 out << (*it).first << (*it).second;
459 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
462 for(quint16 i = 0; i < cnt; i++) {
463 quint16 pos; quint32 ftype;
465 formatList.append(qMakePair((quint16)pos, ftype));