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 // TODO: implement setting for nick autocoloring and make a check for it here
132 if ( (ftype & 0x00000fff) == Sender )
134 // If it is not enabled just set ftype to Sender and go on
137 if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
138 else return _defaultFormats.value(ftype, QTextCharFormat());
141 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
142 // until you _really_ know what you do!
143 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
144 if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
145 if(ftype == Invalid) return QTextCharFormat();
146 // Now we construct the merged format, starting with the default
147 QTextCharFormat fmt = format(None);
148 // First: general message format
149 fmt.merge(format((FormatType)(ftype & 0x0f)));
150 // now more specific ones
151 for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
152 if(ftype & mask) fmt.merge(format((FormatType)mask));
155 if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
156 if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
157 // Sender auto colors
158 if((ftype & 0xfff) == 0x200 && (ftype & 0xff000200) != 0x200) fmt.merge(format((FormatType)(ftype & 0xff000200)));
160 if(ftype & Url) fmt.merge(format(Url));
161 return _cachedFormats[ftype] = fmt;
164 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
165 // QFontMetricsF is not assignable, so we need to store pointers :/
166 if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
167 return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
170 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
171 if(_formatCodes.contains(code)) return _formatCodes.value(code);
175 QString UiStyle::formatCode(FormatType ftype) const {
176 return _formatCodes.key(ftype);
179 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
180 QList<QTextLayout::FormatRange> formatRanges;
181 QTextLayout::FormatRange range;
183 for(i = 0; i < formatList.count(); i++) {
184 range.format = mergedFormat(formatList.at(i).second);
185 range.start = formatList.at(i).first;
186 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
187 formatRanges.append(range);
189 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
193 // This method expects a well-formatted string, there is no error checking!
194 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
195 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
197 if(s.length() > 65535) {
198 qWarning() << QString("String too long to be styled: %1").arg(s);
199 return StyledString();
202 result.formatList.append(qMakePair((quint16)0, (quint32)None));
203 quint32 curfmt = (quint32)None;
204 int pos = 0; quint16 length = 0;
206 pos = s.indexOf('%', pos);
208 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
213 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
214 if(s[pos+3] == '-') { // color off
215 curfmt &= 0x003fffff;
218 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
219 //TODO: use 99 as transparent color (re mirc color "standard")
221 if(s[pos+3] == 'f') {
222 curfmt &= 0xf0ffffff;
223 curfmt |= (color << 24) | 0x00400000;
225 curfmt &= 0x0fffffff;
226 curfmt |= (color << 28) | 0x00800000;
230 } else if(s[pos+1] == 'O') { // reset formatting
231 curfmt &= 0x0000000f; // we keep message type-specific formatting
233 } else if(s[pos+1] == 'R') { // reverse
234 // TODO: implement reverse formatting
237 } else { // all others are toggles
238 QString code = QString("%") + s[pos+1];
239 if(s[pos+1] == 'D') code += s[pos+2];
240 FormatType ftype = formatType(code);
241 if(ftype == Invalid) {
242 qWarning() << (QString("Invalid format code in string: %1").arg(s));
246 length = code.length();
248 s.remove(pos, length);
249 if(pos == result.formatList.last().first)
250 result.formatList.last().second = curfmt;
252 result.formatList.append(qMakePair((quint16)pos, curfmt));
254 result.plainText = s;
258 QString UiStyle::mircToInternal(const QString &mirc_) const {
259 QString mirc = mirc_;
260 mirc.replace('%', "%%"); // escape % just to be sure
261 mirc.replace('\x02', "%B");
262 mirc.replace('\x0f', "%O");
263 mirc.replace('\x12', "%R");
264 mirc.replace('\x16', "%R");
265 mirc.replace('\x1d', "%S");
266 mirc.replace('\x1f', "%U");
268 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
269 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
270 // %Dc- turns color off.
271 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
272 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
275 pos = mirc.indexOf('\x03', pos);
276 if(pos < 0) break; // no more mirc color codes
278 int l = mirc.length();
280 // check for fg color
281 if(i < l && mirc[i].isDigit()) {
283 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
284 else num.prepend('0');
285 ins = QString("%Dcf%1").arg(num);
287 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
290 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
291 else num.prepend('0');
292 ins += QString("%Dcb%1").arg(num);
297 mirc.replace(pos, i-pos, ins);
302 /***********************************************************************************/
303 UiStyle::StyledMessage::StyledMessage(const Message &msg)
308 void UiStyle::StyledMessage::style(UiStyle *style) const {
309 QString user = userFromMask(sender());
310 QString host = hostFromMask(sender());
311 QString nick = nickFromMask(sender());
312 QString txt = style->mircToInternal(contents());
313 QString bufferName = bufferInfo().bufferName();
314 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
319 t = tr("%D0%1").arg(txt); break;
320 case Message::Notice:
321 t = tr("%Dn%1").arg(txt); break;
322 case Message::Server:
323 t = tr("%Ds%1").arg(txt); break;
325 t = tr("%De%1").arg(txt); break;
327 t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
329 t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
330 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
333 t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
334 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
336 case Message::Kick: {
337 QString victim = txt.section(" ", 0, 0);
338 QString kickmsg = txt.section(" ", 1);
339 t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
340 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
344 if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
345 else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
348 if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
349 else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
351 case Message::Action:
352 t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
355 t = tr("%De[%1]").arg(txt);
357 _contents = style->styleString(t);
360 QString UiStyle::StyledMessage::decoratedTimestamp() const {
361 return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
364 QString UiStyle::StyledMessage::plainSender() const {
367 case Message::Notice:
368 return nickFromMask(sender());
374 QString UiStyle::StyledMessage::decoratedSender() const {
377 return tr("<%1>").arg(plainSender()); break;
378 case Message::Notice:
379 return tr("[%1]").arg(plainSender()); break;
380 case Message::Server:
381 return tr("*"); break;
383 return tr("*"); break;
385 return tr("-->"); break;
387 return tr("<--"); break;
389 return tr("<--"); break;
391 return tr("<-*"); break;
393 return tr("<->"); break;
395 return tr("***"); break;
396 case Message::Action:
397 return tr("-*-"); break;
399 return tr("%1").arg(plainSender());
403 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
407 // To produce random like but stable nick colorings some sort of hashing should work best.
408 // In this case we just use the qt function qChecksum which produces a
409 // CRC16 hash. This should be fast and 16 bits are more than enough.
410 hash = qChecksum(_sender.toAscii().data(), _sender.toAscii().size());
411 return (UiStyle::FormatType)((((hash % 21) + 1) << 24) + 0x200);
412 case Message::Notice:
413 return UiStyle::NoticeMsg; break;
414 case Message::Server:
415 return UiStyle::ServerMsg; break;
417 return UiStyle::ErrorMsg; break;
419 return UiStyle::JoinMsg; break;
421 return UiStyle::PartMsg; break;
423 return UiStyle::QuitMsg; break;
425 return UiStyle::KickMsg; break;
427 return UiStyle::RenameMsg; break;
429 return UiStyle::ModeMsg; break;
430 case Message::Action:
431 return UiStyle::ActionMsg; break;
433 return UiStyle::ErrorMsg;
438 /***********************************************************************************/
440 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
441 out << formatList.count();
442 UiStyle::FormatList::const_iterator it = formatList.begin();
443 while(it != formatList.end()) {
444 out << (*it).first << (*it).second;
450 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
453 for(quint16 i = 0; i < cnt; i++) {
454 quint16 pos; quint32 ftype;
456 formatList.append(qMakePair((quint16)pos, ftype));