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"
28 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
29 QString UiStyle::_timestampFormatString;
31 UiStyle::UiStyle(QObject *parent) : QObject(parent) {
32 // register FormatList if that hasn't happened yet
33 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
34 if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
35 qRegisterMetaType<FormatList>("UiStyle::FormatList");
36 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
37 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
40 // Now initialize the mapping between FormatCodes and FormatTypes...
41 _formatCodes["%O"] = None;
42 _formatCodes["%B"] = Bold;
43 _formatCodes["%S"] = Italic;
44 _formatCodes["%U"] = Underline;
45 _formatCodes["%R"] = Reverse;
47 _formatCodes["%DN"] = Nick;
48 _formatCodes["%DH"] = Hostmask;
49 _formatCodes["%DC"] = ChannelName;
50 _formatCodes["%DM"] = ModeFlags;
51 _formatCodes["%DU"] = Url;
53 setTimestampFormatString("[hh:mm:ss]");
58 qDeleteAll(_metricsCache);
61 void UiStyle::loadStyleSheet() {
62 qDeleteAll(_metricsCache);
63 _metricsCache.clear();
69 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("default.qss"));
70 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
71 if(s.value("UseCustomStyleSheet", false).toBool())
72 styleSheet += loadStyleSheet("file:///" + s.value("CustomStyleSheetPath").toString(), true);
73 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
75 if(styleSheet.isEmpty())
79 parser.processStyleSheet(styleSheet);
80 QApplication::setPalette(parser.palette());
81 _formatCache = parser.formats();
83 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
88 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist) {
89 QString ss = styleSheet;
90 if(ss.startsWith("file:///")) {
96 if(file.open(QFile::ReadOnly)) {
97 QTextStream stream(&file);
98 ss = stream.readAll();
102 qWarning() << "Could not open stylesheet file:" << file.fileName();
109 void UiStyle::setTimestampFormatString(const QString &format) {
110 if(_timestampFormatString != format) {
111 _timestampFormatString = format;
116 /******** Caching *******/
118 QTextCharFormat UiStyle::cachedFormat(quint64 key) const {
119 return _formatCache.value(key, QTextCharFormat());
122 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
123 return cachedFormat(formatType | ((quint64)messageLabel << 32));
126 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
127 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
130 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
131 // QFontMetricsF is not assignable, so we need to store pointers :/
132 quint64 key = ftype | ((quint64)label << 32);
134 if(_metricsCache.contains(key))
135 return _metricsCache.value(key);
137 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
140 /******** Generate formats ********/
142 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
143 // until you _really_ know what you do!
144 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) {
146 return QTextCharFormat();
148 quint64 label = (quint64)label_ << 32;
150 // check if we have exactly this format readily cached already
151 QTextCharFormat fmt = cachedFormat(label|ftype);
152 if(fmt.properties().count())
155 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
157 for(quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<=1) {
159 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
162 setCachedFormat(fmt, ftype, label_);
166 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) {
167 mergeSubElementFormat(fmt, ftype & 0x000f, label);
169 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
170 // or "foreground 01 and background 03"
171 if((ftype & 0xfff0)) { // element format
172 for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
174 mergeSubElementFormat(fmt, mask | 0x0f, label);
179 // Now we handle color codes
180 // We assume that those can't be combined with subelement and message types.
181 if(ftype & 0x00400000)
182 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
183 if(ftype & 0x00800000)
184 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
185 if((ftype & 0x00c00000) == 0x00c00000)
186 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
190 mergeSubElementFormat(fmt, ftype & Url, label);
193 // Merge a subelement format into an existing message format
194 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint64 label) {
195 quint64 key = ftype | label;
196 fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000fffffffffff0))); // label + subelement
197 fmt.merge(cachedFormat(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
198 fmt.merge(cachedFormat(key & Q_UINT64_C(0xfffffffffffffff0))); // label + subelement + nickhash
199 fmt.merge(cachedFormat(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
202 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) {
206 case Message::Notice:
208 case Message::Action:
224 case Message::Server:
230 case Message::DayChange:
233 Q_ASSERT(false); // we need to handle all message types
237 UiStyle::FormatType UiStyle::formatType(const QString & code) {
238 if(_formatCodes.contains(code)) return _formatCodes.value(code);
242 QString UiStyle::formatCode(FormatType ftype) {
243 return _formatCodes.key(ftype);
246 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) {
247 QList<QTextLayout::FormatRange> formatRanges;
248 QTextLayout::FormatRange range;
250 for(i = 0; i < formatList.count(); i++) {
251 range.format = format(formatList.at(i).second, messageLabel);
252 range.start = formatList.at(i).first;
253 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
254 formatRanges.append(range);
256 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
260 // This method expects a well-formatted string, there is no error checking!
261 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
262 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
264 if(s.length() > 65535) {
265 qWarning() << QString("String too long to be styled: %1").arg(s);
266 return StyledString();
269 result.formatList.append(qMakePair((quint16)0, baseFormat));
270 quint32 curfmt = baseFormat;
271 int pos = 0; quint16 length = 0;
273 pos = s.indexOf('%', pos);
275 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
280 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
281 if(s[pos+3] == '-') { // color off
282 curfmt &= 0x003fffff;
285 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
286 //TODO: use 99 as transparent color (re mirc color "standard")
288 if(s[pos+3] == 'f') {
289 curfmt &= 0xf0ffffff;
290 curfmt |= (color << 24) | 0x00400000;
292 curfmt &= 0x0fffffff;
293 curfmt |= (color << 28) | 0x00800000;
297 } else if(s[pos+1] == 'O') { // reset formatting
298 curfmt &= 0x0000000f; // we keep message type-specific formatting
300 } else if(s[pos+1] == 'R') { // reverse
301 // TODO: implement reverse formatting
304 } else { // all others are toggles
305 QString code = QString("%") + s[pos+1];
306 if(s[pos+1] == 'D') code += s[pos+2];
307 FormatType ftype = formatType(code);
308 if(ftype == Invalid) {
309 qWarning() << (QString("Invalid format code in string: %1").arg(s));
313 length = code.length();
315 s.remove(pos, length);
316 if(pos == result.formatList.last().first)
317 result.formatList.last().second = curfmt;
319 result.formatList.append(qMakePair((quint16)pos, curfmt));
321 result.plainText = s;
325 QString UiStyle::mircToInternal(const QString &mirc_) {
326 QString mirc = mirc_;
327 mirc.replace('%', "%%"); // escape % just to be sure
328 mirc.replace('\x02', "%B");
329 mirc.replace('\x0f', "%O");
330 mirc.replace('\x12', "%R");
331 mirc.replace('\x16', "%R");
332 mirc.replace('\x1d', "%S");
333 mirc.replace('\x1f', "%U");
335 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
336 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
337 // %Dc- turns color off.
338 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
339 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
342 pos = mirc.indexOf('\x03', pos);
343 if(pos < 0) break; // no more mirc color codes
345 int l = mirc.length();
347 // check for fg color
348 if(i < l && mirc[i].isDigit()) {
350 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
351 else num.prepend('0');
352 ins = QString("%Dcf%1").arg(num);
354 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
357 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
358 else num.prepend('0');
359 ins += QString("%Dcb%1").arg(num);
364 mirc.replace(pos, i-pos, ins);
369 /***********************************************************************************/
370 UiStyle::StyledMessage::StyledMessage(const Message &msg)
373 if(type() == Message::Plain)
376 _senderHash = 0x00; // this means we never compute the hash for msgs that aren't plain
379 void UiStyle::StyledMessage::style() const {
380 QString user = userFromMask(sender());
381 QString host = hostFromMask(sender());
382 QString nick = nickFromMask(sender());
383 QString txt = UiStyle::mircToInternal(contents());
384 QString bufferName = bufferInfo().bufferName();
385 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
391 t = tr("%1").arg(txt); break;
392 case Message::Notice:
394 t = tr("%1").arg(txt); break;
395 case Message::Action:
397 t = tr("%DN%1%DN %2").arg(nick).arg(txt);
401 if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
402 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
406 if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
407 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
411 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
414 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
415 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
419 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
420 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
422 case Message::Kick: {
423 QString victim = txt.section(" ", 0, 0);
424 QString kickmsg = txt.section(" ", 1);
426 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
427 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
430 //case Message::Kill: FIXME
432 case Message::Server:
434 t = tr("%1").arg(txt); break;
437 t = tr("%1").arg(txt); break;
440 t = tr("%1").arg(txt); break;
441 case Message::DayChange:
442 //: Day Change Message
443 t = tr("{Day changed to %1}").arg(timestamp().toString());
446 t = tr("[%1]").arg(txt);
448 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
451 const QString &UiStyle::StyledMessage::plainContents() const {
452 if(_contents.plainText.isNull())
455 return _contents.plainText;
458 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
459 if(_contents.plainText.isNull())
462 return _contents.formatList;
465 QString UiStyle::StyledMessage::decoratedTimestamp() const {
466 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
469 QString UiStyle::StyledMessage::plainSender() const {
472 case Message::Notice:
473 return nickFromMask(sender());
479 QString UiStyle::StyledMessage::decoratedSender() const {
482 return tr("<%1>").arg(plainSender()); break;
483 case Message::Notice:
484 return tr("[%1]").arg(plainSender()); break;
487 case Message::Server:
488 return tr("*"); break;
490 return tr("*"); break;
492 case Message::Action:
493 return tr("-*-"); break;
495 return tr("<->"); break;
497 return tr("***"); break;
498 >>>>>>> Handle all message types properly in UiStyle; eliminate msgtype format codes
500 return tr("-->"); break;
502 return tr("<--"); break;
504 return tr("<--"); break;
506 return tr("<-*"); break;
508 return tr("<-x"); break;
509 case Message::Server:
510 return tr("*"); break;
512 return tr("*"); break;
514 return tr("*"); break;
515 case Message::DayChange:
516 return tr("-"); break;
518 return tr("%1").arg(plainSender());
522 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
525 // To produce random like but stable nick colorings some sort of hashing should work best.
526 // In this case we just use the qt function qChecksum which produces a
527 // CRC16 hash. This should be fast and 16 bits are more than enough.
529 QString nick = nickFromMask(sender()).toLower();
530 if(!nick.isEmpty()) {
532 while(nick[nick.count() - 1 - chopCount] == '_') {
535 nick.chop(chopCount);
537 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
538 return (UiStyle::FormatType)((((hash % 12) + 1) << 24) + 0x200); // FIXME: amount of sender colors hardwired
540 case Message::Notice:
541 return UiStyle::NoticeMsg; break;
543 case Message::Server:
544 return UiStyle::ServerMsg; break;
546 return UiStyle::ErrorMsg; break;
548 return UiStyle::JoinMsg; break;
550 return UiStyle::PartMsg; break;
552 return UiStyle::QuitMsg; break;
554 return UiStyle::KickMsg; break;
556 return UiStyle::NickMsg; break;
558 return UiStyle::ModeMsg; break;
559 case Message::Action:
560 return UiStyle::ActionMsg; break;
562 return UiStyle::ErrorMsg;
566 // FIXME hardcoded to 16 sender hashes
567 quint8 UiStyle::StyledMessage::senderHash() const {
568 if(_senderHash != 0xff)
571 QString nick = nickFromMask(sender()).toLower();
572 if(!nick.isEmpty()) {
574 while(nick.at(nick.count() - 1 - chopCount) == '_')
576 nick.chop(chopCount);
578 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
579 return (_senderHash = (hash & 0xf) + 1);
582 /***********************************************************************************/
584 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
585 out << formatList.count();
586 UiStyle::FormatList::const_iterator it = formatList.begin();
587 while(it != formatList.end()) {
588 out << (*it).first << (*it).second;
594 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
597 for(quint16 i = 0; i < cnt; i++) {
598 quint16 pos; quint32 ftype;
600 formatList.append(qMakePair((quint16)pos, ftype));