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>
22 #include "qssparser.h"
25 #include "uisettings.h"
29 // register FormatList if that hasn't happened yet
30 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
31 if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
32 qRegisterMetaType<FormatList>("UiStyle::FormatList");
33 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
34 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
37 // Now initialize the mapping between FormatCodes and FormatTypes...
38 _formatCodes["%O"] = None;
39 _formatCodes["%B"] = Bold;
40 _formatCodes["%S"] = Italic;
41 _formatCodes["%U"] = Underline;
42 _formatCodes["%R"] = Reverse;
44 _formatCodes["%D0"] = PlainMsg;
45 _formatCodes["%Dn"] = NoticeMsg;
46 _formatCodes["%Ds"] = ServerMsg;
47 _formatCodes["%De"] = ErrorMsg;
48 _formatCodes["%Dj"] = JoinMsg;
49 _formatCodes["%Dp"] = PartMsg;
50 _formatCodes["%Dq"] = QuitMsg;
51 _formatCodes["%Dk"] = KickMsg;
52 _formatCodes["%Dr"] = RenameMsg;
53 _formatCodes["%Dm"] = ModeMsg;
54 _formatCodes["%Da"] = ActionMsg;
56 _formatCodes["%DT"] = Timestamp;
57 _formatCodes["%DS"] = Sender;
58 _formatCodes["%DN"] = Nick;
59 _formatCodes["%DH"] = Hostmask;
60 _formatCodes["%DC"] = ChannelName;
61 _formatCodes["%DM"] = ModeFlags;
62 _formatCodes["%DU"] = Url;
67 UiStyle::~ UiStyle() {
68 qDeleteAll(_metricsCache);
71 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
72 return _formatCache.value(key, QTextCharFormat());
75 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
76 return cachedFormat(formatType | ((quint64)messageLabel << 32));
79 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
80 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
83 // Merge a subelement format into an existing message format
84 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint32 label) {
85 quint64 key = ftype | ((quint64)label << 32);
87 // start with the most general format and then specialize
88 fmt.merge(cachedFormat(key & 0x00000000fffffff0)); // basic subelement format
89 fmt.merge(cachedFormat(key & 0x00000000ffffffff)); // subelement + msgtype
90 fmt.merge(cachedFormat(key & 0xffff0000fffffff0)); // subelement + nickhash
91 fmt.merge(cachedFormat(key & 0xffff0000ffffffff)); // subelement + nickhash + msgtype
92 fmt.merge(cachedFormat(key & 0x0000fffffffffff0)); // label + subelement
93 fmt.merge(cachedFormat(key & 0x0000ffffffffffff)); // label + subelement + msgtype
94 fmt.merge(cachedFormat(key & 0xfffffffffffffff0)); // label + subelement + nickhash
95 fmt.merge(cachedFormat(key & 0xffffffffffffffff)); // label + subelement + nickhash + msgtype
98 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
99 // until you _really_ know what you do!
100 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label) {
102 return QTextCharFormat();
104 quint64 key = ftype | ((quint64)label << 32);
106 // check if we have exactly this format readily cached already
107 QTextCharFormat fmt = cachedFormat(key);
111 fmt.merge(cachedFormat(key & 0x0000000000000000)); // basic
112 fmt.merge(cachedFormat(key & 0x000000000000000f)); // msgtype
113 fmt.merge(cachedFormat(key & 0x0000ffff00000000)); // label
114 fmt.merge(cachedFormat(key & 0x0000ffff0000000f)); // label + msgtype
116 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
117 // or "foreground 01 and background 03"
118 if((ftype & 0xfff0)) { // element format
119 for(quint32 mask = 0x10; mask <= 0x2000; mask <<= 1) {
121 mergeSubElementFormat(fmt, ftype & 0xffff, label);
126 // Now we handle color codes
127 if(ftype & 0x00400000)
128 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
129 if(ftype & 0x00800000)
130 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
131 if((ftype & 0x00c00000) == 0x00c00000)
132 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
136 mergeSubElementFormat(fmt, ftype & Url, label);
138 setCachedFormat(fmt, ftype, label);
142 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
143 // QFontMetricsF is not assignable, so we need to store pointers :/
144 quint64 key = ftype | ((quint64)label << 32);
146 if(_metricsCache.contains(key))
147 return _metricsCache.value(key);
149 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
152 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
153 if(_formatCodes.contains(code)) return _formatCodes.value(code);
157 QString UiStyle::formatCode(FormatType ftype) const {
158 return _formatCodes.key(ftype);
161 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
162 QList<QTextLayout::FormatRange> formatRanges;
163 QTextLayout::FormatRange range;
165 for(i = 0; i < formatList.count(); i++) {
166 range.format = format(formatList.at(i).second);
167 range.start = formatList.at(i).first;
168 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
169 formatRanges.append(range);
171 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
175 // This method expects a well-formatted string, there is no error checking!
176 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
177 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
179 if(s.length() > 65535) {
180 qWarning() << QString("String too long to be styled: %1").arg(s);
181 return StyledString();
184 result.formatList.append(qMakePair((quint16)0, (quint32)None));
185 quint32 curfmt = (quint32)None;
186 int pos = 0; quint16 length = 0;
188 pos = s.indexOf('%', pos);
190 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
195 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
196 if(s[pos+3] == '-') { // color off
197 curfmt &= 0x003fffff;
200 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
201 //TODO: use 99 as transparent color (re mirc color "standard")
203 if(s[pos+3] == 'f') {
204 curfmt &= 0xf0ffffff;
205 curfmt |= (color << 24) | 0x00400000;
207 curfmt &= 0x0fffffff;
208 curfmt |= (color << 28) | 0x00800000;
212 } else if(s[pos+1] == 'O') { // reset formatting
213 curfmt &= 0x0000000f; // we keep message type-specific formatting
215 } else if(s[pos+1] == 'R') { // reverse
216 // TODO: implement reverse formatting
219 } else { // all others are toggles
220 QString code = QString("%") + s[pos+1];
221 if(s[pos+1] == 'D') code += s[pos+2];
222 FormatType ftype = formatType(code);
223 if(ftype == Invalid) {
224 qWarning() << (QString("Invalid format code in string: %1").arg(s));
228 length = code.length();
230 s.remove(pos, length);
231 if(pos == result.formatList.last().first)
232 result.formatList.last().second = curfmt;
234 result.formatList.append(qMakePair((quint16)pos, curfmt));
236 result.plainText = s;
240 QString UiStyle::mircToInternal(const QString &mirc_) const {
241 QString mirc = mirc_;
242 mirc.replace('%', "%%"); // escape % just to be sure
243 mirc.replace('\x02', "%B");
244 mirc.replace('\x0f', "%O");
245 mirc.replace('\x12', "%R");
246 mirc.replace('\x16', "%R");
247 mirc.replace('\x1d', "%S");
248 mirc.replace('\x1f', "%U");
250 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
251 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
252 // %Dc- turns color off.
253 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
254 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
257 pos = mirc.indexOf('\x03', pos);
258 if(pos < 0) break; // no more mirc color codes
260 int l = mirc.length();
262 // check for fg color
263 if(i < l && mirc[i].isDigit()) {
265 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
266 else num.prepend('0');
267 ins = QString("%Dcf%1").arg(num);
269 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
272 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
273 else num.prepend('0');
274 ins += QString("%Dcb%1").arg(num);
279 mirc.replace(pos, i-pos, ins);
284 /***********************************************************************************/
285 UiStyle::StyledMessage::StyledMessage(const Message &msg)
290 void UiStyle::StyledMessage::style(UiStyle *style) const {
291 QString user = userFromMask(sender());
292 QString host = hostFromMask(sender());
293 QString nick = nickFromMask(sender());
294 QString txt = style->mircToInternal(contents());
295 QString bufferName = bufferInfo().bufferName();
296 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
301 t = tr("%D0%1").arg(txt); break;
302 case Message::Notice:
303 t = tr("%Dn%1").arg(txt); break;
305 case Message::Server:
306 t = tr("%Ds%1").arg(txt); break;
308 t = tr("%De%1").arg(txt); break;
310 t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
312 t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
313 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
316 t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
317 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
319 case Message::Kick: {
320 QString victim = txt.section(" ", 0, 0);
321 QString kickmsg = txt.section(" ", 1);
322 t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
323 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
327 if(nick == contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
328 else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
331 if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
332 else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
334 case Message::Action:
335 t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
338 t = tr("%De[%1]").arg(txt);
340 _contents = style->styleString(t);
343 QString UiStyle::StyledMessage::decoratedTimestamp() const {
344 return QString("[%1]").arg(timestamp().toLocalTime().toString("hh:mm:ss"));
347 QString UiStyle::StyledMessage::plainSender() const {
350 case Message::Notice:
351 return nickFromMask(sender());
357 QString UiStyle::StyledMessage::decoratedSender() const {
360 return tr("<%1>").arg(plainSender()); break;
361 case Message::Notice:
362 return tr("[%1]").arg(plainSender()); break;
364 case Message::Server:
365 return tr("*"); break;
367 return tr("*"); break;
369 return tr("-->"); break;
371 return tr("<--"); break;
373 return tr("<--"); break;
375 return tr("<-*"); break;
377 return tr("<->"); break;
379 return tr("***"); break;
380 case Message::Action:
381 return tr("-*-"); break;
383 return tr("%1").arg(plainSender());
387 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
390 // To produce random like but stable nick colorings some sort of hashing should work best.
391 // In this case we just use the qt function qChecksum which produces a
392 // CRC16 hash. This should be fast and 16 bits are more than enough.
394 QString nick = nickFromMask(sender()).toLower();
395 if(!nick.isEmpty()) {
397 while(nick[nick.count() - 1 - chopCount] == '_') {
400 nick.chop(chopCount);
402 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
403 return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
405 case Message::Notice:
406 return UiStyle::NoticeMsg; break;
408 case Message::Server:
409 return UiStyle::ServerMsg; break;
411 return UiStyle::ErrorMsg; break;
413 return UiStyle::JoinMsg; break;
415 return UiStyle::PartMsg; break;
417 return UiStyle::QuitMsg; break;
419 return UiStyle::KickMsg; break;
421 return UiStyle::RenameMsg; break;
423 return UiStyle::ModeMsg; break;
424 case Message::Action:
425 return UiStyle::ActionMsg; break;
427 return UiStyle::ErrorMsg;
432 /***********************************************************************************/
434 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
435 out << formatList.count();
436 UiStyle::FormatList::const_iterator it = formatList.begin();
437 while(it != formatList.end()) {
438 out << (*it).first << (*it).second;
444 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
447 for(quint16 i = 0; i < cnt; i++) {
448 quint16 pos; quint32 ftype;
450 formatList.append(qMakePair((quint16)pos, ftype));
455 /***********************************************************************************/
456 // Stylesheet handling
457 /***********************************************************************************/
459 void UiStyle::loadStyleSheet() {
461 parser.loadStyleSheet(qApp->styleSheet());
463 // TODO handle results
464 QApplication::setPalette(parser.palette());
466 qDeleteAll(_metricsCache);
467 _metricsCache.clear();
468 _formatCache = parser.formats();