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(QVariant)));
75 _allowMircColors = s.value("AllowMircColors", true).toBool();
76 s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
82 qDeleteAll(_metricsCache);
85 void UiStyle::reload() {
89 void UiStyle::loadStyleSheet() {
90 qDeleteAll(_metricsCache);
91 _metricsCache.clear();
98 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
99 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
100 if(s.value("UseCustomStyleSheet", false).toBool())
101 styleSheet += loadStyleSheet("file:///" + s.value("CustomStyleSheetPath").toString(), true);
102 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
104 if(!styleSheet.isEmpty()) {
106 parser.processStyleSheet(styleSheet);
107 QApplication::setPalette(parser.palette());
109 _uiStylePalette = parser.uiStylePalette();
110 _formats = parser.formats();
111 _listItemFormats = parser.listItemFormats();
113 styleSheet = styleSheet.trimmed();
114 if(!styleSheet.isEmpty())
115 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
121 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist) {
122 QString ss = styleSheet;
123 if(ss.startsWith("file:///")) {
129 if(file.open(QFile::ReadOnly)) {
130 QTextStream stream(&file);
131 ss = stream.readAll();
135 qWarning() << "Could not open stylesheet file:" << file.fileName();
142 void UiStyle::setTimestampFormatString(const QString &format) {
143 if(_timestampFormatString != format) {
144 _timestampFormatString = format;
149 void UiStyle::allowMircColorsChanged(const QVariant &v) {
150 _allowMircColors = v.toBool();
154 /******** ItemView Styling *******/
156 void UiStyle::showItemViewIconsChanged(const QVariant &v) {
157 _showBufferViewIcons = _showNickViewIcons = v.toBool();
160 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const {
161 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
162 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
164 if(role == Qt::DecorationRole) {
165 if(!_showBufferViewIcons)
169 case BufferInfo::ChannelBuffer:
171 return _channelJoinedIcon;
173 return _channelPartedIcon;
174 case BufferInfo::QueryBuffer:
176 return _userOfflineIcon;
177 if(index.data(NetworkModel::UserAwayRole).toBool())
178 return _userAwayIcon;
180 return _userOnlineIcon;
186 quint32 fmtType = BufferViewItem;
188 case BufferInfo::StatusBuffer:
189 fmtType |= NetworkItem;
191 case BufferInfo::ChannelBuffer:
192 fmtType |= ChannelBufferItem;
194 case BufferInfo::QueryBuffer:
195 fmtType |= QueryBufferItem;
201 QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
202 fmt.merge(_listItemFormats.value(fmtType));
204 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
205 if(activity & BufferInfo::Highlight) {
206 fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
207 fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
208 } else if(activity & BufferInfo::NewMessage) {
209 fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
210 fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
211 } else if(activity & BufferInfo::OtherActivity) {
212 fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
213 fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
214 } else if(!isActive) {
215 fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
216 fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
217 } else if(index.data(NetworkModel::UserAwayRole).toBool()) {
218 fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
219 fmt.merge(_listItemFormats.value(fmtType | UserAway));
222 return itemData(role, fmt);
225 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const {
226 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
228 if(role == Qt::DecorationRole) {
229 if(!_showNickViewIcons)
233 case NetworkModel::UserCategoryItemType:
235 int categoryId = index.data(TreeModel::SortRole).toInt();
236 if(categoryId <= _opIconLimit)
237 return _categoryOpIcon;
238 if(categoryId <= _voiceIconLimit)
239 return _categoryVoiceIcon;
240 return _userOnlineIcon;
242 case NetworkModel::IrcUserItemType:
243 if(index.data(NetworkModel::ItemActiveRole).toBool())
244 return _userOnlineIcon;
246 return _userAwayIcon;
252 QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
255 case NetworkModel::IrcUserItemType:
256 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
257 if(!index.data(NetworkModel::ItemActiveRole).toBool()) {
258 fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
259 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
262 case NetworkModel::UserCategoryItemType:
263 fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
269 return itemData(role, fmt);
272 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const {
275 return format.font();
276 case Qt::ForegroundRole:
277 return format.property(QTextFormat::ForegroundBrush);
278 case Qt::BackgroundRole:
279 return format.property(QTextFormat::BackgroundBrush);
285 /******** Caching *******/
287 QTextCharFormat UiStyle::format(quint64 key) const {
288 return _formats.value(key, QTextCharFormat());
291 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const {
292 return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
295 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) const {
296 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
299 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const {
300 // QFontMetricsF is not assignable, so we need to store pointers :/
301 quint64 key = ftype | ((quint64)label << 32);
303 if(_metricsCache.contains(key))
304 return _metricsCache.value(key);
306 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
309 /******** Generate formats ********/
311 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
312 // until you _really_ know what you do!
313 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const {
315 return QTextCharFormat();
317 quint64 label = (quint64)label_ << 32;
319 // check if we have exactly this format readily cached already
320 QTextCharFormat fmt = cachedFormat(ftype, label_);
321 if(fmt.properties().count())
324 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
326 for(quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<=1) {
328 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
331 setCachedFormat(fmt, ftype, label_);
335 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const {
336 mergeSubElementFormat(fmt, ftype & 0x00ff, label);
338 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
339 // or "foreground 01 and background 03"
340 if((ftype & 0xfff00)) { // element format
341 for(quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
343 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
348 // Now we handle color codes
349 // We assume that those can't be combined with subelement and message types.
350 if(_allowMircColors) {
351 if(ftype & 0x00400000)
352 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
353 if(ftype & 0x00800000)
354 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
355 if((ftype & 0x00c00000) == 0x00c00000)
356 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
361 mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
364 // Merge a subelement format into an existing message format
365 void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, quint32 ftype, quint64 label) const {
366 quint64 key = ftype | label;
367 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
368 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
369 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
370 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
373 UiStyle::FormatType UiStyle::formatType(Message::Type msgType) {
377 case Message::Notice:
379 case Message::Action:
395 case Message::Server:
401 case Message::DayChange:
405 case Message::NetsplitJoin:
406 return NetsplitJoinMsg;
407 case Message::NetsplitQuit:
408 return NetsplitQuitMsg;
409 case Message::Invite:
412 //Q_ASSERT(false); // we need to handle all message types
413 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
417 UiStyle::FormatType UiStyle::formatType(const QString & code) {
418 if(_formatCodes.contains(code)) return _formatCodes.value(code);
422 QString UiStyle::formatCode(FormatType ftype) {
423 return _formatCodes.key(ftype);
426 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const {
427 QList<QTextLayout::FormatRange> formatRanges;
428 QTextLayout::FormatRange range;
430 for(i = 0; i < formatList.count(); i++) {
431 range.format = format(formatList.at(i).second, messageLabel);
432 range.start = formatList.at(i).first;
433 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
434 formatRanges.append(range);
436 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
440 // This method expects a well-formatted string, there is no error checking!
441 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
442 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat) {
444 if(s.length() > 65535) {
445 qWarning() << QString("String too long to be styled: %1").arg(s);
446 return StyledString();
449 result.formatList.append(qMakePair((quint16)0, baseFormat));
450 quint32 curfmt = baseFormat;
451 int pos = 0; quint16 length = 0;
453 pos = s.indexOf('%', pos);
455 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
460 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
461 if(s[pos+3] == '-') { // color off
462 curfmt &= 0x003fffff;
465 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
466 //TODO: use 99 as transparent color (re mirc color "standard")
468 if(s[pos+3] == 'f') {
469 curfmt &= 0xf0ffffff;
470 curfmt |= (quint32)(color << 24) | 0x00400000;
472 curfmt &= 0x0fffffff;
473 curfmt |= (quint32)(color << 28) | 0x00800000;
477 } else if(s[pos+1] == 'O') { // reset formatting
478 curfmt &= 0x000000ff; // we keep message type-specific formatting
480 } else if(s[pos+1] == 'R') { // reverse
481 // TODO: implement reverse formatting
484 } else { // all others are toggles
485 QString code = QString("%") + s[pos+1];
486 if(s[pos+1] == 'D') code += s[pos+2];
487 FormatType ftype = formatType(code);
488 if(ftype == Invalid) {
490 qWarning() << (QString("Invalid format code in string: %1").arg(s));
494 length = code.length();
496 s.remove(pos, length);
497 if(pos == result.formatList.last().first)
498 result.formatList.last().second = curfmt;
500 result.formatList.append(qMakePair((quint16)pos, curfmt));
502 result.plainText = s;
506 QString UiStyle::mircToInternal(const QString &mirc_) {
507 QString mirc = mirc_;
508 mirc.replace('%', "%%"); // escape % just to be sure
509 mirc.replace('\t', " "); // tabs break layout, also this is italics in Konversation
510 mirc.replace('\x02', "%B");
511 mirc.replace('\x0f', "%O");
512 mirc.replace('\x12', "%R");
513 mirc.replace('\x16', "%R");
514 mirc.replace('\x1d', "%S");
515 mirc.replace('\x1f', "%U");
517 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
518 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
519 // %Dc- turns color off.
520 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
521 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
524 pos = mirc.indexOf('\x03', pos);
525 if(pos < 0) break; // no more mirc color codes
527 int l = mirc.length();
529 // check for fg color
530 if(i < l && mirc[i].isDigit()) {
532 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
533 else num.prepend('0');
534 ins = QString("%Dcf%1").arg(num);
536 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
539 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
540 else num.prepend('0');
541 ins += QString("%Dcb%1").arg(num);
546 mirc.replace(pos, i-pos, ins);
551 /***********************************************************************************/
552 UiStyle::StyledMessage::StyledMessage(const Message &msg)
555 if(type() == Message::Plain)
558 _senderHash = 0x00; // this means we never compute the hash for msgs that aren't plain
561 void UiStyle::StyledMessage::style() const {
562 QString user = userFromMask(sender());
563 QString host = hostFromMask(sender());
564 QString nick = nickFromMask(sender());
565 QString txt = UiStyle::mircToInternal(contents());
566 QString bufferName = bufferInfo().bufferName();
567 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
568 host.replace('%', "%%"); // hostnames too...
569 user.replace('%', "%%"); // and the username...
570 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
571 const int maxNetsplitNicks = 15;
577 t = tr("%1").arg(txt); break;
578 case Message::Notice:
580 t = tr("%1").arg(txt); break;
581 case Message::Action:
583 t = tr("%DN%1%DN %2").arg(nick).arg(txt);
587 if(nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
588 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
592 if(nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
593 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
597 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
600 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
601 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
605 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
606 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
608 case Message::Kick: {
609 QString victim = txt.section(" ", 0, 0);
610 QString kickmsg = txt.section(" ", 1);
612 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
613 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
616 //case Message::Kill: FIXME
618 case Message::Server:
620 t = tr("%1").arg(txt); break;
623 t = tr("%1").arg(txt); break;
626 t = tr("%1").arg(txt); break;
627 case Message::DayChange:
628 //: Day Change Message
629 t = tr("{Day changed to %1}").arg(timestamp().toString());
633 t = tr("%1").arg(txt); break;
634 case Message::NetsplitJoin: {
635 QStringList users = txt.split("#:#");
636 QStringList servers = users.takeLast().split(" ");
638 for(int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
639 users[i] = nickFromMask(users.at(i));
641 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0),servers.at(1));
642 if(users.count() <= maxNetsplitNicks)
643 t.append(QString("%DN%1%DN").arg(users.join(", ")));
645 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
648 case Message::NetsplitQuit: {
649 QStringList users = txt.split("#:#");
650 QStringList servers = users.takeLast().split(" ");
652 for(int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
653 users[i] = nickFromMask(users.at(i));
655 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0),servers.at(1));
657 if(users.count() <= maxNetsplitNicks)
658 t.append(QString("%DN%1%DN").arg(users.join(", ")));
660 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
663 case Message::Invite:
665 t = tr("%1").arg(txt); break;
667 t = tr("[%1]").arg(txt);
669 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
672 const QString &UiStyle::StyledMessage::plainContents() const {
673 if(_contents.plainText.isNull())
676 return _contents.plainText;
679 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const {
680 if(_contents.plainText.isNull())
683 return _contents.formatList;
686 QString UiStyle::StyledMessage::decoratedTimestamp() const {
687 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
690 QString UiStyle::StyledMessage::plainSender() const {
693 case Message::Notice:
694 return nickFromMask(sender());
700 QString UiStyle::StyledMessage::decoratedSender() const {
703 return tr("<%1>").arg(plainSender()); break;
704 case Message::Notice:
705 return tr("[%1]").arg(plainSender()); break;
706 case Message::Action:
722 case Message::Server:
728 case Message::DayChange:
732 case Message::NetsplitJoin:
734 case Message::NetsplitQuit:
736 case Message::Invite:
739 return QString("%1").arg(plainSender());
743 // FIXME hardcoded to 16 sender hashes
744 quint8 UiStyle::StyledMessage::senderHash() const {
745 if(_senderHash != 0xff)
748 QString nick = nickFromMask(sender()).toLower();
749 if(!nick.isEmpty()) {
751 while(chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
753 if(chopCount < nick.size())
754 nick.chop(chopCount);
756 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
757 return (_senderHash = (hash & 0xf) + 1);
760 /***********************************************************************************/
762 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
763 out << formatList.count();
764 UiStyle::FormatList::const_iterator it = formatList.begin();
765 while(it != formatList.end()) {
766 out << (*it).first << (*it).second;
772 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
775 for(quint16 i = 0; i < cnt; i++) {
776 quint16 pos; quint32 ftype;
778 formatList.append(qMakePair((quint16)pos, ftype));