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::_showSenderPrefixes; /// If true, show prefixmodes before sender names
36 bool UiStyle::_showSenderBrackets; /// If true, show brackets around sender names
38 UiStyle::UiStyle(QObject *parent)
40 _channelJoinedIcon(QIcon::fromTheme("irc-channel-joined", QIcon(":/icons/irc-channel-joined.png"))),
41 _channelPartedIcon(QIcon::fromTheme("irc-channel-parted", QIcon(":/icons/irc-channel-parted.png"))),
42 _userOfflineIcon(QIcon::fromTheme("im-user-offline", QIcon::fromTheme("user-offline", QIcon(":/icons/im-user-offline.png")))),
43 _userOnlineIcon(QIcon::fromTheme("im-user", QIcon::fromTheme("user-available", QIcon(":/icons/im-user.png")))), // im-user-* are non-standard oxygen extensions
44 _userAwayIcon(QIcon::fromTheme("im-user-away", QIcon::fromTheme("user-away", QIcon(":/icons/im-user-away.png")))),
45 _categoryOpIcon(QIcon::fromTheme("irc-operator")),
46 _categoryVoiceIcon(QIcon::fromTheme("irc-voice")),
47 _opIconLimit(UserCategoryItem::categoryFromModes("o")),
48 _voiceIconLimit(UserCategoryItem::categoryFromModes("v"))
50 // register FormatList if that hasn't happened yet
51 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
52 if (QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
53 qRegisterMetaType<FormatList>("UiStyle::FormatList");
54 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
55 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
58 _uiStylePalette = QVector<QBrush>(NumRoles, QBrush());
60 // Now initialize the mapping between FormatCodes and FormatTypes...
61 _formatCodes["%O"] = Base;
62 _formatCodes["%B"] = Bold;
63 _formatCodes["%S"] = Italic;
64 _formatCodes["%U"] = Underline;
65 _formatCodes["%R"] = Reverse;
67 _formatCodes["%DN"] = Nick;
68 _formatCodes["%DH"] = Hostmask;
69 _formatCodes["%DC"] = ChannelName;
70 _formatCodes["%DM"] = ModeFlags;
71 _formatCodes["%DU"] = Url;
73 // Initialize fallback defaults
74 // NOTE: If you change this, update qtui/chatviewsettings.h, too. More explanations available
76 setUseCustomTimestampFormat(false);
77 setTimestampFormatString(" hh:mm:ss");
78 enableSenderPrefixes(false);
79 enableSenderBrackets(true);
81 // BufferView / NickView settings
83 _showBufferViewIcons = _showNickViewIcons = s.value("ShowItemViewIcons", true).toBool();
84 s.notify("ShowItemViewIcons", this, SLOT(showItemViewIconsChanged(QVariant)));
86 _allowMircColors = s.value("AllowMircColors", true).toBool();
87 s.notify("AllowMircColors", this, SLOT(allowMircColorsChanged(QVariant)));
95 qDeleteAll(_metricsCache);
99 void UiStyle::reload()
105 void UiStyle::loadStyleSheet()
107 qDeleteAll(_metricsCache);
108 _metricsCache.clear();
109 _formatCache.clear();
115 styleSheet += loadStyleSheet("file:///" + Quassel::findDataFilePath("stylesheets/default.qss"));
116 styleSheet += loadStyleSheet("file:///" + Quassel::configDirPath() + "settings.qss");
117 if (s.value("UseCustomStyleSheet", false).toBool()) {
118 QString customSheetPath(s.value("CustomStyleSheetPath").toString());
119 QString customSheet = loadStyleSheet("file:///" + customSheetPath, true);
120 if (customSheet.isEmpty()) {
121 // MIGRATION: changed default install path for data from /usr/share/apps to /usr/share
122 if (customSheetPath.startsWith("/usr/share/apps/quassel")) {
123 customSheetPath.replace(QRegExp("^/usr/share/apps"), "/usr/share");
124 customSheet = loadStyleSheet("file:///" + customSheetPath, true);
125 if (!customSheet.isEmpty()) {
126 s.setValue("CustomStyleSheetPath", customSheetPath);
127 qDebug() << "Custom stylesheet path migrated to" << customSheetPath;
131 styleSheet += customSheet;
133 styleSheet += loadStyleSheet("file:///" + Quassel::optionValue("qss"), true);
135 if (!styleSheet.isEmpty()) {
137 parser.processStyleSheet(styleSheet);
138 QApplication::setPalette(parser.palette());
140 _uiStylePalette = parser.uiStylePalette();
141 _formats = parser.formats();
142 _listItemFormats = parser.listItemFormats();
144 styleSheet = styleSheet.trimmed();
145 if (!styleSheet.isEmpty())
146 qApp->setStyleSheet(styleSheet); // pass the remaining sections to the application
153 QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
155 QString ss = styleSheet;
156 if (ss.startsWith("file:///")) {
162 if (file.open(QFile::ReadOnly)) {
163 QTextStream stream(&file);
164 ss = stream.readAll();
169 qWarning() << "Could not open stylesheet file:" << file.fileName();
177 void UiStyle::updateSystemTimestampFormat()
179 // Does the system locale use AM/PM designators? For example:
183 // 24-hour: hh:mm ADD things
184 // For timestamp format, see https://doc.qt.io/qt-5/qdatetime.html#toString
185 // This won't update if the system locale is changed while Quassel is running. If need be,
186 // Quassel could hook into notifications of changing system locale to update this.
188 // Match any AP or A designation if on a word boundary, including underscores.
189 // .*(\b|_)(A|AP)(\b|_).*
190 // .* Match any number of characters
191 // \b Match a word boundary, i.e. "AAA.BBB", "." is matched
192 // _ Match the literal character '_' (not considered a word boundary)
193 // (X|Y) Match either X or Y, exactly
195 // Note that '\' must be escaped as '\\'
196 // QRegExp does not support (?> ...), so it's replaced with standard matching, (...)
197 // Helpful interactive website for debugging and explaining: https://regex101.com/
198 const QRegExp regExpMatchAMPM(".*(\\b|_)(A|AP)(\\b|_).*", Qt::CaseInsensitive);
200 if (regExpMatchAMPM.exactMatch(QLocale::system().timeFormat(QLocale::ShortFormat))) {
202 _systemTimestampFormatString = " h:mm:ss ap";
204 // 24-hour style used
205 _systemTimestampFormatString = " hh:mm:ss";
207 // Include a space to give the timestamp a small bit of padding between the border of the chat
208 // buffer window and the numbers. Helps with readability.
209 // If you change this to include brackets, e.g. "[hh:mm:ss]", also update
210 // ChatScene::updateTimestampHasBrackets() to true or false as needed!
214 // FIXME The following should trigger a reload/refresh of the chat view.
215 void UiStyle::setUseCustomTimestampFormat(bool enabled)
217 if (_useCustomTimestampFormat != enabled) {
218 _useCustomTimestampFormat = enabled;
222 void UiStyle::setTimestampFormatString(const QString &format)
224 if (_timestampFormatString != format) {
225 _timestampFormatString = format;
229 void UiStyle::enableSenderPrefixes(bool enabled)
231 if (_showSenderPrefixes != enabled) {
232 _showSenderPrefixes = enabled;
236 void UiStyle::enableSenderBrackets(bool enabled)
238 if (_showSenderBrackets != enabled) {
239 _showSenderBrackets = enabled;
244 void UiStyle::allowMircColorsChanged(const QVariant &v)
246 _allowMircColors = v.toBool();
251 /******** ItemView Styling *******/
253 void UiStyle::showItemViewIconsChanged(const QVariant &v)
255 _showBufferViewIcons = _showNickViewIcons = v.toBool();
259 QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
261 BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
262 bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
264 if (role == Qt::DecorationRole) {
265 if (!_showBufferViewIcons)
269 case BufferInfo::ChannelBuffer:
271 return _channelJoinedIcon;
273 return _channelPartedIcon;
274 case BufferInfo::QueryBuffer:
276 return _userOfflineIcon;
277 if (index.data(NetworkModel::UserAwayRole).toBool())
278 return _userAwayIcon;
280 return _userOnlineIcon;
286 quint32 fmtType = BufferViewItem;
288 case BufferInfo::StatusBuffer:
289 fmtType |= NetworkItem;
291 case BufferInfo::ChannelBuffer:
292 fmtType |= ChannelBufferItem;
294 case BufferInfo::QueryBuffer:
295 fmtType |= QueryBufferItem;
301 QTextCharFormat fmt = _listItemFormats.value(BufferViewItem);
302 fmt.merge(_listItemFormats.value(fmtType));
304 BufferInfo::ActivityLevel activity = (BufferInfo::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
305 if (activity & BufferInfo::Highlight) {
306 fmt.merge(_listItemFormats.value(BufferViewItem | HighlightedBuffer));
307 fmt.merge(_listItemFormats.value(fmtType | HighlightedBuffer));
309 else if (activity & BufferInfo::NewMessage) {
310 fmt.merge(_listItemFormats.value(BufferViewItem | UnreadBuffer));
311 fmt.merge(_listItemFormats.value(fmtType | UnreadBuffer));
313 else if (activity & BufferInfo::OtherActivity) {
314 fmt.merge(_listItemFormats.value(BufferViewItem | ActiveBuffer));
315 fmt.merge(_listItemFormats.value(fmtType | ActiveBuffer));
317 else if (!isActive) {
318 fmt.merge(_listItemFormats.value(BufferViewItem | InactiveBuffer));
319 fmt.merge(_listItemFormats.value(fmtType | InactiveBuffer));
321 else if (index.data(NetworkModel::UserAwayRole).toBool()) {
322 fmt.merge(_listItemFormats.value(BufferViewItem | UserAway));
323 fmt.merge(_listItemFormats.value(fmtType | UserAway));
326 return itemData(role, fmt);
330 QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
332 NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
334 if (role == Qt::DecorationRole) {
335 if (!_showNickViewIcons)
339 case NetworkModel::UserCategoryItemType:
341 int categoryId = index.data(TreeModel::SortRole).toInt();
342 if (categoryId <= _opIconLimit)
343 return _categoryOpIcon;
344 if (categoryId <= _voiceIconLimit)
345 return _categoryVoiceIcon;
346 return _userOnlineIcon;
348 case NetworkModel::IrcUserItemType:
349 if (index.data(NetworkModel::ItemActiveRole).toBool())
350 return _userOnlineIcon;
352 return _userAwayIcon;
358 QTextCharFormat fmt = _listItemFormats.value(NickViewItem);
361 case NetworkModel::IrcUserItemType:
362 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem));
363 if (!index.data(NetworkModel::ItemActiveRole).toBool()) {
364 fmt.merge(_listItemFormats.value(NickViewItem | UserAway));
365 fmt.merge(_listItemFormats.value(NickViewItem | IrcUserItem | UserAway));
368 case NetworkModel::UserCategoryItemType:
369 fmt.merge(_listItemFormats.value(NickViewItem | UserCategoryItem));
375 return itemData(role, fmt);
379 QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
383 return format.font();
384 case Qt::ForegroundRole:
385 return format.property(QTextFormat::ForegroundBrush);
386 case Qt::BackgroundRole:
387 return format.property(QTextFormat::BackgroundBrush);
394 /******** Caching *******/
396 QTextCharFormat UiStyle::format(quint64 key) const
398 return _formats.value(key, QTextCharFormat());
402 QTextCharFormat UiStyle::cachedFormat(quint32 formatType, quint32 messageLabel) const
404 return _formatCache.value(formatType | ((quint64)messageLabel << 32), QTextCharFormat());
408 void UiStyle::setCachedFormat(const QTextCharFormat &format, quint32 formatType, quint32 messageLabel) const
410 _formatCache[formatType | ((quint64)messageLabel << 32)] = format;
414 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype, quint32 label) const
416 // QFontMetricsF is not assignable, so we need to store pointers :/
417 quint64 key = ftype | ((quint64)label << 32);
419 if (_metricsCache.contains(key))
420 return _metricsCache.value(key);
422 return (_metricsCache[key] = new QFontMetricsF(format(ftype, label).font()));
426 /******** Generate formats ********/
428 // NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
429 // until you _really_ know what you do!
430 QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const
432 if (ftype == Invalid)
433 return QTextCharFormat();
435 quint64 label = (quint64)label_ << 32;
437 // check if we have exactly this format readily cached already
438 QTextCharFormat fmt = cachedFormat(ftype, label_);
439 if (fmt.properties().count())
442 mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));
444 for (quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<= 1) {
446 mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
449 setCachedFormat(fmt, ftype, label_);
454 void UiStyle::mergeFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
456 mergeSubElementFormat(fmt, ftype & 0x00ff, label);
458 // TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
459 // or "foreground 01 and background 03"
460 if ((ftype & 0xfff00)) { // element format
461 for (quint32 mask = 0x00100; mask <= 0x40000; mask <<= 1) {
463 mergeSubElementFormat(fmt, ftype & (mask | 0xff), label);
468 // Now we handle color codes
469 // We assume that those can't be combined with subelement and message types.
470 if (_allowMircColors) {
471 if (ftype & 0x00400000)
472 mergeSubElementFormat(fmt, ftype & 0x0f400000, label); // foreground
473 if (ftype & 0x00800000)
474 mergeSubElementFormat(fmt, ftype & 0xf0800000, label); // background
475 if ((ftype & 0x00c00000) == 0x00c00000)
476 mergeSubElementFormat(fmt, ftype & 0xffc00000, label); // combination
481 mergeSubElementFormat(fmt, ftype & (Url | 0x000000ff), label);
485 // Merge a subelement format into an existing message format
486 void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, quint32 ftype, quint64 label) const
488 quint64 key = ftype | label;
489 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffff00))); // label + subelement
490 fmt.merge(format(key & Q_UINT64_C(0x0000ffffffffffff))); // label + subelement + msgtype
491 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffff00))); // label + subelement + nickhash
492 fmt.merge(format(key & Q_UINT64_C(0xffffffffffffffff))); // label + subelement + nickhash + msgtype
496 UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
501 case Message::Notice:
503 case Message::Action:
519 case Message::Server:
525 case Message::DayChange:
529 case Message::NetsplitJoin:
530 return NetsplitJoinMsg;
531 case Message::NetsplitQuit:
532 return NetsplitQuitMsg;
533 case Message::Invite:
536 //Q_ASSERT(false); // we need to handle all message types
537 qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
542 UiStyle::FormatType UiStyle::formatType(const QString &code)
544 if (_formatCodes.contains(code)) return _formatCodes.value(code);
549 QString UiStyle::formatCode(FormatType ftype)
551 return _formatCodes.key(ftype);
555 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, quint32 messageLabel) const
557 QList<QTextLayout::FormatRange> formatRanges;
558 QTextLayout::FormatRange range;
560 for (i = 0; i < formatList.count(); i++) {
561 range.format = format(formatList.at(i).second, messageLabel);
562 range.start = formatList.at(i).first;
563 if (i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
564 formatRanges.append(range);
566 if (i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
571 // This method expects a well-formatted string, there is no error checking!
572 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
573 UiStyle::StyledString UiStyle::styleString(const QString &s_, quint32 baseFormat)
577 result.formatList.append(qMakePair((quint16)0, baseFormat));
579 if (s.length() > 65535) {
580 // We use quint16 for indexes
581 qWarning() << QString("String too long to be styled: %1").arg(s);
582 result.plainText = s;
586 quint32 curfmt = baseFormat;
587 int pos = 0; quint16 length = 0;
589 pos = s.indexOf('%', pos);
591 if (s[pos+1] == '%') { // escaped %, we just remove one and continue
596 if (s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
597 if (s[pos+3] == '-') { // color off
598 curfmt &= 0x003fffff;
602 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
603 //TODO: use 99 as transparent color (re mirc color "standard")
605 if (s[pos+3] == 'f') {
606 curfmt &= 0xf0ffffff;
607 curfmt |= (quint32)(color << 24) | 0x00400000;
610 curfmt &= 0x0fffffff;
611 curfmt |= (quint32)(color << 28) | 0x00800000;
616 else if (s[pos+1] == 'O') { // reset formatting
617 curfmt &= 0x000000ff; // we keep message type-specific formatting
620 else if (s[pos+1] == 'R') { // reverse
621 // TODO: implement reverse formatting
625 else { // all others are toggles
626 QString code = QString("%") + s[pos+1];
627 if (s[pos+1] == 'D') code += s[pos+2];
628 FormatType ftype = formatType(code);
629 if (ftype == Invalid) {
631 qWarning() << (QString("Invalid format code in string: %1").arg(s));
635 length = code.length();
637 s.remove(pos, length);
638 if (pos == result.formatList.last().first)
639 result.formatList.last().second = curfmt;
641 result.formatList.append(qMakePair((quint16)pos, curfmt));
643 result.plainText = s;
648 QString UiStyle::mircToInternal(const QString &mirc_)
651 mirc.reserve(mirc_.size());
652 foreach (const QChar &c, mirc_) {
653 if ((c < '\x20' || c == '\x7f') && c != '\x03') {
654 switch (c.unicode()) {
675 mirc += QChar(0x2421);
678 mirc += QChar(0x2400 + c.unicode());
687 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
688 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
689 // %Dc- turns color off.
690 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
691 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
694 pos = mirc.indexOf('\x03', pos);
695 if (pos < 0) break; // no more mirc color codes
697 int l = mirc.length();
699 // check for fg color
700 if (i < l && mirc[i].isDigit()) {
702 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
703 else num.prepend('0');
704 ins = QString("%Dcf%1").arg(num);
706 if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
709 if (i < l && mirc[i].isDigit()) num.append(mirc[i++]);
710 else num.prepend('0');
711 ins += QString("%Dcb%1").arg(num);
717 mirc.replace(pos, i-pos, ins);
723 QString UiStyle::systemTimestampFormatString()
725 if (_systemTimestampFormatString.isEmpty()) {
726 // Calculate and cache the system timestamp format string
727 updateSystemTimestampFormat();
729 return _systemTimestampFormatString;
733 QString UiStyle::timestampFormatString()
735 if (useCustomTimestampFormat()) {
736 return _timestampFormatString;
738 return systemTimestampFormatString();
743 /***********************************************************************************/
744 UiStyle::StyledMessage::StyledMessage(const Message &msg)
748 // Don't compute the sender hash for message types without a nickname embedded
749 case Message::Server:
752 case Message::DayChange:
754 case Message::Invite:
755 // Don't compute the sender hash for messages with multiple nicks
756 // Fixing this without breaking themes would be.. complex.
757 case Message::NetsplitJoin:
758 case Message::NetsplitQuit:
760 // Don't compute the sender hash for message types that are not yet completed elsewhere
765 // Compute the sender hash for all other message types
772 void UiStyle::StyledMessage::style() const
774 QString user = userFromMask(sender());
775 QString host = hostFromMask(sender());
776 QString nick = nickFromMask(sender());
777 QString txt = UiStyle::mircToInternal(contents());
778 QString bufferName = bufferInfo().bufferName();
779 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
780 host.replace('%', "%%"); // hostnames too...
781 user.replace('%', "%%"); // and the username...
782 nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
783 const int maxNetsplitNicks = 15;
788 t = QString("%1").arg(txt); break;
789 case Message::Notice:
790 t = QString("%1").arg(txt); break;
791 case Message::Action:
792 t = QString("%DN%1%DN %2").arg(nick).arg(txt);
796 if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
797 else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
801 if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
802 else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
806 t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
809 t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
810 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
814 t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
815 if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
819 QString victim = txt.section(" ", 0, 0);
820 QString kickmsg = txt.section(" ", 1);
822 t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
823 if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
826 //case Message::Kill: FIXME
828 case Message::Server:
829 t = QString("%1").arg(txt); break;
831 t = QString("%1").arg(txt); break;
833 t = QString("%1").arg(txt); break;
834 case Message::DayChange:
836 //: Day Change Message
837 t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
841 t = QString("%1").arg(txt); break;
842 case Message::NetsplitJoin:
844 QStringList users = txt.split("#:#");
845 QStringList servers = users.takeLast().split(" ");
847 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
848 users[i] = nickFromMask(users.at(i));
850 t = tr("Netsplit between %DH%1%DH and %DH%2%DH ended. Users joined: ").arg(servers.at(0), servers.at(1));
851 if (users.count() <= maxNetsplitNicks)
852 t.append(QString("%DN%1%DN").arg(users.join(", ")));
854 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
857 case Message::NetsplitQuit:
859 QStringList users = txt.split("#:#");
860 QStringList servers = users.takeLast().split(" ");
862 for (int i = 0; i < users.count() && i < maxNetsplitNicks; i++)
863 users[i] = nickFromMask(users.at(i));
865 t = tr("Netsplit between %DH%1%DH and %DH%2%DH. Users quit: ").arg(servers.at(0), servers.at(1));
867 if (users.count() <= maxNetsplitNicks)
868 t.append(QString("%DN%1%DN").arg(users.join(", ")));
870 t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
873 case Message::Invite:
874 t = QString("%1").arg(txt); break;
876 t = QString("[%1]").arg(txt);
878 _contents = UiStyle::styleString(t, UiStyle::formatType(type()));
882 const QString &UiStyle::StyledMessage::plainContents() const
884 if (_contents.plainText.isNull())
887 return _contents.plainText;
891 const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
893 if (_contents.plainText.isNull())
896 return _contents.formatList;
900 QString UiStyle::StyledMessage::decoratedTimestamp() const
902 return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
906 QString UiStyle::StyledMessage::plainSender() const
910 case Message::Notice:
911 return nickFromMask(sender());
918 QString UiStyle::StyledMessage::decoratedSender() const
920 QString _senderPrefixes;
921 if (_showSenderPrefixes) {
922 _senderPrefixes = senderPrefixes();
927 if (_showSenderBrackets)
928 return QString("<%1%2>").arg(_senderPrefixes, plainSender());
930 return QString("%1%2").arg(_senderPrefixes, plainSender());
932 case Message::Notice:
933 return QString("[%1%2]").arg(_senderPrefixes, plainSender()); break;
934 case Message::Action:
950 case Message::Server:
956 case Message::DayChange:
960 case Message::NetsplitJoin:
962 case Message::NetsplitQuit:
964 case Message::Invite:
967 return QString("%1%2").arg(_senderPrefixes, plainSender());
972 // FIXME hardcoded to 16 sender hashes
973 quint8 UiStyle::StyledMessage::senderHash() const
975 if (_senderHash != 0xff)
980 // HACK: Until multiple nicknames with different colors can be solved in the theming engine,
981 // for /nick change notifications, use the color of the new nickname (if possible), not the old
983 if (type() == Message::Nick) {
984 // New nickname is given as contents. Change to that.
985 nick = stripFormatCodes(contents()).toLower();
987 // Just use the sender directly
988 nick = nickFromMask(sender()).toLower();
991 if (!nick.isEmpty()) {
993 while (chopCount < nick.size() && nick.at(nick.count() - 1 - chopCount) == '_')
995 if (chopCount < nick.size())
996 nick.chop(chopCount);
998 quint16 hash = qChecksum(nick.toLatin1().data(), nick.toLatin1().size());
999 return (_senderHash = (hash & 0xf) + 1);
1003 /***********************************************************************************/
1005 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
1007 out << formatList.count();
1008 UiStyle::FormatList::const_iterator it = formatList.begin();
1009 while (it != formatList.end()) {
1010 out << (*it).first << (*it).second;
1017 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
1021 for (quint16 i = 0; i < cnt; i++) {
1022 quint16 pos; quint32 ftype;
1024 formatList.append(qMakePair((quint16)pos, ftype));