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)));
84 qDeleteAll(_metricsCache);
88 void UiStyle::reload()
94 void UiStyle::loadStyleSheet()
96 qDeleteAll(_metricsCache);
97 _metricsCache.clear();
104 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
105 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
106 if (s.value("UseCustomStyleSheet", false).toBool())
107 styleSheet += loadStyleSheet("file:///" + s.value("CustomStyleSheetPath").toString(), true);
108 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
110 if (!styleSheet.isEmpty()) {
112 parser.processStyleSheet(styleSheet);
113 QApplication::setPalette(parser.palette());
115 _uiStylePalette = parser.uiStylePalette();
116 _formats = parser.formats();
117 _listItemFormats = parser.listItemFormats();
119 styleSheet = styleSheet.trimmed();
120 if (!styleSheet.isEmpty())
121 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
128 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
130 QString ss = styleSheet;
131 if (ss.startsWith("file:///")) {
137 if (file.open(QFile::ReadOnly)) {
138 QTextStream stream(&file);
139 ss = stream.readAll();
144 qWarning() << "Could not open stylesheet file:" << file.fileName();
152 void UiStyle::setTimestampFormatString(const QString &format)
154 if (_timestampFormatString != format) {
155 _timestampFormatString = format;
161 void UiStyle::allowMircColorsChanged(const QVariant &v)
163 _allowMircColors = v.toBool();
168 /******** ItemView Styling *******/
170 void UiStyle::showItemViewIconsChanged(const QVariant &v)
172 _showBufferViewIcons = _showNickViewIcons = v.toBool();
176 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
178 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
179 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
181 if (role == Qt::DecorationRole) {
182 if (!_showBufferViewIcons)
186 case BufferInfo::ChannelBuffer:
188 return _channelJoinedIcon;
190 return _channelPartedIcon;
191 case BufferInfo::QueryBuffer:
193 return _userOfflineIcon;
194 if (index.data(NetworkModel::UserAwayRole).toBool())
195 return _userAwayIcon;
197 return _userOnlineIcon;
203 quint32 fmtType = BufferViewItem;
205 case BufferInfo::StatusBuffer:
206 fmtType |= NetworkItem;
208 case BufferInfo::ChannelBuffer:
209 fmtType |= ChannelBufferItem;
211 case BufferInfo::QueryBuffer:
212 fmtType |= QueryBufferItem;
218 QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
219 fmt.merge(_listItemFormats.value(fmtType));
221 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
222 if (activity & BufferInfo::Highlight) {
223 fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
224 fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
226 else if (activity & BufferInfo::NewMessage) {
227 fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
228 fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
230 else if (activity & BufferInfo::OtherActivity) {
231 fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
232 fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
234 else if (!isActive) {
235 fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
236 fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
238 else if (index.data(NetworkModel::UserAwayRole).toBool()) {
239 fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
240 fmt.merge(_listItemFormats.value(fmtType | UserAway));
243 return itemData(role, fmt);
247 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
249 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
251 if (role == Qt::DecorationRole) {
252 if (!_showNickViewIcons)
256 case NetworkModel::UserCategoryItemType:
258 int categoryId = index.data(TreeModel::SortRole).toInt();
259 if (categoryId <= _opIconLimit)
260 return _categoryOpIcon;
261 if (categoryId <= _voiceIconLimit)
262 return _categoryVoiceIcon;
263 return _userOnlineIcon;
265 case NetworkModel::IrcUserItemType:
266 if (index.data(NetworkModel::ItemActiveRole).toBool())
267 return _userOnlineIcon;
269 return _userAwayIcon;
275 QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
278 case NetworkModel::IrcUserItemType:
279 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
280 if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
281 fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
282 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
285 case NetworkModel::UserCategoryItemType:
286 fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
292 return itemData(role, fmt);
296 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
300 return format.font();
301 case Qt::ForegroundRole:
302 return format.property(QTextFormat::ForegroundBrush);
303 case Qt::BackgroundRole:
304 return format.property(QTextFormat::BackgroundBrush);
311 /******** Caching *******/
313 QTextCharFormat UiStyle::format(quint64 key) const
315 return _formats.value(key, QTextCharFormat());
319 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const
321 return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
325 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) const
327 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
331 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const
333 // QFontMetricsF is not assignable, so we need to store pointers :/
334 quint64 key = ftype | ((quint64)label << 32);
336 if (_metricsCache.contains(key))
337 return _metricsCache.value(key);
339 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
343 /******** Generate formats ********/
345 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
346 // until you _really_ know what you do!
347 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const
349 if (ftype == Invalid)
350 return QTextCharFormat();
352 quint64 label = (quint64)label_ << 32;
354 // check if we have exactly this format readily cached already
355 QTextCharFormat fmt = cachedFormat(ftype, label_);
356 if (fmt.properties().count())
359 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
361 for (quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<= 1) {
363 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
366 setCachedFormat(fmt, ftype, label_);
371 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
373 mergeSubElementFormat(fmt, ftype & 0x00ff, label);
375 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
376 // or "foreground 01 and background 03"
377 if ((ftype & 0xfff00)) { // element format
378 for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
380 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
385 // Now we handle color codes
386 // We assume that those can't be combined with subelement and message types.
387 if (_allowMircColors) {
388 if (ftype & 0x00400000)
389 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
390 if (ftype & 0x00800000)
391 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
392 if ((ftype & 0x00c00000) == 0x00c00000)
393 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
398 mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
402 // Merge a subelement format into an existing message format
403 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
405 quint64 key = ftype | label;
406 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
407 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
408 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
409 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
413 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
418 case Message::Notice:
420 case Message::Action:
436 case Message::Server:
442 case Message::DayChange:
446 case Message::NetsplitJoin:
447 return NetsplitJoinMsg;
448 case Message::NetsplitQuit:
449 return NetsplitQuitMsg;
450 case Message::Invite:
453 //Q_ASSERT(false); // we need to handle all message types
454 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
459 UiStyle::FormatType UiStyle::formatType(const QString &code)
461 if (_formatCodes.contains(code)) return _formatCodes.value(code);
466 QString UiStyle::formatCode(FormatType ftype)
468 return _formatCodes.key(ftype);
472 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const
474 QList<QTextLayout::FormatRange> formatRanges;
475 QTextLayout::FormatRange range;
477 for (i = 0; i < formatList.count(); i++) {
478 range.format = format(formatList.at(i).second, messageLabel);
479 range.start = formatList.at(i).first;
480 if (i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
481 formatRanges.append(range);
483 if (i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
488 // This method expects a well-formatted string, there is no error checking!
489 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
490 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat)
493 if (s.length() > 65535) {
494 qWarning() << QString("String too long to be styled: %1").arg(s);
495 return StyledString();
498 result.formatList.append(qMakePair((quint16)0, baseFormat));
499 quint32 curfmt = baseFormat;
500 int pos = 0; quint16 length = 0;
502 pos = s.indexOf('%', pos);
504 if (s[pos+1] == '%') { // escaped %, we just remove one and continue
509 if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
510 if (s[pos+3] == '-') { // color off
511 curfmt &= 0x003fffff;
515 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
516 //TODO: use 99 as transparent color (re mirc color "standard")
518 if (s[pos+3] == 'f') {
519 curfmt &= 0xf0ffffff;
520 curfmt |= (quint32)(color << 24) | 0x00400000;
523 curfmt &= 0x0fffffff;
524 curfmt |= (quint32)(color << 28) | 0x00800000;
529 else if (s[pos+1] == 'O') { // reset formatting
530 curfmt &= 0x000000ff; // we keep message type-specific formatting
533 else if (s[pos+1] == 'R') { // reverse
534 // TODO: implement reverse formatting
538 else { // all others are toggles
539 QString code = QString("%") + s[pos+1];
540 if (s[pos+1] == 'D') code += s[pos+2];
541 FormatType ftype = formatType(code);
542 if (ftype == Invalid) {
544 qWarning() << (QString("Invalid format code in string: %1").arg(s));
548 length = code.length();
550 s.remove(pos, length);
551 if (pos == result.formatList.last().first)
552 result.formatList.last().second = curfmt;
554 result.formatList.append(qMakePair((quint16)pos, curfmt));
556 result.plainText = s;
561 QString UiStyle::mircToInternal(const QString &mirc_)
563 QString mirc = mirc_;
564 mirc.replace('%', "%%"); // escape % just to be sure
565 mirc.replace('\t', " "); // tabs break layout, also this is italics in Konversation
566 mirc.replace('\x02', "%B");
567 mirc.replace('\x0f', "%O");
568 mirc.replace('\x12', "%R");
569 mirc.replace('\x16', "%R");
570 mirc.replace('\x1d', "%S");
571 mirc.replace('\x1f', "%U");
573 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
574 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
575 // %Dc- turns color off.
576 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
577 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
580 pos = mirc.indexOf('\x03', pos);
581 if (pos < 0) break; // no more mirc color codes
583 int l = mirc.length();
585 // check for fg color
586 if (i < l && mirc[i].isDigit()) {
588 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
589 else num.prepend('0');
590 ins = QString("%Dcf%1").arg(num);
592 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
595 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
596 else num.prepend('0');
597 ins += QString("%Dcb%1").arg(num);
603 mirc.replace(pos, i-pos, ins);
609 /***********************************************************************************/
610 UiStyle::StyledMessage::StyledMessage(const Message &msg)
613 if (type() == Message::Plain)
616 _senderHash = 0x00; // this means we never compute the hash for msgs that aren't plain
620 void UiStyle::StyledMessage::style() const
622 QString user = userFromMask(sender());
623 QString host = hostFromMask(sender());
624 QString nick = nickFromMask(sender());
625 QString txt = UiStyle::mircToInternal(contents());
626 QString bufferName = bufferInfo().bufferName();
627 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
628 host.replace('%', "%%"); // hostnames too...
629 user.replace('%', "%%"); // and the username...
630 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
631 const int maxNetsplitNicks = 15;
637 t = tr("%1").arg(txt); break;
638 case Message::Notice:
640 t = tr("%1").arg(txt); break;
641 case Message::Action:
643 t = tr("%DN%1%DN %2").arg(nick).arg(txt);
647 if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
648 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
652 if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
653 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
657 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
660 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
661 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
665 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
666 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
670 QString victim = txt.section(" ", 0, 0);
671 QString kickmsg = txt.section(" ", 1);
673 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
674 if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
677 //case Message::Kill: FIXME
679 case Message::Server:
681 t = tr("%1").arg(txt); break;
684 t = tr("%1").arg(txt); break;
687 t = tr("%1").arg(txt); break;
688 case Message::DayChange:
689 //: Day Change Message
690 t = tr("{Day changed to %1}").arg(timestamp().toString());
694 t = tr("%1").arg(txt); break;
695 case Message::NetsplitJoin:
697 QStringList users = txt.split("#:#");
698 QStringList servers = users.takeLast().split(" ");
700 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
701 users[i] = nickFromMask(users.at(i));
703 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
704 if (users.count() <= maxNetsplitNicks)
705 t.append(QString("%DN%1%DN").arg(users.join(", ")));
707 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
710 case Message::NetsplitQuit:
712 QStringList users = txt.split("#:#");
713 QStringList servers = users.takeLast().split(" ");
715 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
716 users[i] = nickFromMask(users.at(i));
718 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
720 if (users.count() <= maxNetsplitNicks)
721 t.append(QString("%DN%1%DN").arg(users.join(", ")));
723 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
726 case Message::Invite:
728 t = tr("%1").arg(txt); break;
730 t = tr("[%1]").arg(txt);
732 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
736 const QString &UiStyle::StyledMessage::plainContents() const
738 if (_contents.plainText.isNull())
741 return _contents.plainText;
745 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
747 if (_contents.plainText.isNull())
750 return _contents.formatList;
754 QString UiStyle::StyledMessage::decoratedTimestamp() const
756 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
760 QString UiStyle::StyledMessage::plainSender() const
764 case Message::Notice:
765 return nickFromMask(sender());
772 QString UiStyle::StyledMessage::decoratedSender() const
776 return tr("<%1>").arg(plainSender()); break;
777 case Message::Notice:
778 return tr("[%1]").arg(plainSender()); break;
779 case Message::Action:
795 case Message::Server:
801 case Message::DayChange:
805 case Message::NetsplitJoin:
807 case Message::NetsplitQuit:
809 case Message::Invite:
812 return QString("%1").arg(plainSender());
817 // FIXME hardcoded to 16 sender hashes
818 quint8 UiStyle::StyledMessage::senderHash() const
820 if (_senderHash != 0xff)
823 QString nick = nickFromMask(sender()).toLower();
824 if (!nick.isEmpty()) {
826 while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
828 if (chopCount < nick.size())
829 nick.chop(chopCount);
831 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
832 return (_senderHash = (hash & 0xf) + 1);
836 /***********************************************************************************/
838 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
840 out << formatList.count();
841 UiStyle::FormatList::const_iterator it = formatList.begin();
842 while (it != formatList.end()) {
843 out << (*it).first << (*it).second;
850 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
854 for (quint16 i = 0; i < cnt; i++) {
855 quint16 pos; quint32 ftype;
857 formatList.append(qMakePair((quint16)pos, ftype));