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>
23 #include "uisettings.h"
26 // 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(), Global::clientApplicationName);
44 QSettings mys(QCoreApplication::organizationName(), Global::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();
150 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
151 if(mode == Settings::Custom && _customFormats.contains(ftype)) return _customFormats.value(ftype);
152 else return _defaultFormats.value(ftype, QTextCharFormat());
155 // NOTE: This function is intimately tied to the values in FormatType. Don't change this
156 // until you _really_ know what you do!
157 QTextCharFormat UiStyle::mergedFormat(quint32 ftype) {
158 if(_cachedFormats.contains(ftype)) return _cachedFormats.value(ftype);
159 if(ftype == Invalid) return QTextCharFormat();
160 // Now we construct the merged format, starting with the default
161 QTextCharFormat fmt = format(None);
162 // First: general message format
163 fmt.merge(format((FormatType)(ftype & 0x0f)));
164 // now more specific ones
165 for(quint32 mask = 0x0010; mask <= 0x2000; mask <<= 1) {
166 if(ftype & mask) fmt.merge(format((FormatType)mask));
169 if(ftype & 0x00400000) fmt.merge(format((FormatType)(ftype & 0x0f400000))); // foreground
170 if(ftype & 0x00800000) fmt.merge(format((FormatType)(ftype & 0xf0800000))); // background
172 if(ftype & Url) fmt.merge(format(Url));
173 return _cachedFormats[ftype] = fmt;
176 QFontMetricsF *UiStyle::fontMetrics(quint32 ftype) {
177 // QFontMetricsF is not assignable, so we need to store pointers :/
178 if(_cachedFontMetrics.contains(ftype)) return _cachedFontMetrics.value(ftype);
179 return (_cachedFontMetrics[ftype] = new QFontMetricsF(mergedFormat(ftype).font()));
182 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
183 if(_formatCodes.contains(code)) return _formatCodes.value(code);
187 QString UiStyle::formatCode(FormatType ftype) const {
188 return _formatCodes.key(ftype);
191 QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength) {
192 QList<QTextLayout::FormatRange> formatRanges;
193 QTextLayout::FormatRange range;
195 for(i = 0; i < formatList.count(); i++) {
196 range.format = mergedFormat(formatList.at(i).second);
197 range.start = formatList.at(i).first;
198 if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
199 formatRanges.append(range);
201 if(i > 0) formatRanges.last().length = textLength - formatRanges.last().start;
205 // This method expects a well-formatted string, there is no error checking!
206 // Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
207 UiStyle::StyledString UiStyle::styleString(const QString &s_) {
209 if(s.length() > 65535) {
210 qWarning() << QString("String too long to be styled: %1").arg(s);
211 return StyledString();
214 result.formatList.append(qMakePair((quint16)0, (quint32)None));
215 quint32 curfmt = (quint32)None;
216 int pos = 0; quint16 length = 0;
218 pos = s.indexOf('%', pos);
220 if(s[pos+1] == '%') { // escaped %, we just remove one and continue
225 if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
226 if(s[pos+3] == '-') { // color off
227 curfmt &= 0x003fffff;
230 int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
231 //TODO: use 99 as transparent color (re mirc color "standard")
233 if(s[pos+3] == 'f') {
234 curfmt &= 0xf0ffffff;
235 curfmt |= (color << 24) | 0x00400000;
237 curfmt &= 0x0fffffff;
238 curfmt |= (color << 28) | 0x00800000;
242 } else if(s[pos+1] == 'O') { // reset formatting
243 curfmt &= 0x0000000f; // we keep message type-specific formatting
245 } else if(s[pos+1] == 'R') { // reverse
246 // TODO: implement reverse formatting
249 } else { // all others are toggles
250 QString code = QString("%") + s[pos+1];
251 if(s[pos+1] == 'D') code += s[pos+2];
252 FormatType ftype = formatType(code);
253 if(ftype == Invalid) {
254 qWarning(qPrintable(QString("Invalid format code in string: %1").arg(s)));
258 length = code.length();
260 s.remove(pos, length);
261 if(pos == result.formatList.last().first)
262 result.formatList.last().second = curfmt;
264 result.formatList.append(qMakePair((quint16)pos, curfmt));
266 result.plainText = s;
270 QString UiStyle::mircToInternal(const QString &mirc_) const {
271 QString mirc = mirc_;
272 mirc.replace('%', "%%"); // escape % just to be sure
273 mirc.replace('\x02', "%B");
274 mirc.replace('\x0f', "%O");
275 mirc.replace('\x12', "%R");
276 mirc.replace('\x16', "%R");
277 mirc.replace('\x1d', "%S");
278 mirc.replace('\x1f', "%U");
280 // Now we bring the color codes (\x03) in a sane format that can be parsed more easily later.
281 // %Dcfxx is foreground, %Dcbxx is background color, where xx is a 2 digit dec number denoting the color code.
282 // %Dc- turns color off.
283 // Note: We use the "mirc standard" as described in <http://www.mirc.co.uk/help/color.txt>.
284 // This means that we don't accept something like \x03,5 (even though others, like WeeChat, do).
287 pos = mirc.indexOf('\x03', pos);
288 if(pos < 0) break; // no more mirc color codes
290 int l = mirc.length();
292 // check for fg color
293 if(i < l && mirc[i].isDigit()) {
295 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
296 else num.prepend('0');
297 ins = QString("%Dcf%1").arg(num);
299 if(i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
302 if(i < l && mirc[i].isDigit()) num.append(mirc[i++]);
303 else num.prepend('0');
304 ins += QString("%Dcb%1").arg(num);
309 mirc.replace(pos, i-pos, ins);
314 UiStyle::StyledMessage UiStyle::styleMessage(const Message &msg) {
315 QString user = userFromMask(msg.sender());
316 QString host = hostFromMask(msg.sender());
317 QString nick = nickFromMask(msg.sender());
318 QString txt = mircToInternal(msg.contents());
319 QString bufferName = msg.bufferInfo().bufferName();
321 StyledMessage result;
323 result.timestamp = styleString(tr("%DT[%1]").arg(msg.timestamp().toLocalTime().toString("hh:mm:ss")));
328 s = tr("%DS<%1>").arg(nick); t = tr("%D0%1").arg(txt); break;
329 case Message::Notice:
330 s = tr("%Dn[%1]").arg(nick); t = tr("%Dn%1").arg(txt); break;
331 case Message::Server:
332 s = tr("%Ds*"); t = tr("%Ds%1").arg(txt); break;
334 s = tr("%De*"); t = tr("%De%1").arg(txt); break;
336 s = tr("%Dj-->"); t = tr("%Dj%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
338 s = tr("%Dp<--"); t = tr("%Dp%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
339 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
342 s = tr("%Dq<--"); t = tr("%Dq%DN%DU%1%DU%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
343 if(!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
347 QString victim = txt.section(" ", 0, 0);
348 //if(victim == ui.ownNick->currentText()) victim = tr("you");
349 QString kickmsg = txt.section(" ", 1);
350 t = tr("%Dk%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
351 if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
356 if(nick == msg.contents()) t = tr("%DrYou are now known as %DN%1%DN").arg(txt);
357 else t = tr("%Dr%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
361 if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(txt);
362 else t = tr("%DmMode %DM%1%DM by %DN%2%DN").arg(txt, nick);
364 case Message::Action:
366 t = tr("%Da%DN%1%DN %2").arg(nick).arg(txt);
369 s = tr("%De%1").arg(msg.sender());
370 t = tr("%De[%1]").arg(txt);
372 result.sender = styleString(s);
373 result.contents = styleString(t);
377 QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList) {
378 out << formatList.count();
379 UiStyle::FormatList::const_iterator it = formatList.begin();
380 while(it != formatList.end()) {
381 out << (*it).first << (*it).second;
387 QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList) {
390 for(quint16 i = 0; i < cnt; i++) {
391 quint16 pos; quint32 ftype;
393 formatList.append(qMakePair((quint16)pos, ftype));