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 ***************************************************************************/
21 #include <QApplication>
24 #include "buffersettings.h"
25 #include "qssparser.h"
28 #include "uisettings.h"
31 QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
32 bool UiStyle::_useCustomTimestampFormat; /// If true, use the custom timestamp format
33 QString UiStyle::_timestampFormatString; /// Timestamp format
34 QString UiStyle::_systemTimestampFormatString; /// Cached copy of system locale timestamp format
35 bool UiStyle::_showSenderBrackets; /// If true, show brackets around sender names
37 UiStyle::UiStyle(QObject *parent)
39 _channelJoinedIcon(QIcon::fromTheme("irc-channel-joined", QIcon(":/icons/irc-channel-joined.png"))),
40 _channelPartedIcon(QIcon::fromTheme("irc-channel-parted", QIcon(":/icons/irc-channel-parted.png"))),
41 _userOfflineIcon(QIcon::fromTheme("im-user-offline", QIcon::fromTheme("user-offline", QIcon(":/icons/im-user-offline.png")))),
42 _userOnlineIcon(QIcon::fromTheme("im-user", QIcon::fromTheme("user-available", QIcon(":/icons/im-user.png")))), // im-user-* are non-standard oxygen extensions
43 _userAwayIcon(QIcon::fromTheme("im-user-away", QIcon::fromTheme("user-away", QIcon(":/icons/im-user-away.png")))),
44 _categoryOpIcon(QIcon::fromTheme("irc-operator")),
45 _categoryVoiceIcon(QIcon::fromTheme("irc-voice")),
46 _opIconLimit(UserCategoryItem::categoryFromModes("o")),
47 _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
49 // register FormatList if that hasn't happened yet
50 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
51 if (QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
52 qRegisterMetaType<FormatList>("UiStyle::FormatList");
53 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
54 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
57 _uiStylePalette = QVector<QBrush>(NumRoles, QBrush());
59 // Now initialize the mapping between FormatCodes and FormatTypes...
60 _formatCodes["%O"] = Base;
61 _formatCodes["%B"] = Bold;
62 _formatCodes["%S"] = Italic;
63 _formatCodes["%U"] = Underline;
64 _formatCodes["%R"] = Reverse;
66 _formatCodes["%DN"] = Nick;
67 _formatCodes["%DH"] = Hostmask;
68 _formatCodes["%DC"] = ChannelName;
69 _formatCodes["%DM"] = ModeFlags;
70 _formatCodes["%DU"] = Url;
72 // Initialize fallback defaults
73 // NOTE: If you change this, update qtui/chatviewsettings.h, too. More explanations available
75 setUseCustomTimestampFormat(false);
76 setTimestampFormatString(" hh:mm:ss");
77 enableSenderBrackets(true);
79 // BufferView / NickView settings
81 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
82 s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
84 _allowMircColors = s.value("AllowMircColors", true).toBool();
85 s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
93 qDeleteAll(_metricsCache);
97 void UiStyle::reload()
103 void UiStyle::loadStyleSheet()
105 qDeleteAll(_metricsCache);
106 _metricsCache.clear();
107 _formatCache.clear();
113 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
114 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
115 if (s.value("UseCustomStyleSheet", false).toBool()) {
116 QString customSheetPath(s.value("CustomStyleSheetPath").toString());
117 QString customSheet = loadStyleSheet("file:///" + customSheetPath, true);
118 if (customSheet.isEmpty()) {
119 // MIGRATION: changed default install path for data from /usr/share/apps to /usr/share
120 if (customSheetPath.startsWith("/usr/share/apps/quassel")) {
121 customSheetPath.replace(QRegExp("^/usr/share/apps"), "/usr/share");
122 customSheet = loadStyleSheet("file:///" + customSheetPath, true);
123 if (!customSheet.isEmpty()) {
124 s.setValue("CustomStyleSheetPath", customSheetPath);
125 qDebug() << "Custom stylesheet path migrated to" << customSheetPath;
129 styleSheet += customSheet;
131 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
133 if (!styleSheet.isEmpty()) {
135 parser.processStyleSheet(styleSheet);
136 QApplication::setPalette(parser.palette());
138 _uiStylePalette = parser.uiStylePalette();
139 _formats = parser.formats();
140 _listItemFormats = parser.listItemFormats();
142 styleSheet = styleSheet.trimmed();
143 if (!styleSheet.isEmpty())
144 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
151 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
153 QString ss = styleSheet;
154 if (ss.startsWith("file:///")) {
160 if (file.open(QFile::ReadOnly)) {
161 QTextStream stream(&file);
162 ss = stream.readAll();
167 qWarning() << "Could not open stylesheet file:" << file.fileName();
175 void UiStyle::updateSystemTimestampFormat()
177 // Does the system locale use AM/PM designators? For example:
181 // 24-hour: hh:mm ADD things
182 // For timestamp format, see https://doc.qt.io/qt-5/qdatetime.html#toString
183 // This won't update if the system locale is changed while Quassel is running. If need be,
184 // Quassel could hook into notifications of changing system locale to update this.
186 // Match any AP or A designation if on a word boundary, including underscores.
187 // .*(\b|_)(A|AP)(\b|_).*
188 // .* Match any number of characters
189 // \b Match a word boundary, i.e. "AAA.BBB", "." is matched
190 // _ Match the literal character '_' (not considered a word boundary)
191 // (X|Y) Match either X or Y, exactly
193 // Note that '\' must be escaped as '\\'
194 // QRegExp does not support (?> ...), so it's replaced with standard matching, (...)
195 // Helpful interactive website for debugging and explaining: https://regex101.com/
196 const QRegExp regExpMatchAMPM(".*(\\b|_)(A|AP)(\\b|_).*", Qt::CaseInsensitive);
198 if (regExpMatchAMPM.exactMatch(QLocale::system().timeFormat(QLocale::ShortFormat))) {
200 _systemTimestampFormatString = " h:mm:ss ap";
202 // 24-hour style used
203 _systemTimestampFormatString = " hh:mm:ss";
205 // Include a space to give the timestamp a small bit of padding between the border of the chat
206 // buffer window and the numbers. Helps with readability.
207 // If you change this to include brackets, e.g. "[hh:mm:ss]", also update
208 // ChatScene::updateTimestampHasBrackets() to true or false as needed!
212 // FIXME The following should trigger a reload/refresh of the chat view.
213 void UiStyle::setUseCustomTimestampFormat(bool enabled)
215 if (_useCustomTimestampFormat != enabled) {
216 _useCustomTimestampFormat = enabled;
220 void UiStyle::setTimestampFormatString(const QString &format)
222 if (_timestampFormatString != format) {
223 _timestampFormatString = format;
227 void UiStyle::enableSenderBrackets(bool enabled)
229 if (_showSenderBrackets != enabled) {
230 _showSenderBrackets = enabled;
235 void UiStyle::allowMircColorsChanged(const QVariant &v)
237 _allowMircColors = v.toBool();
242 /******** ItemView Styling *******/
244 void UiStyle::showItemViewIconsChanged(const QVariant &v)
246 _showBufferViewIcons = _showNickViewIcons = v.toBool();
250 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
252 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
253 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
255 if (role == Qt::DecorationRole) {
256 if (!_showBufferViewIcons)
260 case BufferInfo::ChannelBuffer:
262 return _channelJoinedIcon;
264 return _channelPartedIcon;
265 case BufferInfo::QueryBuffer:
267 return _userOfflineIcon;
268 if (index.data(NetworkModel::UserAwayRole).toBool())
269 return _userAwayIcon;
271 return _userOnlineIcon;
277 quint32 fmtType = BufferViewItem;
279 case BufferInfo::StatusBuffer:
280 fmtType |= NetworkItem;
282 case BufferInfo::ChannelBuffer:
283 fmtType |= ChannelBufferItem;
285 case BufferInfo::QueryBuffer:
286 fmtType |= QueryBufferItem;
292 QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
293 fmt.merge(_listItemFormats.value(fmtType));
295 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
296 if (activity & BufferInfo::Highlight) {
297 fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
298 fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
300 else if (activity & BufferInfo::NewMessage) {
301 fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
302 fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
304 else if (activity & BufferInfo::OtherActivity) {
305 fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
306 fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
308 else if (!isActive) {
309 fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
310 fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
312 else if (index.data(NetworkModel::UserAwayRole).toBool()) {
313 fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
314 fmt.merge(_listItemFormats.value(fmtType | UserAway));
317 return itemData(role, fmt);
321 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
323 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
325 if (role == Qt::DecorationRole) {
326 if (!_showNickViewIcons)
330 case NetworkModel::UserCategoryItemType:
332 int categoryId = index.data(TreeModel::SortRole).toInt();
333 if (categoryId <= _opIconLimit)
334 return _categoryOpIcon;
335 if (categoryId <= _voiceIconLimit)
336 return _categoryVoiceIcon;
337 return _userOnlineIcon;
339 case NetworkModel::IrcUserItemType:
340 if (index.data(NetworkModel::ItemActiveRole).toBool())
341 return _userOnlineIcon;
343 return _userAwayIcon;
349 QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
352 case NetworkModel::IrcUserItemType:
353 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
354 if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
355 fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
356 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
359 case NetworkModel::UserCategoryItemType:
360 fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
366 return itemData(role, fmt);
370 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
374 return format.font();
375 case Qt::ForegroundRole:
376 return format.property(QTextFormat::ForegroundBrush);
377 case Qt::BackgroundRole:
378 return format.property(QTextFormat::BackgroundBrush);
385 /******** Caching *******/
387 QTextCharFormat UiStyle::format(quint64 key) const
389 return _formats.value(key, QTextCharFormat());
393 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const
395 return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
399 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) const
401 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
405 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const
407 // QFontMetricsF is not assignable, so we need to store pointers :/
408 quint64 key = ftype | ((quint64)label << 32);
410 if (_metricsCache.contains(key))
411 return _metricsCache.value(key);
413 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
417 /******** Generate formats ********/
419 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
420 // until you _really_ know what you do!
421 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const
423 if (ftype == Invalid)
424 return QTextCharFormat();
426 quint64 label = (quint64)label_ << 32;
428 // check if we have exactly this format readily cached already
429 QTextCharFormat fmt = cachedFormat(ftype, label_);
430 if (fmt.properties().count())
433 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
435 for (quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<= 1) {
437 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
440 setCachedFormat(fmt, ftype, label_);
445 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
447 mergeSubElementFormat(fmt, ftype & 0x00ff, label);
449 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
450 // or "foreground 01 and background 03"
451 if ((ftype & 0xfff00)) { // element format
452 for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
454 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
459 // Now we handle color codes
460 // We assume that those can't be combined with subelement and message types.
461 if (_allowMircColors) {
462 if (ftype & 0x00400000)
463 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
464 if (ftype & 0x00800000)
465 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
466 if ((ftype & 0x00c00000) == 0x00c00000)
467 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
472 mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
476 // Merge a subelement format into an existing message format
477 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
479 quint64 key = ftype | label;
480 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
481 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
482 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
483 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
487 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
492 case Message::Notice:
494 case Message::Action:
510 case Message::Server:
516 case Message::DayChange:
520 case Message::NetsplitJoin:
521 return NetsplitJoinMsg;
522 case Message::NetsplitQuit:
523 return NetsplitQuitMsg;
524 case Message::Invite:
527 //Q_ASSERT(false); // we need to handle all message types
528 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
533 UiStyle::FormatType UiStyle::formatType(const QString &code)
535 if (_formatCodes.contains(code)) return _formatCodes.value(code);
540 QString UiStyle::formatCode(FormatType ftype)
542 return _formatCodes.key(ftype);
546 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const
548 QList<QTextLayout::FormatRange> formatRanges;
549 QTextLayout::FormatRange range;
551 for (i = 0; i < formatList.count(); i++) {
552 range.format = format(formatList.at(i).second, messageLabel);
553 range.start = formatList.at(i).first;
554 if (i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
555 formatRanges.append(range);
557 if (i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
562 // This method expects a well-formatted string, there is no error checking!
563 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
564 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat)
568 result.formatList.append(qMakePair((quint16)0, baseFormat));
570 if (s.length() > 65535) {
571 // We use quint16 for indexes
572 qWarning() << QString("String too long to be styled: %1").arg(s);
573 result.plainText = s;
577 quint32 curfmt = baseFormat;
578 int pos = 0; quint16 length = 0;
580 pos = s.indexOf('%', pos);
582 if (s[pos+1] == '%') { // escaped %, we just remove one and continue
587 if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
588 if (s[pos+3] == '-') { // color off
589 curfmt &= 0x003fffff;
593 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
594 //TODO: use 99 as transparent color (re mirc color "standard")
596 if (s[pos+3] == 'f') {
597 curfmt &= 0xf0ffffff;
598 curfmt |= (quint32)(color << 24) | 0x00400000;
601 curfmt &= 0x0fffffff;
602 curfmt |= (quint32)(color << 28) | 0x00800000;
607 else if (s[pos+1] == 'O') { // reset formatting
608 curfmt &= 0x000000ff; // we keep message type-specific formatting
611 else if (s[pos+1] == 'R') { // reverse
612 // TODO: implement reverse formatting
616 else { // all others are toggles
617 QString code = QString("%") + s[pos+1];
618 if (s[pos+1] == 'D') code += s[pos+2];
619 FormatType ftype = formatType(code);
620 if (ftype == Invalid) {
622 qWarning() << (QString("Invalid format code in string: %1").arg(s));
626 length = code.length();
628 s.remove(pos, length);
629 if (pos == result.formatList.last().first)
630 result.formatList.last().second = curfmt;
632 result.formatList.append(qMakePair((quint16)pos, curfmt));
634 result.plainText = s;
639 QString UiStyle::mircToInternal(const QString &mirc_)
642 mirc.reserve(mirc_.size());
643 foreach (const QChar &c, mirc_) {
644 if ((c < '\x20' || c == '\x7f') && c != '\x03') {
645 switch (c.unicode()) {
666 mirc += QChar(0x2421);
669 mirc += QChar(0x2400 + c.unicode());
678 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
679 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
680 // %Dc- turns color off.
681 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
682 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
685 pos = mirc.indexOf('\x03', pos);
686 if (pos < 0) break; // no more mirc color codes
688 int l = mirc.length();
690 // check for fg color
691 if (i < l && mirc[i].isDigit()) {
693 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
694 else num.prepend('0');
695 ins = QString("%Dcf%1").arg(num);
697 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
700 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
701 else num.prepend('0');
702 ins += QString("%Dcb%1").arg(num);
708 mirc.replace(pos, i-pos, ins);
714 QString UiStyle::systemTimestampFormatString()
716 if (_systemTimestampFormatString.isEmpty()) {
717 // Calculate and cache the system timestamp format string
718 updateSystemTimestampFormat();
720 return _systemTimestampFormatString;
724 QString UiStyle::timestampFormatString()
726 if (useCustomTimestampFormat()) {
727 return _timestampFormatString;
729 return systemTimestampFormatString();
734 /***********************************************************************************/
735 UiStyle::StyledMessage::StyledMessage(const Message &msg)
739 // Don't compute the sender hash for message types without a nickname embedded
740 case Message::Server:
743 case Message::DayChange:
745 case Message::Invite:
746 // Don't compute the sender hash for messages with multiple nicks
747 // Fixing this without breaking themes would be.. complex.
748 case Message::NetsplitJoin:
749 case Message::NetsplitQuit:
751 // Don't compute the sender hash for message types that are not yet completed elsewhere
756 // Compute the sender hash for all other message types
763 void UiStyle::StyledMessage::style() const
765 QString user = userFromMask(sender());
766 QString host = hostFromMask(sender());
767 QString nick = nickFromMask(sender());
768 QString txt = UiStyle::mircToInternal(contents());
769 QString bufferName = bufferInfo().bufferName();
770 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
771 host.replace('%', "%%"); // hostnames too...
772 user.replace('%', "%%"); // and the username...
773 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
774 const int maxNetsplitNicks = 15;
779 t = QString("%1").arg(txt); break;
780 case Message::Notice:
781 t = QString("%1").arg(txt); break;
782 case Message::Action:
783 t = QString("%DN%1%DN %2").arg(nick).arg(txt);
787 if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
788 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
792 if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
793 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
797 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
800 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
801 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
805 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
806 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
810 QString victim = txt.section(" ", 0, 0);
811 QString kickmsg = txt.section(" ", 1);
813 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
814 if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
817 //case Message::Kill: FIXME
819 case Message::Server:
820 t = QString("%1").arg(txt); break;
822 t = QString("%1").arg(txt); break;
824 t = QString("%1").arg(txt); break;
825 case Message::DayChange:
827 //: Day Change Message
828 t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
832 t = QString("%1").arg(txt); break;
833 case Message::NetsplitJoin:
835 QStringList users = txt.split("#:#");
836 QStringList servers = users.takeLast().split(" ");
838 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
839 users[i] = nickFromMask(users.at(i));
841 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
842 if (users.count() <= maxNetsplitNicks)
843 t.append(QString("%DN%1%DN").arg(users.join(", ")));
845 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
848 case Message::NetsplitQuit:
850 QStringList users = txt.split("#:#");
851 QStringList servers = users.takeLast().split(" ");
853 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
854 users[i] = nickFromMask(users.at(i));
856 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
858 if (users.count() <= maxNetsplitNicks)
859 t.append(QString("%DN%1%DN").arg(users.join(", ")));
861 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
864 case Message::Invite:
865 t = QString("%1").arg(txt); break;
867 t = QString("[%1]").arg(txt);
869 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
873 const QString &UiStyle::StyledMessage::plainContents() const
875 if (_contents.plainText.isNull())
878 return _contents.plainText;
882 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
884 if (_contents.plainText.isNull())
887 return _contents.formatList;
891 QString UiStyle::StyledMessage::decoratedTimestamp() const
893 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
897 QString UiStyle::StyledMessage::plainSender() const
901 case Message::Notice:
902 return nickFromMask(sender());
909 QString UiStyle::StyledMessage::decoratedSender() const
913 if (_showSenderBrackets)
914 return QString("<%1>").arg(plainSender());
916 return QString("%1").arg(plainSender());
918 case Message::Notice:
919 return QString("[%1]").arg(plainSender()); break;
920 case Message::Action:
936 case Message::Server:
942 case Message::DayChange:
946 case Message::NetsplitJoin:
948 case Message::NetsplitQuit:
950 case Message::Invite:
953 return QString("%1").arg(plainSender());
958 // FIXME hardcoded to 16 sender hashes
959 quint8 UiStyle::StyledMessage::senderHash() const
961 if (_senderHash != 0xff)
966 // HACK: Until multiple nicknames with different colors can be solved in the theming engine,
967 // for /nick change notifications, use the color of the new nickname (if possible), not the old
969 if (type() == Message::Nick) {
970 // New nickname is given as contents. Change to that.
971 nick = stripFormatCodes(contents()).toLower();
973 // Just use the sender directly
974 nick = nickFromMask(sender()).toLower();
977 if (!nick.isEmpty()) {
979 while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
981 if (chopCount < nick.size())
982 nick.chop(chopCount);
984 quint16 hash = qChecksum(nick.toLatin1().data(), nick.toLatin1().size());
985 return (_senderHash = (hash & 0xf) + 1);
989 /***********************************************************************************/
991 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
993 out << formatList.count();
994 UiStyle::FormatList::const_iterator it = formatList.begin();
995 while (it != formatList.end()) {
996 out << (*it).first << (*it).second;
1003 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
1007 for (quint16 i = 0; i < cnt; i++) {
1008 quint16 pos; quint32 ftype;
1010 formatList.append(qMakePair((quint16)pos, ftype));