1 /***************************************************************************
2 * Copyright (C) 2005-2014 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include <QApplication>
23 #include "buffersettings.h"
24 #include "iconloader.h"
25 #include "qssparser.h"
28 #include "uisettings.h"
31 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
32 QString UiStyle::_timestampFormatString;
34 UiStyle::UiStyle(QObject *parent)
36 _channelJoinedIcon(SmallIcon("irc-channel-active")),
37 _channelPartedIcon(SmallIcon("irc-channel-inactive")),
38 _userOfflineIcon(SmallIcon("im-user-offline")),
39 _userOnlineIcon(SmallIcon("im-user")),
40 _userAwayIcon(SmallIcon("im-user-away")),
41 _categoryOpIcon(SmallIcon("irc-operator")),
42 _categoryVoiceIcon(SmallIcon("irc-voice")),
43 _opIconLimit(UserCategoryItem::categoryFromModes("o")),
44 _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
46 // register FormatList if that hasn't happened yet
47 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
48 if (QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
49 qRegisterMetaType<FormatList>("UiStyle::FormatList");
50 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
51 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
54 _uiStylePalette = QVector<QBrush>(NumRoles, QBrush());
56 // Now initialize the mapping between FormatCodes and FormatTypes...
57 _formatCodes["%O"] = Base;
58 _formatCodes["%B"] = Bold;
59 _formatCodes["%S"] = Italic;
60 _formatCodes["%U"] = Underline;
61 _formatCodes["%R"] = Reverse;
63 _formatCodes["%DN"] = Nick;
64 _formatCodes["%DH"] = Hostmask;
65 _formatCodes["%DC"] = ChannelName;
66 _formatCodes["%DM"] = ModeFlags;
67 _formatCodes["%DU"] = Url;
69 setTimestampFormatString("[hh:mm:ss]");
71 // BufferView / NickView settings
73 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
74 s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
76 _allowMircColors = s.value("AllowMircColors", true).toBool();
77 s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
85 qDeleteAll(_metricsCache);
89 void UiStyle::reload()
95 void UiStyle::loadStyleSheet()
97 qDeleteAll(_metricsCache);
98 _metricsCache.clear();
105 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
106 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
107 if (s.value("UseCustomStyleSheet", false).toBool())
108 styleSheet += loadStyleSheet("file:///" + s.value("CustomStyleSheetPath").toString(), true);
109 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
111 if (!styleSheet.isEmpty()) {
113 parser.processStyleSheet(styleSheet);
114 QApplication::setPalette(parser.palette());
116 _uiStylePalette = parser.uiStylePalette();
117 _formats = parser.formats();
118 _listItemFormats = parser.listItemFormats();
120 styleSheet = styleSheet.trimmed();
121 if (!styleSheet.isEmpty())
122 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
129 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
131 QString ss = styleSheet;
132 if (ss.startsWith("file:///")) {
138 if (file.open(QFile::ReadOnly)) {
139 QTextStream stream(&file);
140 ss = stream.readAll();
145 qWarning() << "Could not open stylesheet file:" << file.fileName();
153 void UiStyle::setTimestampFormatString(const QString &format)
155 if (_timestampFormatString != format) {
156 _timestampFormatString = format;
162 void UiStyle::allowMircColorsChanged(const QVariant &v)
164 _allowMircColors = v.toBool();
169 /******** ItemView Styling *******/
171 void UiStyle::showItemViewIconsChanged(const QVariant &v)
173 _showBufferViewIcons = _showNickViewIcons = v.toBool();
177 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
179 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
180 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
182 if (role == Qt::DecorationRole) {
183 if (!_showBufferViewIcons)
187 case BufferInfo::ChannelBuffer:
189 return _channelJoinedIcon;
191 return _channelPartedIcon;
192 case BufferInfo::QueryBuffer:
194 return _userOfflineIcon;
195 if (index.data(NetworkModel::UserAwayRole).toBool())
196 return _userAwayIcon;
198 return _userOnlineIcon;
204 quint32 fmtType = BufferViewItem;
206 case BufferInfo::StatusBuffer:
207 fmtType |= NetworkItem;
209 case BufferInfo::ChannelBuffer:
210 fmtType |= ChannelBufferItem;
212 case BufferInfo::QueryBuffer:
213 fmtType |= QueryBufferItem;
219 QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
220 fmt.merge(_listItemFormats.value(fmtType));
222 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
223 if (activity & BufferInfo::Highlight) {
224 fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
225 fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
227 else if (activity & BufferInfo::NewMessage) {
228 fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
229 fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
231 else if (activity & BufferInfo::OtherActivity) {
232 fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
233 fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
235 else if (!isActive) {
236 fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
237 fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
239 else if (index.data(NetworkModel::UserAwayRole).toBool()) {
240 fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
241 fmt.merge(_listItemFormats.value(fmtType | UserAway));
244 return itemData(role, fmt);
248 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
250 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
252 if (role == Qt::DecorationRole) {
253 if (!_showNickViewIcons)
257 case NetworkModel::UserCategoryItemType:
259 int categoryId = index.data(TreeModel::SortRole).toInt();
260 if (categoryId <= _opIconLimit)
261 return _categoryOpIcon;
262 if (categoryId <= _voiceIconLimit)
263 return _categoryVoiceIcon;
264 return _userOnlineIcon;
266 case NetworkModel::IrcUserItemType:
267 if (index.data(NetworkModel::ItemActiveRole).toBool())
268 return _userOnlineIcon;
270 return _userAwayIcon;
276 QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
279 case NetworkModel::IrcUserItemType:
280 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
281 if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
282 fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
283 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
286 case NetworkModel::UserCategoryItemType:
287 fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
293 return itemData(role, fmt);
297 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
301 return format.font();
302 case Qt::ForegroundRole:
303 return format.property(QTextFormat::ForegroundBrush);
304 case Qt::BackgroundRole:
305 return format.property(QTextFormat::BackgroundBrush);
312 /******** Caching *******/
314 QTextCharFormat UiStyle::format(quint64 key) const
316 return _formats.value(key, QTextCharFormat());
320 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const
322 return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
326 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) const
328 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
332 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const
334 // QFontMetricsF is not assignable, so we need to store pointers :/
335 quint64 key = ftype | ((quint64)label << 32);
337 if (_metricsCache.contains(key))
338 return _metricsCache.value(key);
340 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
344 /******** Generate formats ********/
346 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
347 // until you _really_ know what you do!
348 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const
350 if (ftype == Invalid)
351 return QTextCharFormat();
353 quint64 label = (quint64)label_ << 32;
355 // check if we have exactly this format readily cached already
356 QTextCharFormat fmt = cachedFormat(ftype, label_);
357 if (fmt.properties().count())
360 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
362 for (quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<= 1) {
364 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
367 setCachedFormat(fmt, ftype, label_);
372 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
374 mergeSubElementFormat(fmt, ftype & 0x00ff, label);
376 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
377 // or "foreground 01 and background 03"
378 if ((ftype & 0xfff00)) { // element format
379 for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
381 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
386 // Now we handle color codes
387 // We assume that those can't be combined with subelement and message types.
388 if (_allowMircColors) {
389 if (ftype & 0x00400000)
390 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
391 if (ftype & 0x00800000)
392 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
393 if ((ftype & 0x00c00000) == 0x00c00000)
394 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
399 mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
403 // Merge a subelement format into an existing message format
404 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
406 quint64 key = ftype | label;
407 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
408 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
409 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
410 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
414 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
419 case Message::Notice:
421 case Message::Action:
437 case Message::Server:
443 case Message::DayChange:
447 case Message::NetsplitJoin:
448 return NetsplitJoinMsg;
449 case Message::NetsplitQuit:
450 return NetsplitQuitMsg;
451 case Message::Invite:
454 //Q_ASSERT(false); // we need to handle all message types
455 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
460 UiStyle::FormatType UiStyle::formatType(const QString &code)
462 if (_formatCodes.contains(code)) return _formatCodes.value(code);
467 QString UiStyle::formatCode(FormatType ftype)
469 return _formatCodes.key(ftype);
473 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const
475 QList<QTextLayout::FormatRange> formatRanges;
476 QTextLayout::FormatRange range;
478 for (i = 0; i < formatList.count(); i++) {
479 range.format = format(formatList.at(i).second, messageLabel);
480 range.start = formatList.at(i).first;
481 if (i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
482 formatRanges.append(range);
484 if (i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
489 // This method expects a well-formatted string, there is no error checking!
490 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
491 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat)
495 result.formatList.append(qMakePair((quint16)0, baseFormat));
497 if (s.length() > 65535) {
498 // We use quint16 for indexes
499 qWarning() << QString("String too long to be styled: %1").arg(s);
500 result.plainText = s;
504 quint32 curfmt = baseFormat;
505 int pos = 0; quint16 length = 0;
507 pos = s.indexOf('%', pos);
509 if (s[pos+1] == '%') { // escaped %, we just remove one and continue
514 if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
515 if (s[pos+3] == '-') { // color off
516 curfmt &= 0x003fffff;
520 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
521 //TODO: use 99 as transparent color (re mirc color "standard")
523 if (s[pos+3] == 'f') {
524 curfmt &= 0xf0ffffff;
525 curfmt |= (quint32)(color << 24) | 0x00400000;
528 curfmt &= 0x0fffffff;
529 curfmt |= (quint32)(color << 28) | 0x00800000;
534 else if (s[pos+1] == 'O') { // reset formatting
535 curfmt &= 0x000000ff; // we keep message type-specific formatting
538 else if (s[pos+1] == 'R') { // reverse
539 // TODO: implement reverse formatting
543 else { // all others are toggles
544 QString code = QString("%") + s[pos+1];
545 if (s[pos+1] == 'D') code += s[pos+2];
546 FormatType ftype = formatType(code);
547 if (ftype == Invalid) {
549 qWarning() << (QString("Invalid format code in string: %1").arg(s));
553 length = code.length();
555 s.remove(pos, length);
556 if (pos == result.formatList.last().first)
557 result.formatList.last().second = curfmt;
559 result.formatList.append(qMakePair((quint16)pos, curfmt));
561 result.plainText = s;
566 QString UiStyle::mircToInternal(const QString &mirc_)
569 mirc.reserve(mirc_.size());
570 foreach (const QChar &c, mirc_) {
571 if ((c < '\x20' || c == '\x7f') && c != '\x03') {
572 switch (c.unicode()) {
593 mirc += QChar(0x2421);
596 mirc += QChar(0x2400 + c.unicode());
605 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
606 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
607 // %Dc- turns color off.
608 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
609 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
612 pos = mirc.indexOf('\x03', pos);
613 if (pos < 0) break; // no more mirc color codes
615 int l = mirc.length();
617 // check for fg color
618 if (i < l && mirc[i].isDigit()) {
620 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
621 else num.prepend('0');
622 ins = QString("%Dcf%1").arg(num);
624 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
627 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
628 else num.prepend('0');
629 ins += QString("%Dcb%1").arg(num);
635 mirc.replace(pos, i-pos, ins);
641 /***********************************************************************************/
642 UiStyle::StyledMessage::StyledMessage(const Message &msg)
645 if (type() == Message::Plain)
648 _senderHash = 0x00; // this means we never compute the hash for msgs that aren't plain
652 void UiStyle::StyledMessage::style() const
654 QString user = userFromMask(sender());
655 QString host = hostFromMask(sender());
656 QString nick = nickFromMask(sender());
657 QString txt = UiStyle::mircToInternal(contents());
658 QString bufferName = bufferInfo().bufferName();
659 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
660 host.replace('%', "%%"); // hostnames too...
661 user.replace('%', "%%"); // and the username...
662 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
663 const int maxNetsplitNicks = 15;
669 t = tr("%1").arg(txt); break;
670 case Message::Notice:
672 t = tr("%1").arg(txt); break;
673 case Message::Action:
675 t = tr("%DN%1%DN %2").arg(nick).arg(txt);
679 if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
680 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
684 if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
685 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
689 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
692 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
693 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
697 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
698 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
702 QString victim = txt.section(" ", 0, 0);
703 QString kickmsg = txt.section(" ", 1);
705 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
706 if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
709 //case Message::Kill: FIXME
711 case Message::Server:
713 t = tr("%1").arg(txt); break;
716 t = tr("%1").arg(txt); break;
719 t = tr("%1").arg(txt); break;
720 case Message::DayChange:
722 //: Day Change Message
723 t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
728 t = tr("%1").arg(txt); break;
729 case Message::NetsplitJoin:
731 QStringList users = txt.split("#:#");
732 QStringList servers = users.takeLast().split(" ");
734 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
735 users[i] = nickFromMask(users.at(i));
737 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
738 if (users.count() <= maxNetsplitNicks)
739 t.append(QString("%DN%1%DN").arg(users.join(", ")));
741 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
744 case Message::NetsplitQuit:
746 QStringList users = txt.split("#:#");
747 QStringList servers = users.takeLast().split(" ");
749 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
750 users[i] = nickFromMask(users.at(i));
752 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
754 if (users.count() <= maxNetsplitNicks)
755 t.append(QString("%DN%1%DN").arg(users.join(", ")));
757 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
760 case Message::Invite:
762 t = tr("%1").arg(txt); break;
764 t = tr("[%1]").arg(txt);
766 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
770 const QString &UiStyle::StyledMessage::plainContents() const
772 if (_contents.plainText.isNull())
775 return _contents.plainText;
779 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
781 if (_contents.plainText.isNull())
784 return _contents.formatList;
788 QString UiStyle::StyledMessage::decoratedTimestamp() const
790 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
794 QString UiStyle::StyledMessage::plainSender() const
798 case Message::Notice:
799 return nickFromMask(sender());
806 QString UiStyle::StyledMessage::decoratedSender() const
810 return tr("<%1>").arg(plainSender()); break;
811 case Message::Notice:
812 return tr("[%1]").arg(plainSender()); break;
813 case Message::Action:
829 case Message::Server:
835 case Message::DayChange:
839 case Message::NetsplitJoin:
841 case Message::NetsplitQuit:
843 case Message::Invite:
846 return QString("%1").arg(plainSender());
851 // FIXME hardcoded to 16 sender hashes
852 quint8 UiStyle::StyledMessage::senderHash() const
854 if (_senderHash != 0xff)
857 QString nick = nickFromMask(sender()).toLower();
858 if (!nick.isEmpty()) {
860 while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
862 if (chopCount < nick.size())
863 nick.chop(chopCount);
865 quint16 hash = qChecksum(nick.toAscii().data(), nick.toAscii().size());
866 return (_senderHash = (hash & 0xf) + 1);
870 /***********************************************************************************/
872 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
874 out << formatList.count();
875 UiStyle::FormatList::const_iterator it = formatList.begin();
876 while (it != formatList.end()) {
877 out << (*it).first << (*it).second;
884 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
888 for (quint16 i = 0; i < cnt; i++) {
889 quint16 pos; quint32 ftype;
891 formatList.append(qMakePair((quint16)pos, ftype));