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 static bool registered = []() {
76 qRegisterMetaType<FormatList>();
77 qRegisterMetaTypeStreamOperators<FormatList>();
82 _uiStylePalette = QVector<QBrush>(static_cast<int>(ColorRole::NumRoles), QBrush());
84 // Now initialize the mapping between FormatCodes and FormatTypes...
85 _formatCodes["%O"] = FormatType::Base;
86 _formatCodes["%B"] = FormatType::Bold;
87 _formatCodes["%S"] = FormatType::Italic;
88 _formatCodes["%U"] = FormatType::Underline;
89 _formatCodes["%R"] = FormatType::Reverse;
91 _formatCodes["%DN"] = FormatType::Nick;
92 _formatCodes["%DH"] = FormatType::Hostmask;
93 _formatCodes["%DC"] = FormatType::ChannelName;
94 _formatCodes["%DM"] = FormatType::ModeFlags;
95 _formatCodes["%DU"] = FormatType::Url;
97 // Initialize fallback defaults
98 // NOTE: If you change this, update qtui/chatviewsettings.h, too. More explanations available
100 setUseCustomTimestampFormat(false);
101 setTimestampFormatString(" hh:mm:ss");
102 enableSenderPrefixes(false);
103 enableSenderBrackets(true);
105 // BufferView / NickView settings
107 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
108 s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
110 _allowMircColors = s.value("AllowMircColors", true).toBool();
111 s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
119 qDeleteAll(_metricsCache);
123 void UiStyle::reload()
129 void UiStyle::loadStyleSheet()
131 qDeleteAll(_metricsCache);
132 _metricsCache.clear();
133 _formatCache.clear();
139 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
140 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
141 if (s.value("UseCustomStyleSheet", false).toBool()) {
142 QString customSheetPath(s.value("CustomStyleSheetPath").toString());
143 QString customSheet = loadStyleSheet("file:///" + customSheetPath, true);
144 if (customSheet.isEmpty()) {
145 // MIGRATION: changed default install path for data from /usr/share/apps to /usr/share
146 if (customSheetPath.startsWith("/usr/share/apps/quassel")) {
147 customSheetPath.replace(QRegExp("^/usr/share/apps"), "/usr/share");
148 customSheet = loadStyleSheet("file:///" + customSheetPath, true);
149 if (!customSheet.isEmpty()) {
150 s.setValue("CustomStyleSheetPath", customSheetPath);
151 qDebug() << "Custom stylesheet path migrated to" << customSheetPath;
155 styleSheet += customSheet;
157 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
159 if (!styleSheet.isEmpty()) {
161 parser.processStyleSheet(styleSheet);
162 QApplication::setPalette(parser.palette());
164 _uiStylePalette = parser.uiStylePalette();
165 _formats = parser.formats();
166 _listItemFormats = parser.listItemFormats();
168 styleSheet = styleSheet.trimmed();
169 if (!styleSheet.isEmpty())
170 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
177 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
179 QString ss = styleSheet;
180 if (ss.startsWith("file:///")) {
186 if (file.open(QFile::ReadOnly)) {
187 QTextStream stream(&file);
188 ss = stream.readAll();
193 qWarning() << "Could not open stylesheet file:" << file.fileName();
201 void UiStyle::updateSystemTimestampFormat()
203 // Does the system locale use AM/PM designators? For example:
207 // 24-hour: hh:mm ADD things
208 // For timestamp format, see https://doc.qt.io/qt-5/qdatetime.html#toString
209 // This won't update if the system locale is changed while Quassel is running. If need be,
210 // Quassel could hook into notifications of changing system locale to update this.
212 // Match any AP or A designation if on a word boundary, including underscores.
213 // .*(\b|_)(A|AP)(\b|_).*
214 // .* Match any number of characters
215 // \b Match a word boundary, i.e. "AAA.BBB", "." is matched
216 // _ Match the literal character '_' (not considered a word boundary)
217 // (X|Y) Match either X or Y, exactly
219 // Note that '\' must be escaped as '\\'
220 // QRegExp does not support (?> ...), so it's replaced with standard matching, (...)
221 // Helpful interactive website for debugging and explaining: https://regex101.com/
222 const QRegExp regExpMatchAMPM(".*(\\b|_)(A|AP)(\\b|_).*", Qt::CaseInsensitive);
224 if (regExpMatchAMPM.exactMatch(QLocale::system().timeFormat(QLocale::ShortFormat))) {
226 _systemTimestampFormatString = " h:mm:ss ap";
228 // 24-hour style used
229 _systemTimestampFormatString = " hh:mm:ss";
231 // Include a space to give the timestamp a small bit of padding between the border of the chat
232 // buffer window and the numbers. Helps with readability.
233 // If you change this to include brackets, e.g. "[hh:mm:ss]", also update
234 // ChatScene::updateTimestampHasBrackets() to true or false as needed!
238 // FIXME The following should trigger a reload/refresh of the chat view.
239 void UiStyle::setUseCustomTimestampFormat(bool enabled)
241 if (_useCustomTimestampFormat != enabled) {
242 _useCustomTimestampFormat = enabled;
246 void UiStyle::setTimestampFormatString(const QString &format)
248 if (_timestampFormatString != format) {
249 _timestampFormatString = format;
253 void UiStyle::enableSenderPrefixes(bool enabled)
255 if (_showSenderPrefixes != enabled) {
256 _showSenderPrefixes = enabled;
260 void UiStyle::enableSenderBrackets(bool enabled)
262 if (_showSenderBrackets != enabled) {
263 _showSenderBrackets = enabled;
268 void UiStyle::allowMircColorsChanged(const QVariant &v)
270 _allowMircColors = v.toBool();
275 /******** ItemView Styling *******/
277 void UiStyle::showItemViewIconsChanged(const QVariant &v)
279 _showBufferViewIcons = _showNickViewIcons = v.toBool();
283 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
285 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
286 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
288 if (role == Qt::DecorationRole) {
289 if (!_showBufferViewIcons)
293 case BufferInfo::ChannelBuffer:
295 return _channelJoinedIcon;
297 return _channelPartedIcon;
298 case BufferInfo::QueryBuffer:
300 return _userOfflineIcon;
301 if (index.data(NetworkModel::UserAwayRole).toBool())
302 return _userAwayIcon;
304 return _userOnlineIcon;
310 ItemFormatType fmtType = ItemFormatType::BufferViewItem;
312 case BufferInfo::StatusBuffer:
313 fmtType |= ItemFormatType::NetworkItem;
315 case BufferInfo::ChannelBuffer:
316 fmtType |= ItemFormatType::ChannelBufferItem;
318 case BufferInfo::QueryBuffer:
319 fmtType |= ItemFormatType::QueryBufferItem;
325 QTextCharFormat fmt = _listItemFormats.value(ItemFormatType::BufferViewItem);
326 fmt.merge(_listItemFormats.value(fmtType));
328 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
329 if (activity & BufferInfo::Highlight) {
330 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::HighlightedBuffer));
331 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::HighlightedBuffer));
333 else if (activity & BufferInfo::NewMessage) {
334 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::UnreadBuffer));
335 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::UnreadBuffer));
337 else if (activity & BufferInfo::OtherActivity) {
338 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::ActiveBuffer));
339 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::ActiveBuffer));
341 else if (!isActive) {
342 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::InactiveBuffer));
343 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::InactiveBuffer));
345 else if (index.data(NetworkModel::UserAwayRole).toBool()) {
346 fmt.merge(_listItemFormats.value(ItemFormatType::BufferViewItem | ItemFormatType::UserAway));
347 fmt.merge(_listItemFormats.value(fmtType | ItemFormatType::UserAway));
350 return itemData(role, fmt);
354 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
356 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
358 if (role == Qt::DecorationRole) {
359 if (!_showNickViewIcons)
363 case NetworkModel::UserCategoryItemType:
365 int categoryId = index.data(TreeModel::SortRole).toInt();
366 if (categoryId <= _opIconLimit)
367 return _categoryOpIcon;
368 if (categoryId <= _voiceIconLimit)
369 return _categoryVoiceIcon;
370 return _userOnlineIcon;
372 case NetworkModel::IrcUserItemType:
373 if (index.data(NetworkModel::ItemActiveRole).toBool())
374 return _userOnlineIcon;
376 return _userAwayIcon;
382 QTextCharFormat fmt = _listItemFormats.value(ItemFormatType::NickViewItem);
385 case NetworkModel::IrcUserItemType:
386 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::IrcUserItem));
387 if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
388 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::UserAway));
389 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::IrcUserItem | ItemFormatType::UserAway));
392 case NetworkModel::UserCategoryItemType:
393 fmt.merge(_listItemFormats.value(ItemFormatType::NickViewItem | ItemFormatType::UserCategoryItem));
399 return itemData(role, fmt);
403 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
407 return format.font();
408 case Qt::ForegroundRole:
409 return format.property(QTextFormat::ForegroundBrush);
410 case Qt::BackgroundRole:
411 return format.property(QTextFormat::BackgroundBrush);
418 /******** Caching *******/
420 QTextCharFormat UiStyle::format(quint64 key) const
422 return _formats.value(key, QTextCharFormat());
427 // Create unique key for given Format object and message label
428 QString formatKey(const UiStyle::Format &format, UiStyle::MessageLabel label)
430 return QString::number(format.type | label, 16)
431 + (format.foreground.isValid() ? format.foreground.name() : "#------")
432 + (format.background.isValid() ? format.background.name() : "#------");
437 QTextCharFormat UiStyle::cachedFormat(const Format &format, MessageLabel messageLabel) const
439 return _formatCache.value(formatKey(format, messageLabel), QTextCharFormat());
443 void UiStyle::setCachedFormat(const QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const
445 _formatCache[formatKey(format, messageLabel)] = charFormat;
449 QFontMetricsF *UiStyle::fontMetrics(FormatType ftype, MessageLabel label) const
451 // QFontMetricsF is not assignable, so we need to store pointers :/
452 quint64 key = ftype | label;
454 if (_metricsCache.contains(key))
455 return _metricsCache.value(key);
457 return (_metricsCache[key] = new QFontMetricsF(format({ftype, {}, {}}, label).font()));
461 /******** Generate formats ********/
463 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
464 // until you _really_ know what you do!
465 QTextCharFormat UiStyle::format(const Format &format, MessageLabel label) const
467 if (format.type == FormatType::Invalid)
470 // Check if we have exactly this format readily cached already
471 QTextCharFormat charFormat = cachedFormat(format, label);
472 if (charFormat.properties().count())
475 mergeFormat(charFormat, format, label & 0xffff0000); // keep nickhash in label
477 for (quint32 mask = 0x00000001; mask <= static_cast<quint32>(MessageLabel::Selected); mask <<= 1) {
478 if (static_cast<quint32>(label) & mask) {
479 mergeFormat(charFormat, {format.type, {}, {}}, label & (mask | 0xffff0000)); // Don't re-apply extended colors
483 setCachedFormat(charFormat, format, label);
488 void UiStyle::mergeFormat(QTextCharFormat &charFormat, const Format &format, MessageLabel label) const
490 mergeSubElementFormat(charFormat, format.type & 0x00ff, label);
492 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
493 // or "foreground 01 and background 03"
494 if ((format.type & 0xfff00) != FormatType::Base) { // element format
495 for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
496 if ((format.type & mask) != FormatType::Base) {
497 mergeSubElementFormat(charFormat, format.type & (mask | 0xff), label);
502 // Now we handle color codes
503 // We assume that those can't be combined with subelement and message types.
504 if (_allowMircColors) {
505 // Classic mIRC colors (styleable)
506 if ((format.type & 0x00400000) != FormatType::Base)
507 mergeSubElementFormat(charFormat, format.type & 0x0f400000, label); // foreground
508 if ((format.type & 0x00800000) != FormatType::Base)
509 mergeSubElementFormat(charFormat, format.type & 0xf0800000, label); // background
510 if ((format.type & 0x00c00000) == static_cast<FormatType>(0x00c00000))
511 mergeSubElementFormat(charFormat, format.type & 0xffc00000, label); // combination
513 // Extended mIRC colors (hardcoded)
514 if (format.foreground.isValid())
515 charFormat.setForeground(format.foreground);
516 if (format.background.isValid())
517 charFormat.setBackground(format.background);
521 if ((format.type & FormatType::Url) != FormatType::Base)
522 mergeSubElementFormat(charFormat, format.type & (FormatType::Url | static_cast<FormatType>(0x000000ff)), label);
526 // Merge a subelement format into an existing message format
527 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, FormatType ftype, MessageLabel label) const
529 quint64 key = ftype | label;
530 fmt.merge(format(key & 0x0000ffffffffff00ull)); // label + subelement
531 fmt.merge(format(key & 0x0000ffffffffffffull)); // label + subelement + msgtype
532 fmt.merge(format(key & 0xffffffffffffff00ull)); // label + subelement + nickhash
533 fmt.merge(format(key & 0xffffffffffffffffull)); // label + subelement + nickhash + msgtype
537 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
541 return FormatType::PlainMsg;
542 case Message::Notice:
543 return FormatType::NoticeMsg;
544 case Message::Action:
545 return FormatType::ActionMsg;
547 return FormatType::NickMsg;
549 return FormatType::ModeMsg;
551 return FormatType::JoinMsg;
553 return FormatType::PartMsg;
555 return FormatType::QuitMsg;
557 return FormatType::KickMsg;
559 return FormatType::KillMsg;
560 case Message::Server:
561 return FormatType::ServerMsg;
563 return FormatType::InfoMsg;
565 return FormatType::ErrorMsg;
566 case Message::DayChange:
567 return FormatType::DayChangeMsg;
569 return FormatType::TopicMsg;
570 case Message::NetsplitJoin:
571 return FormatType::NetsplitJoinMsg;
572 case Message::NetsplitQuit:
573 return FormatType::NetsplitQuitMsg;
574 case Message::Invite:
575 return FormatType::InviteMsg;
577 //Q_ASSERT(false); // we need to handle all message types
578 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
579 return FormatType::ErrorMsg;
583 UiStyle::FormatType UiStyle::formatType(const QString &code)
585 if (_formatCodes.contains(code))
586 return _formatCodes.value(code);
587 return FormatType::Invalid;
591 QString UiStyle::formatCode(FormatType ftype)
593 return _formatCodes.key(ftype);
597 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, MessageLabel messageLabel) const
599 QList<QTextLayout::FormatRange> formatRanges;
600 QTextLayout::FormatRange range;
602 for (i = 0; i < formatList.size(); i++) {
603 range.format = format(formatList.at(i).second, messageLabel);
604 range.start = formatList.at(i).first;
606 formatRanges.last().length = range.start - formatRanges.last().start;
607 formatRanges.append(range);
610 formatRanges.last().length = textLength - formatRanges.last().start;
615 // This method expects a well-formatted string, there is no error checking!
616 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
617 UiStyle::StyledString UiStyle::styleString(const QString &s_, FormatType baseFormat)
621 result.formatList.emplace_back(std::make_pair(quint16{0}, Format{baseFormat, {}, {}}));
623 if (s.length() > 65535) {
624 // We use quint16 for indexes
625 qWarning() << QString("String too long to be styled: %1").arg(s);
626 result.plainText = s;
630 Format curfmt{baseFormat, {}, {}};
632 int pos = 0; quint16 length = 0;
634 pos = s.indexOf('%', pos);
636 if (s[pos+1] == '%') { // escaped %, we just remove one and continue
641 if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
642 if (s[pos+3] == '-') { // color off
643 curfmt.type &= 0x003fffff;
644 curfmt.foreground = QColor{};
645 curfmt.background = QColor{};
649 quint32 color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
650 // Color values 0-15 are traditional mIRC colors, defined in the stylesheet and thus going through the format engine
651 // Larger color values are hardcoded and applied separately (cf. https://modern.ircdocs.horse/formatting.html#colors-16-98)
652 if (s[pos+3] == 'f') {
654 // Traditional mIRC color, defined in the stylesheet
655 curfmt.type &= 0xf0ffffff;
656 curfmt.type |= color << 24 | 0x00400000;
657 curfmt.foreground = QColor{};
660 curfmt.type &= 0xf0bfffff; // mask out traditional foreground color
661 curfmt.foreground = extendedMircColor(color);
666 curfmt.type &= 0x0fffffff;
667 curfmt.type |= color << 28 | 0x00800000;
668 curfmt.background = QColor{};
671 curfmt.type &= 0x0f7fffff; // mask out traditional background color
672 curfmt.background = extendedMircColor(color);
678 else if (s[pos+1] == 'O') { // reset formatting
679 curfmt.type &= 0x000000ff; // we keep message type-specific formatting
680 curfmt.foreground = QColor{};
681 curfmt.background = QColor{};
684 else if (s[pos+1] == 'R') { // reverse
685 // TODO: implement reverse formatting
689 else { // all others are toggles
690 QString code = QString("%") + s[pos+1];
691 if (s[pos+1] == 'D') code += s[pos+2];
692 FormatType ftype = formatType(code);
693 if (ftype == FormatType::Invalid) {
695 qWarning() << (QString("Invalid format code in string: %1").arg(s));
698 curfmt.type ^= ftype;
699 length = code.length();
701 s.remove(pos, length);
702 if (pos == result.formatList.back().first)
703 result.formatList.back().second = curfmt;
705 result.formatList.emplace_back(std::make_pair(pos, curfmt));
707 result.plainText = s;
712 QString UiStyle::mircToInternal(const QString &mirc_)
715 mirc.reserve(mirc_.size());
716 foreach (const QChar &c, mirc_) {
717 if ((c < '\x20' || c == '\x7f') && c != '\x03') {
718 switch (c.unicode()) {
739 mirc += QChar(0x2421);
742 mirc += QChar(0x2400 + c.unicode());
751 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
752 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
753 // %Dc- turns color off.
754 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
755 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
758 pos = mirc.indexOf('\x03', pos);
760 break; // no more mirc color codes
762 int l = mirc.length();
764 // check for fg color
765 if (i < l && mirc[i].isDigit()) {
767 if (i < l && mirc[i].isDigit())
768 num.append(mirc[i++]);
771 ins = QString("%Dcf%1").arg(num);
773 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
776 if (i < l && mirc[i].isDigit())
777 num.append(mirc[i++]);
780 ins += QString("%Dcb%1").arg(num);
786 mirc.replace(pos, i-pos, ins);
792 QString UiStyle::systemTimestampFormatString()
794 if (_systemTimestampFormatString.isEmpty()) {
795 // Calculate and cache the system timestamp format string
796 updateSystemTimestampFormat();
798 return _systemTimestampFormatString;
802 QString UiStyle::timestampFormatString()
804 if (useCustomTimestampFormat()) {
805 return _timestampFormatString;
807 return systemTimestampFormatString();
812 /***********************************************************************************/
813 UiStyle::StyledMessage::StyledMessage(const Message &msg)
817 // Don't compute the sender hash for message types without a nickname embedded
818 case Message::Server:
821 case Message::DayChange:
823 case Message::Invite:
824 // Don't compute the sender hash for messages with multiple nicks
825 // Fixing this without breaking themes would be.. complex.
826 case Message::NetsplitJoin:
827 case Message::NetsplitQuit:
829 // Don't compute the sender hash for message types that are not yet completed elsewhere
834 // Compute the sender hash for all other message types
841 void UiStyle::StyledMessage::style() const
843 QString user = userFromMask(sender());
844 QString host = hostFromMask(sender());
845 QString nick = nickFromMask(sender());
846 QString txt = UiStyle::mircToInternal(contents());
847 QString bufferName = bufferInfo().bufferName();
848 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
849 host.replace('%', "%%"); // hostnames too...
850 user.replace('%', "%%"); // and the username...
851 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
852 const int maxNetsplitNicks = 15;
857 t = QString("%1").arg(txt); break;
858 case Message::Notice:
859 t = QString("%1").arg(txt); break;
860 case Message::Action:
861 t = QString("%DN%1%DN %2").arg(nick).arg(txt);
865 if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
866 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
870 if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
871 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
875 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
878 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
879 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
883 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
884 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
888 QString victim = txt.section(" ", 0, 0);
889 QString kickmsg = txt.section(" ", 1);
891 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
892 if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
895 //case Message::Kill: FIXME
897 case Message::Server:
898 t = QString("%1").arg(txt); break;
900 t = QString("%1").arg(txt); break;
902 t = QString("%1").arg(txt); break;
903 case Message::DayChange:
905 //: Day Change Message
906 t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
910 t = QString("%1").arg(txt); break;
911 case Message::NetsplitJoin:
913 QStringList users = txt.split("#:#");
914 QStringList servers = users.takeLast().split(" ");
916 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
917 users[i] = nickFromMask(users.at(i));
919 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
920 if (users.count() <= maxNetsplitNicks)
921 t.append(QString("%DN%1%DN").arg(users.join(", ")));
923 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
926 case Message::NetsplitQuit:
928 QStringList users = txt.split("#:#");
929 QStringList servers = users.takeLast().split(" ");
931 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
932 users[i] = nickFromMask(users.at(i));
934 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
936 if (users.count() <= maxNetsplitNicks)
937 t.append(QString("%DN%1%DN").arg(users.join(", ")));
939 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
942 case Message::Invite:
943 t = QString("%1").arg(txt); break;
945 t = QString("[%1]").arg(txt);
947 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
951 const QString &UiStyle::StyledMessage::plainContents() const
953 if (_contents.plainText.isNull())
956 return _contents.plainText;
960 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
962 if (_contents.plainText.isNull())
965 return _contents.formatList;
969 QString UiStyle::StyledMessage::decoratedTimestamp() const
971 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
975 QString UiStyle::StyledMessage::plainSender() const
979 case Message::Notice:
980 return nickFromMask(sender());
987 QString UiStyle::StyledMessage::decoratedSender() const
989 QString _senderPrefixes;
990 if (_showSenderPrefixes) {
991 _senderPrefixes = senderPrefixes();
996 if (_showSenderBrackets)
997 return QString("<%1%2>").arg(_senderPrefixes, plainSender());
999 return QString("%1%2").arg(_senderPrefixes, plainSender());
1000 case Message::Notice:
1001 return QString("[%1%2]").arg(_senderPrefixes, plainSender());
1002 case Message::Action:
1018 case Message::Server:
1022 case Message::Error:
1024 case Message::DayChange:
1026 case Message::Topic:
1028 case Message::NetsplitJoin:
1030 case Message::NetsplitQuit:
1032 case Message::Invite:
1036 return QString("%1%2").arg(_senderPrefixes, plainSender());
1040 // FIXME hardcoded to 16 sender hashes
1041 quint8 UiStyle::StyledMessage::senderHash() const
1043 if (_senderHash != 0xff)
1048 // HACK: Until multiple nicknames with different colors can be solved in the theming engine,
1049 // for /nick change notifications, use the color of the new nickname (if possible), not the old
1051 if (type() == Message::Nick) {
1052 // New nickname is given as contents. Change to that.
1053 nick = stripFormatCodes(contents()).toLower();
1055 // Just use the sender directly
1056 nick = nickFromMask(sender()).toLower();
1059 if (!nick.isEmpty()) {
1061 while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
1063 if (chopCount < nick.size())
1064 nick.chop(chopCount);
1066 quint16 hash = qChecksum(nick.toLatin1().data(), nick.toLatin1().size());
1067 return (_senderHash = (hash & 0xf) + 1);
1070 /***********************************************************************************/
1072 #if QT_VERSION < 0x050000
1073 uint qHash(UiStyle::ItemFormatType key)
1075 return qHash(static_cast<quint32>(key));
1080 uint qHash(UiStyle::ItemFormatType key, uint seed)
1082 return qHash(static_cast<quint32>(key), seed);
1086 UiStyle::FormatType operator|(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
1088 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1091 UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs)
1093 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1098 UiStyle::FormatType operator|(UiStyle::FormatType lhs, quint32 rhs)
1100 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
1104 UiStyle::FormatType& operator|=(UiStyle::FormatType &lhs, quint32 rhs)
1106 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
1111 UiStyle::FormatType operator&(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
1113 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1117 UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
1119 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1124 UiStyle::FormatType operator&(UiStyle::FormatType lhs, quint32 rhs)
1126 return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
1130 UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, quint32 rhs)
1132 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
1137 UiStyle::FormatType& operator^=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
1139 lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) ^ static_cast<quint32>(rhs));
1144 UiStyle::MessageLabel operator|(UiStyle::MessageLabel lhs, UiStyle::MessageLabel rhs)
1146 return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1150 UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
1152 lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1157 UiStyle::MessageLabel operator&(UiStyle::MessageLabel lhs, quint32 rhs)
1159 return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & rhs);
1163 UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
1165 lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
1170 quint64 operator|(UiStyle::FormatType lhs, UiStyle::MessageLabel rhs)
1172 return static_cast<quint64>(lhs) | (static_cast<quint64>(rhs) << 32ull);
1176 UiStyle::ItemFormatType operator|(UiStyle::ItemFormatType lhs, UiStyle::ItemFormatType rhs)
1178 return static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1182 UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType &lhs, UiStyle::ItemFormatType rhs)
1184 lhs = static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
1188 /***********************************************************************************/
1190 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
1192 out << static_cast<quint16>(formatList.size());
1193 UiStyle::FormatList::const_iterator it = formatList.begin();
1194 while (it != formatList.end()) {
1196 << static_cast<quint32>(it->second.type)
1197 << it->second.foreground
1198 << it->second.background;
1205 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
1209 for (quint16 i = 0; i < cnt; i++) {
1214 in >> pos >> ftype >> foreground >> background;
1215 formatList.emplace_back(std::make_pair(quint16{pos}, UiStyle::Format{static_cast<UiStyle::FormatType>(ftype), foreground, background}));