1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 ***************************************************************************/
23 #include <QApplication>
27 #include "buffersettings.h"
28 #include "qssparser.h"
31 #include "uisettings.h"
34 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
35 bool UiStyle::_useCustomTimestampFormat; /// If true, use the custom timestamp format
36 QString UiStyle::_timestampFormatString; /// Timestamp format
37 QString UiStyle::_systemTimestampFormatString; /// Cached copy of system locale timestamp format
38 bool UiStyle::_showSenderPrefixes; /// If true, show prefixmodes before sender names
39 bool UiStyle::_showSenderBrackets; /// If true, show brackets around sender names
43 // Extended mIRC colors as defined in https://modern.ircdocs.horse/formatting.html#colors-16-98
44 QColor extendedMircColor(int number)
46 static const std::vector<QColor> colorMap = {
47 "#470000", "#472100", "#474700", "#324700", "#004700", "#00472c", "#004747", "#002747", "#000047", "#2e0047", "#470047", "#47002a",
48 "#740000", "#743a00", "#747400", "#517400", "#007400", "#007449", "#007474", "#004074", "#000074", "#4b0074", "#740074", "#740045",
49 "#b50000", "#b56300", "#b5b500", "#7db500", "#00b500", "#00b571", "#00b5b5", "#0063b5", "#0000b5", "#7500b5", "#b500b5", "#b5006b",
50 "#ff0000", "#ff8c00", "#ffff00", "#b2ff00", "#00ff00", "#00ffa0", "#00ffff", "#008cff", "#0000ff", "#a500ff", "#ff00ff", "#ff0098",
51 "#ff5959", "#ffb459", "#ffff71", "#cfff60", "#6fff6f", "#65ffc9", "#6dffff", "#59b4ff", "#5959ff", "#c459ff", "#ff66ff", "#ff59bc",
52 "#ff9c9c", "#ffd39c", "#ffff9c", "#e2ff9c", "#9cff9c", "#9cffdb", "#9cffff", "#9cd3ff", "#9c9cff", "#dc9cff", "#ff9cff", "#ff94d3",
53 "#000000", "#131313", "#282828", "#363636", "#4d4d4d", "#656565", "#818181", "#9f9f9f", "#bcbcbc", "#e2e2e2", "#ffffff"
57 size_t index = number - 16;
58 return (index < colorMap.size() ? colorMap[index] : QColor{});
63 UiStyle::UiStyle(QObject *parent)
65 _channelJoinedIcon(QIcon::fromTheme("irc-channel-joined", QIcon(":/icons/irc-channel-joined.png"))),
66 _channelPartedIcon(QIcon::fromTheme("irc-channel-parted", QIcon(":/icons/irc-channel-parted.png"))),
67 _userOfflineIcon(QIcon::fromTheme("im-user-offline", QIcon::fromTheme("user-offline", QIcon(":/icons/im-user-offline.png")))),
68 _userOnlineIcon(QIcon::fromTheme("im-user", QIcon::fromTheme("user-available", QIcon(":/icons/im-user.png")))), // im-user-* are non-standard oxygen extensions
69 _userAwayIcon(QIcon::fromTheme("im-user-away", QIcon::fromTheme("user-away", QIcon(":/icons/im-user-away.png")))),
70 _categoryOpIcon(QIcon::fromTheme("irc-operator")),
71 _categoryVoiceIcon(QIcon::fromTheme("irc-voice")),
72 _opIconLimit(UserCategoryItem::categoryFromModes("o")),
73 _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
75 // register FormatList if that hasn't happened yet
76 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
77 if (QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
78 qRegisterMetaType<FormatList>("UiStyle::FormatList");
79 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
80 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
83 _uiStylePalette = QVector<QBrush>(static_cast<int>(ColorRole::NumRoles), QBrush());
85 // Now initialize the mapping between FormatCodes and FormatTypes...
86 _formatCodes["%O"] = FormatType::Base;
87 _formatCodes["%B"] = FormatType::Bold;
88 _formatCodes["%S"] = FormatType::Italic;
89 _formatCodes["%U"] = FormatType::Underline;
90 _formatCodes["%R"] = FormatType::Reverse;
92 _formatCodes["%DN"] = FormatType::Nick;
93 _formatCodes["%DH"] = FormatType::Hostmask;
94 _formatCodes["%DC"] = FormatType::ChannelName;
95 _formatCodes["%DM"] = FormatType::ModeFlags;
96 _formatCodes["%DU"] = FormatType::Url;
98 // Initialize fallback defaults
99 // NOTE: If you change this, update qtui/chatviewsettings.h, too. More explanations available
101 setUseCustomTimestampFormat(false);
102 setTimestampFormatString(" hh:mm:ss");
103 enableSenderPrefixes(false);
104 enableSenderBrackets(true);
106 // BufferView / NickView settings
108 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
109 s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
111 _allowMircColors = s.value("AllowMircColors", true).toBool();
112 s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
120 qDeleteAll(_metricsCache);
124 void UiStyle::reload()
130 void UiStyle::loadStyleSheet()
132 qDeleteAll(_metricsCache);
133 _metricsCache.clear();
134 _formatCache.clear();
140 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
141 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
142 if (s.value("UseCustomStyleSheet", false).toBool()) {
143 QString customSheetPath(s.value("CustomStyleSheetPath").toString());
144 QString customSheet = loadStyleSheet("file:///" + customSheetPath, true);
145 if (customSheet.isEmpty()) {
146 // MIGRATION: changed default install path for data from /usr/share/apps to /usr/share
147 if (customSheetPath.startsWith("/usr/share/apps/quassel")) {
148 customSheetPath.replace(QRegExp("^/usr/share/apps"), "/usr/share");
149 customSheet = loadStyleSheet("file:///" + customSheetPath, true);
150 if (!customSheet.isEmpty()) {
151 s.setValue("CustomStyleSheetPath", customSheetPath);
152 qDebug() << "Custom stylesheet path migrated to" << customSheetPath;
156 styleSheet += customSheet;
158 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
160 if (!styleSheet.isEmpty()) {
162 parser.processStyleSheet(styleSheet);
163 QApplication::setPalette(parser.palette());
165 _uiStylePalette = parser.uiStylePalette();
166 _formats = parser.formats();
167 _listItemFormats = parser.listItemFormats();
169 styleSheet = styleSheet.trimmed();
170 if (!styleSheet.isEmpty())
171 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
178 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
180 QString ss = styleSheet;
181 if (ss.startsWith("file:///")) {
187 if (file.open(QFile::ReadOnly)) {
188 QTextStream stream(&file);
189 ss = stream.readAll();
194 qWarning() << "Could not open stylesheet file:" << file.fileName();
202 void UiStyle::updateSystemTimestampFormat()
204 // Does the system locale use AM/PM designators? For example:
208 // 24-hour: hh:mm ADD things
209 // For timestamp format, see https://doc.qt.io/qt-5/qdatetime.html#toString
210 // This won't update if the system locale is changed while Quassel is running. If need be,
211 // Quassel could hook into notifications of changing system locale to update this.
213 // Match any AP or A designation if on a word boundary, including underscores.
214 // .*(\b|_)(A|AP)(\b|_).*
215 // .* Match any number of characters
216 // \b Match a word boundary, i.e. "AAA.BBB", "." is matched
217 // _ Match the literal character '_' (not considered a word boundary)
218 // (X|Y) Match either X or Y, exactly
220 // Note that '\' must be escaped as '\\'
221 // QRegExp does not support (?> ...), so it's replaced with standard matching, (...)
222 // Helpful interactive website for debugging and explaining: https://regex101.com/
223 const QRegExp regExpMatchAMPM(".*(\\b|_)(A|AP)(\\b|_).*", Qt::CaseInsensitive);
225 if (regExpMatchAMPM.exactMatch(QLocale::system().timeFormat(QLocale::ShortFormat))) {
227 _systemTimestampFormatString = " h:mm:ss ap";
229 // 24-hour style used
230 _systemTimestampFormatString = " hh:mm:ss";
232 // Include a space to give the timestamp a small bit of padding between the border of the chat
233 // buffer window and the numbers. Helps with readability.
234 // If you change this to include brackets, e.g. "[hh:mm:ss]", also update
235 // ChatScene::updateTimestampHasBrackets() to true or false as needed!
239 // FIXME The following should trigger a reload/refresh of the chat view.
240 void UiStyle::setUseCustomTimestampFormat(bool enabled)
242 if (_useCustomTimestampFormat != enabled) {
243 _useCustomTimestampFormat = enabled;
247 void UiStyle::setTimestampFormatString(const QString &format)
249 if (_timestampFormatString != format) {
250 _timestampFormatString = format;
254 void UiStyle::enableSenderPrefixes(bool enabled)
256 if (_showSenderPrefixes != enabled) {
257 _showSenderPrefixes = enabled;
261 void UiStyle::enableSenderBrackets(bool enabled)
263 if (_showSenderBrackets != enabled) {
264 _showSenderBrackets = enabled;
269 void UiStyle::allowMircColorsChanged(const QVariant &v)
271 _allowMircColors = v.toBool();
276 /******** ItemView Styling *******/
278 void UiStyle::showItemViewIconsChanged(const QVariant &v)
280 _showBufferViewIcons = _showNickViewIcons = v.toBool();
284 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
286 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
287 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
289 if (role == Qt::DecorationRole) {
290 if (!_showBufferViewIcons)
294 case BufferInfo::ChannelBuffer:
296 return _channelJoinedIcon;
298 return _channelPartedIcon;
299 case BufferInfo::QueryBuffer:
301 return _userOfflineIcon;
302 if (index.data(NetworkModel::UserAwayRole).toBool())
303 return _userAwayIcon;
305 return _userOnlineIcon;
311 ItemFormatType fmtType = ItemFormatType::BufferViewItem;
313 case BufferInfo::StatusBuffer:
314 fmtType |= ItemFormatType::NetworkItem;
316 case BufferInfo::ChannelBuffer:
317 fmtType |= ItemFormatType::ChannelBufferItem;
319 case BufferInfo::QueryBuffer:
320 fmtType |= ItemFormatType::QueryBufferItem;
326 QTextCharFormat fmt = _listItemFormats.value(ItemFormatType::BufferViewItem);
327 fmt.merge(_listItemFormats.value(fmtType));
329 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
330 if (activity & BufferInfo::Highlight) {
331 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::HighlightedBuffer));
332 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::HighlightedBuffer));
334 else if (activity & BufferInfo::NewMessage) {
335 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::UnreadBuffer));
336 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::UnreadBuffer));
338 else if (activity & BufferInfo::OtherActivity) {
339 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::ActiveBuffer));
340 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::ActiveBuffer));
342 else if (!isActive) {
343 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::InactiveBuffer));
344 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::InactiveBuffer));
346 else if (index.data(NetworkModel::UserAwayRole).toBool()) {
347 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::UserAway));
348 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::UserAway));
351 return itemData(role, fmt);
355 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
357 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
359 if (role == Qt::DecorationRole) {
360 if (!_showNickViewIcons)
364 case NetworkModel::UserCategoryItemType:
366 int categoryId = index.data(TreeModel::SortRole).toInt();
367 if (categoryId <= _opIconLimit)
368 return _categoryOpIcon;
369 if (categoryId <= _voiceIconLimit)
370 return _categoryVoiceIcon;
371 return _userOnlineIcon;
373 case NetworkModel::IrcUserItemType:
374 if (index.data(NetworkModel::ItemActiveRole).toBool())
375 return _userOnlineIcon;
377 return _userAwayIcon;
383 QTextCharFormat fmt = _listItemFormats.value(ItemFormatType::NickViewItem);
386 case NetworkModel::IrcUserItemType:
387 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::IrcUserItem));
388 if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
389 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::UserAway));
390 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::IrcUserItem | ItemFormatType::UserAway));
393 case NetworkModel::UserCategoryItemType:
394 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::UserCategoryItem));
400 return itemData(role, fmt);
404 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
408 return format.font();
409 case Qt::ForegroundRole:
410 return format.property(QTextFormat::ForegroundBrush);
411 case Qt::BackgroundRole:
412 return format.property(QTextFormat::BackgroundBrush);
419 /******** Caching *******/
421 QTextCharFormat UiStyle::format(quint64 key) const
423 return _formats.value(key, QTextCharFormat());
428 // Create unique key for given Format object and message label
429 QString formatKey(const UiStyle::Format &format, UiStyle::MessageLabel label)
431 return QString::number(format.type | label, 16)
432 + (format.foreground.isValid() ? format.foreground.name() : "#------")
433 + (format.background.isValid() ? format.background.name() : "#------");
438 QTextCharFormat UiStyle::cachedFormat(const Format &format, MessageLabel messageLabel) const
440 return _formatCache.value(formatKey(format, messageLabel), QTextCharFormat());
444 void UiStyle::setCachedFormat(const QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const
446 _formatCache[formatKey(format, messageLabel)] = charFormat;
450 QFontMetricsF *UiStyle::fontMetrics(FormatType ftype, MessageLabel label) const
452 // QFontMetricsF is not assignable, so we need to store pointers :/
453 quint64 key = ftype | label;
455 if (_metricsCache.contains(key))
456 return _metricsCache.value(key);
458 return (_metricsCache[key] = new QFontMetricsF(format({ftype, {}, {}}, label).font()));
462 /******** Generate formats ********/
464 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
465 // until you _really_ know what you do!
466 QTextCharFormat UiStyle::format(const Format &format, MessageLabel label) const
468 if (format.type == FormatType::Invalid)
471 // Check if we have exactly this format readily cached already
472 QTextCharFormat charFormat = cachedFormat(format, label);
473 if (charFormat.properties().count())
476 mergeFormat(charFormat, format, label & 0xffff0000); // keep nickhash in label
478 for (quint32 mask = 0x00000001; mask <= static_cast<quint32>(MessageLabel::Selected); mask <<= 1) {
479 if (static_cast<quint32>(label) & mask) {
480 mergeFormat(charFormat, {format.type, {}, {}}, label & (mask | 0xffff0000)); // Don't re-apply extended colors
484 setCachedFormat(charFormat, format, label);
489 void UiStyle::mergeFormat(QTextCharFormat &charFormat, const Format &format, MessageLabel label) const
491 mergeSubElementFormat(charFormat, format.type & 0x00ff, label);
493 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
494 // or "foreground 01 and background 03"
495 if ((format.type & 0xfff00) != FormatType::Base) { // element format
496 for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
497 if ((format.type & mask) != FormatType::Base) {
498 mergeSubElementFormat(charFormat, format.type & (mask | 0xff), label);
503 // Now we handle color codes
504 // We assume that those can't be combined with subelement and message types.
505 if (_allowMircColors) {
506 // Classic mIRC colors (styleable)
507 if ((format.type & 0x00400000) != FormatType::Base)
508 mergeSubElementFormat(charFormat, format.type & 0x0f400000, label); // foreground
509 if ((format.type & 0x00800000) != FormatType::Base)
510 mergeSubElementFormat(charFormat, format.type & 0xf0800000, label); // background
511 if ((format.type & 0x00c00000) == static_cast<FormatType>(0x00c00000))
512 mergeSubElementFormat(charFormat, format.type & 0xffc00000, label); // combination
514 // Extended mIRC colors (hardcoded)
515 if (format.foreground.isValid())
516 charFormat.setForeground(format.foreground);
517 if (format.background.isValid())
518 charFormat.setBackground(format.background);
522 if ((format.type & FormatType::Url) != FormatType::Base)
523 mergeSubElementFormat(charFormat, format.type & (FormatType::Url | static_cast<FormatType>(0x000000ff)), label);
527 // Merge a subelement format into an existing message format
528 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, FormatType ftype, MessageLabel label) const
530 quint64 key = ftype | label;
531 fmt.merge(format(key & 0x0000ffffffffff00ull)); // label + subelement
532 fmt.merge(format(key & 0x0000ffffffffffffull)); // label + subelement + msgtype
533 fmt.merge(format(key & 0xffffffffffffff00ull)); // label + subelement + nickhash
534 fmt.merge(format(key & 0xffffffffffffffffull)); // label + subelement + nickhash + msgtype
538 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
542 return FormatType::PlainMsg;
543 case Message::Notice:
544 return FormatType::NoticeMsg;
545 case Message::Action:
546 return FormatType::ActionMsg;
548 return FormatType::NickMsg;
550 return FormatType::ModeMsg;
552 return FormatType::JoinMsg;
554 return FormatType::PartMsg;
556 return FormatType::QuitMsg;
558 return FormatType::KickMsg;
560 return FormatType::KillMsg;
561 case Message::Server:
562 return FormatType::ServerMsg;
564 return FormatType::InfoMsg;
566 return FormatType::ErrorMsg;
567 case Message::DayChange:
568 return FormatType::DayChangeMsg;
570 return FormatType::TopicMsg;
571 case Message::NetsplitJoin:
572 return FormatType::NetsplitJoinMsg;
573 case Message::NetsplitQuit:
574 return FormatType::NetsplitQuitMsg;
575 case Message::Invite:
576 return FormatType::InviteMsg;
578 //Q_ASSERT(false); // we need to handle all message types
579 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
580 return FormatType::ErrorMsg;
584 UiStyle::FormatType UiStyle::formatType(const QString &code)
586 if (_formatCodes.contains(code))
587 return _formatCodes.value(code);
588 return FormatType::Invalid;
592 QString UiStyle::formatCode(FormatType ftype)
594 return _formatCodes.key(ftype);
598 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, MessageLabel messageLabel) const
600 QList<QTextLayout::FormatRange> formatRanges;
601 QTextLayout::FormatRange range;
603 for (i = 0; i < formatList.size(); i++) {
604 range.format = format(formatList.at(i).second, messageLabel);
605 range.start = formatList.at(i).first;
607 formatRanges.last().length = range.start - formatRanges.last().start;
608 formatRanges.append(range);
611 formatRanges.last().length = textLength - formatRanges.last().start;
616 // This method expects a well-formatted string, there is no error checking!
617 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
618 UiStyle::StyledString UiStyle::styleString(const QString &s_, FormatType baseFormat)
622 result.formatList.emplace_back(std::make_pair(quint16{0}, Format{baseFormat, {}, {}}));
624 if (s.length() > 65535) {
625 // We use quint16 for indexes
626 qWarning() << QString("String too long to be styled: %1").arg(s);
627 result.plainText = s;
631 Format curfmt{baseFormat, {}, {}};
633 int pos = 0; quint16 length = 0;
635 pos = s.indexOf('%', pos);
637 if (s[pos+1] == '%') { // escaped %, we just remove one and continue
642 if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
643 if (s[pos+3] == '-') { // color off
644 curfmt.type &= 0x003fffff;
645 curfmt.foreground = QColor{};
646 curfmt.background = QColor{};
650 quint32 color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
651 // Color values 0-15 are traditional mIRC colors, defined in the stylesheet and thus going through the format engine
652 // Larger color values are hardcoded and applied separately (cf. https://modern.ircdocs.horse/formatting.html#colors-16-98)
653 if (s[pos+3] == 'f') {
655 // Traditional mIRC color, defined in the stylesheet
656 curfmt.type &= 0xf0ffffff;
657 curfmt.type |= color << 24 | 0x00400000;
658 curfmt.foreground = QColor{};
661 curfmt.type &= 0xf0bfffff; // mask out traditional foreground color
662 curfmt.foreground = extendedMircColor(color);
667 curfmt.type &= 0x0fffffff;
668 curfmt.type |= color << 28 | 0x00800000;
669 curfmt.background = QColor{};
672 curfmt.type &= 0x0f7fffff; // mask out traditional background color
673 curfmt.background = extendedMircColor(color);
679 else if (s[pos+1] == 'O') { // reset formatting
680 curfmt.type &= 0x000000ff; // we keep message type-specific formatting
681 curfmt.foreground = QColor{};
682 curfmt.background = QColor{};
685 else if (s[pos+1] == 'R') { // reverse
686 // TODO: implement reverse formatting
690 else { // all others are toggles
691 QString code = QString("%") + s[pos+1];
692 if (s[pos+1] == 'D') code += s[pos+2];
693 FormatType ftype = formatType(code);
694 if (ftype == FormatType::Invalid) {
696 qWarning() << (QString("Invalid format code in string: %1").arg(s));
699 curfmt.type ^= ftype;
700 length = code.length();
702 s.remove(pos, length);
703 if (pos == result.formatList.back().first)
704 result.formatList.back().second = curfmt;
706 result.formatList.emplace_back(std::make_pair(pos, curfmt));
708 result.plainText = s;
713 QString UiStyle::mircToInternal(const QString &mirc_)
716 mirc.reserve(mirc_.size());
717 foreach (const QChar &c, mirc_) {
718 if ((c < '\x20' || c == '\x7f') && c != '\x03') {
719 switch (c.unicode()) {
740 mirc += QChar(0x2421);
743 mirc += QChar(0x2400 + c.unicode());
752 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
753 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
754 // %Dc- turns color off.
755 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
756 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
759 pos = mirc.indexOf('\x03', pos);
761 break; // no more mirc color codes
763 int l = mirc.length();
765 // check for fg color
766 if (i < l && mirc[i].isDigit()) {
768 if (i < l && mirc[i].isDigit())
769 num.append(mirc[i++]);
772 ins = QString("%Dcf%1").arg(num);
774 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
777 if (i < l && mirc[i].isDigit())
778 num.append(mirc[i++]);
781 ins += QString("%Dcb%1").arg(num);
787 mirc.replace(pos, i-pos, ins);
793 QString UiStyle::systemTimestampFormatString()
795 if (_systemTimestampFormatString.isEmpty()) {
796 // Calculate and cache the system timestamp format string
797 updateSystemTimestampFormat();
799 return _systemTimestampFormatString;
803 QString UiStyle::timestampFormatString()
805 if (useCustomTimestampFormat()) {
806 return _timestampFormatString;
808 return systemTimestampFormatString();
813 /***********************************************************************************/
814 UiStyle::StyledMessage::StyledMessage(const Message &msg)
818 // Don't compute the sender hash for message types without a nickname embedded
819 case Message::Server:
822 case Message::DayChange:
824 case Message::Invite:
825 // Don't compute the sender hash for messages with multiple nicks
826 // Fixing this without breaking themes would be.. complex.
827 case Message::NetsplitJoin:
828 case Message::NetsplitQuit:
830 // Don't compute the sender hash for message types that are not yet completed elsewhere
835 // Compute the sender hash for all other message types
842 void UiStyle::StyledMessage::style() const
844 QString user = userFromMask(sender());
845 QString host = hostFromMask(sender());
846 QString nick = nickFromMask(sender());
847 QString txt = UiStyle::mircToInternal(contents());
848 QString bufferName = bufferInfo().bufferName();
849 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
850 host.replace('%', "%%"); // hostnames too...
851 user.replace('%', "%%"); // and the username...
852 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
853 const int maxNetsplitNicks = 15;
858 t = QString("%1").arg(txt); break;
859 case Message::Notice:
860 t = QString("%1").arg(txt); break;
861 case Message::Action:
862 t = QString("%DN%1%DN %2").arg(nick).arg(txt);
866 if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
867 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
871 if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
872 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
876 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
879 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
880 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
884 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
885 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
889 QString victim = txt.section(" ", 0, 0);
890 QString kickmsg = txt.section(" ", 1);
892 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
893 if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
896 //case Message::Kill: FIXME
898 case Message::Server:
899 t = QString("%1").arg(txt); break;
901 t = QString("%1").arg(txt); break;
903 t = QString("%1").arg(txt); break;
904 case Message::DayChange:
906 //: Day Change Message
907 t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
911 t = QString("%1").arg(txt); break;
912 case Message::NetsplitJoin:
914 QStringList users = txt.split("#:#");
915 QStringList servers = users.takeLast().split(" ");
917 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
918 users[i] = nickFromMask(users.at(i));
920 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
921 if (users.count() <= maxNetsplitNicks)
922 t.append(QString("%DN%1%DN").arg(users.join(", ")));
924 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
927 case Message::NetsplitQuit:
929 QStringList users = txt.split("#:#");
930 QStringList servers = users.takeLast().split(" ");
932 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
933 users[i] = nickFromMask(users.at(i));
935 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
937 if (users.count() <= maxNetsplitNicks)
938 t.append(QString("%DN%1%DN").arg(users.join(", ")));
940 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
943 case Message::Invite:
944 t = QString("%1").arg(txt); break;
946 t = QString("[%1]").arg(txt);
948 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
952 const QString &UiStyle::StyledMessage::plainContents() const
954 if (_contents.plainText.isNull())
957 return _contents.plainText;
961 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
963 if (_contents.plainText.isNull())
966 return _contents.formatList;
970 QString UiStyle::StyledMessage::decoratedTimestamp() const
972 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
976 QString UiStyle::StyledMessage::plainSender() const
980 case Message::Notice:
981 return nickFromMask(sender());
988 QString UiStyle::StyledMessage::decoratedSender() const
990 QString _senderPrefixes;
991 if (_showSenderPrefixes) {
992 _senderPrefixes = senderPrefixes();
997 if (_showSenderBrackets)
998 return QString("<%1%2>").arg(_senderPrefixes, plainSender());
1000 return QString("%1%2").arg(_senderPrefixes, plainSender());
1001 case Message::Notice:
1002 return QString("[%1%2]").arg(_senderPrefixes, plainSender());
1003 case Message::Action:
1019 case Message::Server:
1023 case Message::Error:
1025 case Message::DayChange:
1027 case Message::Topic:
1029 case Message::NetsplitJoin:
1031 case Message::NetsplitQuit:
1033 case Message::Invite:
1037 return QString("%1%2").arg(_senderPrefixes, plainSender());
1041 // FIXME hardcoded to 16 sender hashes
1042 quint8 UiStyle::StyledMessage::senderHash() const
1044 if (_senderHash != 0xff)
1049 // HACK: Until multiple nicknames with different colors can be solved in the theming engine,
1050 // for /nick change notifications, use the color of the new nickname (if possible), not the old
1052 if (type() == Message::Nick) {
1053 // New nickname is given as contents. Change to that.
1054 nick = stripFormatCodes(contents()).toLower();
1056 // Just use the sender directly
1057 nick = nickFromMask(sender()).toLower();
1060 if (!nick.isEmpty()) {
1062 while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
1064 if (chopCount < nick.size())
1065 nick.chop(chopCount);
1067 quint16 hash = qChecksum(nick.toLatin1().data(), nick.toLatin1().size());
1068 return (_senderHash = (hash & 0xf) + 1);
1071 /***********************************************************************************/
1073 #if QT_VERSION < 0x050000
1074 uint qHash(UiStyle::ItemFormatType key)
1076 return qHash(static_cast<quint32>(key));
1081 uint qHash(UiStyle::ItemFormatType key, uint seed)
1083 return qHash(static_cast<quint32>(key), seed);
1087 UiStyle::FormatType operator|(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
1089 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1092 UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs)
1094 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1099 UiStyle::FormatType operator|(UiStyle::FormatType lhs, quint32 rhs)
1101 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
1105 UiStyle::FormatType& operator|=(UiStyle::FormatType &lhs, quint32 rhs)
1107 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
1112 UiStyle::FormatType operator&(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
1114 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1118 UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
1120 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1125 UiStyle::FormatType operator&(UiStyle::FormatType lhs, quint32 rhs)
1127 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
1131 UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, quint32 rhs)
1133 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
1138 UiStyle::FormatType& operator^=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
1140 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) ^ static_cast<quint32>(rhs));
1145 UiStyle::MessageLabel operator|(UiStyle::MessageLabel lhs, UiStyle::MessageLabel rhs)
1147 return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1151 UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
1153 lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1158 UiStyle::MessageLabel operator&(UiStyle::MessageLabel lhs, quint32 rhs)
1160 return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & rhs);
1164 UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
1166 lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1171 quint64 operator|(UiStyle::FormatType lhs, UiStyle::MessageLabel rhs)
1173 return static_cast<quint64>(lhs) | (static_cast<quint64>(rhs) << 32ull);
1177 UiStyle::ItemFormatType operator|(UiStyle::ItemFormatType lhs, UiStyle::ItemFormatType rhs)
1179 return static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1183 UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType &lhs, UiStyle::ItemFormatType rhs)
1185 lhs = static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1189 /***********************************************************************************/
1191 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
1193 out << static_cast<quint16>(formatList.size());
1194 UiStyle::FormatList::const_iterator it = formatList.begin();
1195 while (it != formatList.end()) {
1197 << static_cast<quint32>(it->second.type)
1198 << it->second.foreground
1199 << it->second.background;
1206 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
1210 for (quint16 i = 0; i < cnt; i++) {
1215 in >> pos >> ftype >> foreground >> background;
1216 formatList.emplace_back(std::make_pair(quint16{pos}, UiStyle::Format{static_cast<UiStyle::FormatType>(ftype), foreground, background}));