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 "buffersettings.h"
23 #include "iconloader.h"
24 #include "qssparser.h"
27 #include "uisettings.h"
30 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
31 QString UiStyle::_timestampFormatString;
33 UiStyle::UiStyle(QObject *parent)
35 _channelJoinedIcon(SmallIcon("irc-channel-active")),
36 _channelPartedIcon(SmallIcon("irc-channel-inactive")),
37 _userOfflineIcon(SmallIcon("im-user-offline")),
38 _userOnlineIcon(SmallIcon("im-user")),
39 _userAwayIcon(SmallIcon("im-user-away")),
40 _categoryOpIcon(SmallIcon("irc-operator")),
41 _categoryVoiceIcon(SmallIcon("irc-voice")),
42 _opIconLimit(UserCategoryItem::categoryFromModes("o")),
43 _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
45 // register FormatList if that hasn't happened yet
46 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
47 if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
48 qRegisterMetaType<FormatList>("UiStyle::FormatList");
49 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
50 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
53 _uiStylePalette = QVector<QBrush>(NumRoles, QBrush());
55 // Now initialize the mapping between FormatCodes and FormatTypes...
56 _formatCodes["%O"] = Base;
57 _formatCodes["%B"] = Bold;
58 _formatCodes["%S"] = Italic;
59 _formatCodes["%U"] = Underline;
60 _formatCodes["%R"] = Reverse;
62 _formatCodes["%DN"] = Nick;
63 _formatCodes["%DH"] = Hostmask;
64 _formatCodes["%DC"] = ChannelName;
65 _formatCodes["%DM"] = ModeFlags;
66 _formatCodes["%DU"] = Url;
68 setTimestampFormatString("[hh:mm:ss]");
70 // BufferView / NickView settings
72 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
73 s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged()));
79 qDeleteAll(_metricsCache);
82 void UiStyle::reload() {
86 void UiStyle::loadStyleSheet() {
87 qDeleteAll(_metricsCache);
88 _metricsCache.clear();
95 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("default.qss"));
96 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
97 if(s.value("UseCustomStyleSheet", false).toBool())
98 styleSheet += loadStyleSheet("file:///" + s.value("CustomStyleSheetPath").toString(), true);
99 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
101 if(!styleSheet.isEmpty()) {
103 parser.processStyleSheet(styleSheet);
104 QApplication::setPalette(parser.palette());
106 _uiStylePalette = parser.uiStylePalette();
107 _formats = parser.formats();
108 _listItemFormats = parser.listItemFormats();
110 styleSheet = styleSheet.trimmed();
111 if(!styleSheet.isEmpty())
112 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
118 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist) {
119 QString ss = styleSheet;
120 if(ss.startsWith("file:///")) {
126 if(file.open(QFile::ReadOnly)) {
127 QTextStream stream(&file);
128 ss = stream.readAll();
132 qWarning() << "Could not open stylesheet file:" << file.fileName();
139 void UiStyle::setTimestampFormatString(const QString &format) {
140 if(_timestampFormatString != format) {
141 _timestampFormatString = format;
146 /******** ItemView Styling *******/
148 void UiStyle::showItemViewIconsChanged() {
150 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons").toBool();
153 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const {
154 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
155 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
157 if(role == Qt::DecorationRole) {
158 if(!_showBufferViewIcons)
162 case BufferInfo::ChannelBuffer:
164 return _channelJoinedIcon;
166 return _channelPartedIcon;
167 case BufferInfo::QueryBuffer:
169 return _userOfflineIcon;
170 if(index.data(NetworkModel::UserAwayRole).toBool())
171 return _userAwayIcon;
173 return _userOnlineIcon;
179 quint32 fmtType = BufferViewItem;
181 case BufferInfo::StatusBuffer:
182 fmtType |= NetworkItem;
184 case BufferInfo::ChannelBuffer:
185 fmtType |= ChannelBufferItem;
187 case BufferInfo::QueryBuffer:
188 fmtType |= QueryBufferItem;
194 QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
195 fmt.merge(_listItemFormats.value(fmtType));
197 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
198 if(activity & BufferInfo::Highlight) {
199 fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
200 fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
201 } else if(activity & BufferInfo::NewMessage) {
202 fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
203 fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
204 } else if(activity & BufferInfo::OtherActivity) {
205 fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
206 fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
207 } else if(!isActive) {
208 fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
209 fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
210 } else if(index.data(NetworkModel::UserAwayRole).toBool()) {
211 fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
212 fmt.merge(_listItemFormats.value(fmtType | UserAway));
215 return itemData(role, fmt);
218 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const {
219 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
221 if(role == Qt::DecorationRole) {
222 if(!_showNickViewIcons)
226 case NetworkModel::UserCategoryItemType:
228 int categoryId = index.data(TreeModel::SortRole).toInt();
229 if(categoryId <= _opIconLimit)
230 return _categoryOpIcon;
231 if(categoryId <= _voiceIconLimit)
232 return _categoryVoiceIcon;
233 return _userOnlineIcon;
235 case NetworkModel::IrcUserItemType:
236 if(index.data(NetworkModel::ItemActiveRole).toBool())
237 return _userOnlineIcon;
239 return _userAwayIcon;
245 QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
248 case NetworkModel::IrcUserItemType:
249 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
250 if(!index.data(NetworkModel::ItemActiveRole).toBool()) {
251 fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
252 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
255 case NetworkModel::UserCategoryItemType:
256 fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
262 return itemData(role, fmt);
265 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const {
268 return format.font();
269 case Qt::ForegroundRole:
270 return format.property(QTextFormat::ForegroundBrush);
271 case Qt::BackgroundRole:
272 return format.property(QTextFormat::BackgroundBrush);
278 /******** Caching *******/
280 QTextCharFormat UiStyle::format(quint64 key) const {
281 return _formats.value(key, QTextCharFormat());
284 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
285 return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
288 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) {
289 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
292 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) {
293 // QFontMetricsF is not assignable, so we need to store pointers :/
294 quint64 key = ftype | ((quint64)label << 32);
296 if(_metricsCache.contains(key))
297 return _metricsCache.value(key);
299 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
302 /******** Generate formats ********/
304 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
305 // until you _really_ know what you do!
306 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) {
308 return QTextCharFormat();
310 quint64 label = (quint64)label_ << 32;
312 // check if we have exactly this format readily cached already
313 QTextCharFormat fmt = cachedFormat(ftype, label_);
314 if(fmt.properties().count())
317 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
319 for(quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<=1) {
321 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
324 setCachedFormat(fmt, ftype, label_);
328 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) {
329 mergeSubElementFormat(fmt, ftype & 0x00ff, label);
331 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
332 // or "foreground 01 and background 03"
333 if((ftype & 0xfff00)) { // element format
334 for(quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
336 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
341 // Now we handle color codes
342 // We assume that those can't be combined with subelement and message types.
343 if(ftype & 0x00400000)
344 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
345 if(ftype & 0x00800000)
346 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
347 if((ftype & 0x00c00000) == 0x00c00000)
348 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
352 mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
355 // Merge a subelement format into an existing message format
356 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint64 label) {
357 quint64 key = ftype | label;
358 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
359 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
360 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
361 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
364 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) {
368 case Message::Notice:
370 case Message::Action:
386 case Message::Server:
392 case Message::DayChange:
397 //Q_ASSERT(false); // we need to handle all message types
398 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
402 UiStyle::FormatType UiStyle::formatType(const QString & code) {
403 if(_formatCodes.contains(code)) return _formatCodes.value(code);
407 QString UiStyle::formatCode(FormatType ftype) {
408 return _formatCodes.key(ftype);
411 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) {
412 QList<QTextLayout::FormatRange> formatRanges;
413 QTextLayout::FormatRange range;
415 for(i = 0; i < formatList.count(); i++) {
416 range.format = format(formatList.at(i).second, messageLabel);
417 range.start = formatList.at(i).first;
418 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
419 formatRanges.append(range);
421 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
425 // This method expects a well-formatted string, there is no error checking!
426 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
427 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
429 if(s.length() > 65535) {
430 qWarning() << QString("String too long to be styled: %1").arg(s);
431 return StyledString();
434 result.formatList.append(qMakePair((quint16)0, baseFormat));
435 quint32 curfmt = baseFormat;
436 int pos = 0; quint16 length = 0;
438 pos = s.indexOf('%', pos);
440 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
445 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
446 if(s[pos+3] == '-') { // color off
447 curfmt &= 0x003fffff;
450 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
451 //TODO: use 99 as transparent color (re mirc color "standard")
453 if(s[pos+3] == 'f') {
454 curfmt &= 0xf0ffffff;
455 curfmt |= (quint32)(color << 24) | 0x00400000;
457 curfmt &= 0x0fffffff;
458 curfmt |= (quint32)(color << 28) | 0x00800000;
462 } else if(s[pos+1] == 'O') { // reset formatting
463 curfmt &= 0x000000ff; // we keep message type-specific formatting
465 } else if(s[pos+1] == 'R') { // reverse
466 // TODO: implement reverse formatting
469 } else { // all others are toggles
470 QString code = QString("%") + s[pos+1];
471 if(s[pos+1] == 'D') code += s[pos+2];
472 FormatType ftype = formatType(code);
473 if(ftype == Invalid) {
474 qWarning() << (QString("Invalid format code in string: %1").arg(s));
478 length = code.length();
480 s.remove(pos, length);
481 if(pos == result.formatList.last().first)
482 result.formatList.last().second = curfmt;
484 result.formatList.append(qMakePair((quint16)pos, curfmt));
486 result.plainText = s;
490 QString UiStyle::mircToInternal(const QString &mirc_) {
491 QString mirc = mirc_;
492 mirc.replace('%', "%%"); // escape % just to be sure
493 mirc.replace('\x02', "%B");
494 mirc.replace('\x0f', "%O");
495 mirc.replace('\x12', "%R");
496 mirc.replace('\x16', "%R");
497 mirc.replace('\x1d', "%S");
498 mirc.replace('\x1f', "%U");
500 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
501 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
502 // %Dc- turns color off.
503 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
504 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
507 pos = mirc.indexOf('\x03', pos);
508 if(pos < 0) break; // no more mirc color codes
510 int l = mirc.length();
512 // check for fg color
513 if(i < l && mirc[i].isDigit()) {
515 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
516 else num.prepend('0');
517 ins = QString("%Dcf%1").arg(num);
519 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
522 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
523 else num.prepend('0');
524 ins += QString("%Dcb%1").arg(num);
529 mirc.replace(pos, i-pos, ins);
534 /***********************************************************************************/
535 UiStyle::StyledMessage::StyledMessage(const Message &msg)
538 if(type() == Message::Plain)
541 _senderHash = 0x00; // this means we never compute the hash for msgs that aren't plain
544 void UiStyle::StyledMessage::style() const {
545 QString user = userFromMask(sender());
546 QString host = hostFromMask(sender());
547 QString nick = nickFromMask(sender());
548 QString txt = UiStyle::mircToInternal(contents());
549 QString bufferName = bufferInfo().bufferName();
550 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
556 t = tr("%1").arg(txt); break;
557 case Message::Notice:
559 t = tr("%1").arg(txt); break;
560 case Message::Action:
562 t = tr("%DN%1%DN %2").arg(nick).arg(txt);
566 if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
567 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
571 if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
572 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
576 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
579 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
580 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
584 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
585 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
587 case Message::Kick: {
588 QString victim = txt.section(" ", 0, 0);
589 QString kickmsg = txt.section(" ", 1);
591 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
592 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
595 //case Message::Kill: FIXME
597 case Message::Server:
599 t = tr("%1").arg(txt); break;
602 t = tr("%1").arg(txt); break;
605 t = tr("%1").arg(txt); break;
606 case Message::DayChange:
607 //: Day Change Message
608 t = tr("{Day changed to %1}").arg(timestamp().toString());
612 t = tr("%1").arg(txt); break;
614 t = tr("[%1]").arg(txt);
616 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
619 const QString &UiStyle::StyledMessage::plainContents() const {
620 if(_contents.plainText.isNull())
623 return _contents.plainText;
626 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
627 if(_contents.plainText.isNull())
630 return _contents.formatList;
633 QString UiStyle::StyledMessage::decoratedTimestamp() const {
634 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
637 QString UiStyle::StyledMessage::plainSender() const {
640 case Message::Notice:
641 return nickFromMask(sender());
647 QString UiStyle::StyledMessage::decoratedSender() const {
650 return tr("<%1>").arg(plainSender()); break;
651 case Message::Notice:
652 return tr("[%1]").arg(plainSender()); break;
653 case Message::Action:
654 return tr("-*-"); break;
656 return tr("<->"); break;
658 return tr("***"); break;
660 return tr("-->"); break;
662 return tr("<--"); break;
664 return tr("<--"); break;
666 return tr("<-*"); break;
668 return tr("<-x"); break;
669 case Message::Server:
670 return tr("*"); break;
672 return tr("*"); break;
674 return tr("*"); break;
675 case Message::DayChange:
676 return tr("-"); break;
678 return tr("*"); break;
680 return tr("%1").arg(plainSender());
684 // FIXME hardcoded to 16 sender hashes
685 quint8 UiStyle::StyledMessage::senderHash() const {
686 if(_senderHash != 0xff)
689 QString nick = nickFromMask(sender()).toLower();
690 if(!nick.isEmpty()) {
692 while(chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
694 if(chopCount < nick.size())
695 nick.chop(chopCount);
697 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
698 return (_senderHash = (hash & 0xf) + 1);
701 /***********************************************************************************/
703 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
704 out << formatList.count();
705 UiStyle::FormatList::const_iterator it = formatList.begin();
706 while(it != formatList.end()) {
707 out << (*it).first << (*it).second;
713 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
716 for(quint16 i = 0; i < cnt; i++) {
717 quint16 pos; quint32 ftype;
719 formatList.append(qMakePair((quint16)pos, ftype));