1 /***************************************************************************
2 * Copyright (C) 2005-08 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
20 #include <QApplication>
24 #include "uisettings.h"
27 // FIXME remove with migration code
30 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
31 // register FormatList if that hasn't happened yet
32 // FIXME I don't think this actually avoids double registration... then again... does it hurt?
33 if(QVariant::nameToType("UiStyle::FormatList") == QVariant::Invalid) {
34 qRegisterMetaType<FormatList>("UiStyle::FormatList");
35 qRegisterMetaTypeStreamOperators<FormatList>("UiStyle::FormatList");
36 Q_ASSERT(QVariant::nameToType("UiStyle::FormatList") != QVariant::Invalid);
39 // FIXME remove migration at some point
40 // We remove old settings if we find them, since they conflict
42 QSettings mys(QCoreApplication::organizationDomain(), Quassel::buildInfo().clientApplicationName);
44 QSettings mys(QCoreApplication::organizationName(), Quassel::buildInfo().clientApplicationName);
46 mys.beginGroup("QtUi");
47 if(mys.childGroups().contains("Colors")) {
48 qDebug() << "Removing obsolete UiStyle settings!";
51 mys.remove("QtUiStyle");
52 mys.remove("QtUiStyleNew");
53 mys.remove("QtUi/Colors");
57 _defaultFont = QFont("Monospace", QApplication::font().pointSize());
60 _defaultPlainFormat.setForeground(QBrush("#000000"));
61 _defaultPlainFormat.setFont(_defaultFont);
62 _defaultPlainFormat.font().setFixedPitch(true);
63 _defaultPlainFormat.font().setStyleHint(QFont::TypeWriter);
64 setFormat(None, _defaultPlainFormat, Settings::Default);
66 // Load saved custom formats
67 UiStyleSettings s(_settingsKey);
68 foreach(FormatType type, s.availableFormats()) {
69 _customFormats[type] = s.customFormat(type);
72 // Now initialize the mapping between FormatCodes and FormatTypes...
73 _formatCodes["%O"] = None;
74 _formatCodes["%B"] = Bold;
75 _formatCodes["%S"] = Italic;
76 _formatCodes["%U"] = Underline;
77 _formatCodes["%R"] = Reverse;
79 _formatCodes["%D0"] = PlainMsg;
80 _formatCodes["%Dn"] = NoticeMsg;
81 _formatCodes["%Ds"] = ServerMsg;
82 _formatCodes["%De"] = ErrorMsg;
83 _formatCodes["%Dj"] = JoinMsg;
84 _formatCodes["%Dp"] = PartMsg;
85 _formatCodes["%Dq"] = QuitMsg;
86 _formatCodes["%Dk"] = KickMsg;
87 _formatCodes["%Dr"] = RenameMsg;
88 _formatCodes["%Dm"] = ModeMsg;
89 _formatCodes["%Da"] = ActionMsg;
91 _formatCodes["%DT"] = Timestamp;
92 _formatCodes["%DS"] = Sender;
93 _formatCodes["%DN"] = Nick;
94 _formatCodes["%DH"] = Hostmask;
95 _formatCodes["%DC"] = ChannelName;
96 _formatCodes["%DM"] = ModeFlags;
97 _formatCodes["%DU"] = Url;
99 // Initialize color codes according to mIRC "standard"
101 //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
102 //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
103 colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
104 colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
107 for(int i = 0; i < 16; i++) {
108 QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
109 _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 | i<<24);
110 _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 | i<<28);
111 QTextCharFormat fgf, bgf;
112 fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 | i<<24), fgf, Settings::Default);
113 bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 | i<<28), bgf, Settings::Default);
116 // Set a few more standard formats
117 QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
118 setFormat(Bold, bold, Settings::Default);
120 QTextCharFormat italic; italic.setFontItalic(true);
121 setFormat(Italic, italic, Settings::Default);
123 QTextCharFormat underline; underline.setFontUnderline(true);
124 setFormat(Underline, underline, Settings::Default);
126 // All other formats should be defined in derived classes.
129 UiStyle::~ UiStyle() {
130 qDeleteAll(_cachedFontMetrics);
133 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
134 if(mode == Settings::Default) {
135 _defaultFormats[ftype] = fmt;
137 UiStyleSettings s(_settingsKey);
138 if(fmt != _defaultFormats[ftype]) {
139 _customFormats[ftype] = fmt;
140 s.setCustomFormat(ftype, fmt);
142 _customFormats.remove(ftype);
143 s.removeCustomFormat(ftype);
146 // TODO: invalidate only affected cached formats... if that's possible with less overhead than just rebuilding them
147 _cachedFormats.clear();
148 _cachedFontMetrics.clear();
151 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
152 if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
153 else return _defaultFormats.value(ftype, QTextCharFormat());
156 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
157 // until you _really_ know what you do!
158 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
159 if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
160 if(ftype == Invalid) return QTextCharFormat();
161 // Now we construct the merged format, starting with the default
162 QTextCharFormat fmt = format(None);
163 // First: general message format
164 fmt.merge(format((FormatType)(ftype & 0x0f)));
165 // now more specific ones
166 for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
167 if(ftype & mask) fmt.merge(format((FormatType)mask));
170 if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
171 if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
173 if(ftype & Url) fmt.merge(format(Url));
174 return _cachedFormats[ftype] = fmt;
177 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
178 // QFontMetricsF is not assignable, so we need to store pointers :/
179 if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
180 return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
183 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
184 if(_formatCodes.contains(code)) return _formatCodes.value(code);
188 QString UiStyle::formatCode(FormatType ftype) const {
189 return _formatCodes.key(ftype);
192 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
193 QList<QTextLayout::FormatRange> formatRanges;
194 QTextLayout::FormatRange range;
196 for(i = 0; i < formatList.count(); i++) {
197 range.format = mergedFormat(formatList.at(i).second);
198 range.start = formatList.at(i).first;
199 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
200 formatRanges.append(range);
202 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
206 // This method expects a well-formatted string, there is no error checking!
207 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
208 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
210 if(s.length() > 65535) {
211 qWarning() << QString("String too long to be styled: %1").arg(s);
212 return StyledString();
215 result.formatList.append(qMakePair((quint16)0, (quint32)None));
216 quint32 curfmt = (quint32)None;
217 int pos = 0; quint16 length = 0;
219 pos = s.indexOf('%', pos);
221 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
226 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
227 if(s[pos+3] == '-') { // color off
228 curfmt &= 0x003fffff;
231 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
232 //TODO: use 99 as transparent color (re mirc color "standard")
234 if(s[pos+3] == 'f') {
235 curfmt &= 0xf0ffffff;
236 curfmt |= (color << 24) | 0x00400000;
238 curfmt &= 0x0fffffff;
239 curfmt |= (color << 28) | 0x00800000;
243 } else if(s[pos+1] == 'O') { // reset formatting
244 curfmt &= 0x0000000f; // we keep message type-specific formatting
246 } else if(s[pos+1] == 'R') { // reverse
247 // TODO: implement reverse formatting
250 } else { // all others are toggles
251 QString code = QString("%") + s[pos+1];
252 if(s[pos+1] == 'D') code += s[pos+2];
253 FormatType ftype = formatType(code);
254 if(ftype == Invalid) {
255 qWarning(qPrintable(QString("Invalid format code in string: %1").arg(s)));
259 length = code.length();
261 s.remove(pos, length);
262 if(pos == result.formatList.last().first)
263 result.formatList.last().second = curfmt;
265 result.formatList.append(qMakePair((quint16)pos, curfmt));
267 result.plainText = s;
271 QString UiStyle::mircToInternal(const QString &mirc_) const {
272 QString mirc = mirc_;
273 mirc.replace('%', "%%"); // escape % just to be sure
274 mirc.replace('\x02', "%B");
275 mirc.replace('\x0f', "%O");
276 mirc.replace('\x12', "%R");
277 mirc.replace('\x16', "%R");
278 mirc.replace('\x1d', "%S");
279 mirc.replace('\x1f', "%U");
281 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
282 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
283 // %Dc- turns color off.
284 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
285 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
288 pos = mirc.indexOf('\x03', pos);
289 if(pos < 0) break; // no more mirc color codes
291 int l = mirc.length();
293 // check for fg color
294 if(i < l && mirc[i].isDigit()) {
296 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
297 else num.prepend('0');
298 ins = QString("%Dcf%1").arg(num);
300 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
303 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
304 else num.prepend('0');
305 ins += QString("%Dcb%1").arg(num);
310 mirc.replace(pos, i-pos, ins);
315 UiStyle::StyledMessage UiStyle::styleMessage(const Message &msg) {
316 return StyledMessage(msg, this);
319 /***********************************************************************************/
321 UiStyle::StyledMessage::StyledMessage(const Message &msg, UiStyle *style) {
322 QString user = userFromMask(msg.sender());
323 QString host = hostFromMask(msg.sender());
324 QString nick = nickFromMask(msg.sender());
325 QString txt = style->mircToInternal(msg.contents());
326 QString bufferName = msg.bufferInfo().bufferName();
327 bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
329 _msgType = msg.type();
330 _timestamp = msg.timestamp();
336 t = tr("%D0%1").arg(txt); break;
337 case Message::Notice:
339 t = tr("%Dn%1").arg(txt); break;
340 case Message::Server:
341 t = tr("%Ds%1").arg(txt); break;
343 t = tr("%De%1").arg(txt); break;
345 t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
347 t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
348 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
351 t = tr("%Dq%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
352 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
354 case Message::Kick: {
355 QString victim = txt.section(" ", 0, 0);
356 //if(victim == ui.ownNick->currentText()) victim = tr("you");
357 QString kickmsg = txt.section(" ", 1);
358 t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
359 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
363 if(nick == msg.contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
364 else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
367 if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
368 else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
370 case Message::Action:
371 t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
374 _sender = msg.sender();
375 t = tr("%De[%1]").arg(txt);
377 _contents = style->styleString(t);
380 QDateTime UiStyle::StyledMessage::timestamp() const {
384 QString UiStyle::StyledMessage::decoratedTimestamp() const {
385 return QString("[%1]").arg(_timestamp.toLocalTime().toString("hh:mm:ss"));
388 QString UiStyle::StyledMessage::sender() const {
391 case Message::Notice:
398 QString UiStyle::StyledMessage::decoratedSender() const {
401 return tr("<%1>").arg(_sender); break;
402 case Message::Notice:
403 return tr("[%1]").arg(_sender); break;
404 case Message::Server:
405 return tr("*"); break;
407 return tr("*"); break;
409 return tr("-->"); break;
411 return tr("<--"); break;
413 return tr("<--"); break;
415 return tr("<-*"); break;
417 return tr("<->"); break;
419 return tr("***"); break;
420 case Message::Action:
421 return tr("-*-"); break;
423 return tr("%1").arg(_sender);
427 QString UiStyle::StyledMessage::contents() const {
428 return _contents.plainText;
431 UiStyle::FormatType UiStyle::StyledMessage::timestampFormat() const {
432 return UiStyle::Timestamp;
435 UiStyle::FormatType UiStyle::StyledMessage::senderFormat() const {
438 return UiStyle::Sender; break;
439 case Message::Notice:
440 return UiStyle::NoticeMsg; break;
441 case Message::Server:
442 return UiStyle::ServerMsg; break;
444 return UiStyle::ErrorMsg; break;
446 return UiStyle::JoinMsg; break;
448 return UiStyle::PartMsg; break;
450 return UiStyle::QuitMsg; break;
452 return UiStyle::KickMsg; break;
454 return UiStyle::RenameMsg; break;
456 return UiStyle::ModeMsg; break;
457 case Message::Action:
458 return UiStyle::ActionMsg; break;
460 return UiStyle::ErrorMsg;
464 UiStyle::FormatList UiStyle::StyledMessage::contentsFormatList() const {
465 return _contents.formatList;
468 /***********************************************************************************/
470 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
471 out << formatList.count();
472 UiStyle::FormatList::const_iterator it = formatList.begin();
473 while(it != formatList.end()) {
474 out << (*it).first << (*it).second;
480 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
483 for(quint16 i = 0; i < cnt; i++) {
484 quint16 pos; quint32 ftype;
486 formatList.append(qMakePair((quint16)pos, ftype));