Make Quassel not crash on color codes > 15 (Sput)
[quassel.git] / src / uisupport / uistyle.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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
21 #include "uistyle.h"
22 #include "uistylesettings.h"
23
24 UiStyle::UiStyle(const QString &settingsKey) : _settingsKey(settingsKey) {
25   // Default format
26   QTextCharFormat def;
27   def.setForeground(QBrush("#000000"));
28   def.setFont(QFont("Mono",12));
29   _defaultFormats = QVector<QTextCharFormat>(NumFormatTypes, def);
30   _customFormats = QVector<QTextCharFormat>(NumFormatTypes, QTextFormat().toCharFormat());
31
32   // Load saved custom formats
33   UiStyleSettings s(_settingsKey);
34   foreach(FormatType type, s.availableFormats()) {
35     _customFormats[type] = s.customFormat(type);
36   }
37
38   // Initialize color codes according to mIRC "standard"
39   QStringList colors;
40   //colors << "white" << "black" << "navy" << "green" << "red" << "maroon" << "purple" << "orange";
41   //colors << "yellow" << "lime" << "teal" << "aqua" << "royalblue" << "fuchsia" << "grey" << "silver";
42   colors << "#ffffff" << "#000000" << "#000080" << "#008000" << "#ff0000" << "#800000" << "#800080" << "#ffa500";
43   colors << "#ffff00" << "#00ff00" << "#008080" << "#00ffff" << "#4169E1" << "#ff00ff" << "#808080" << "#c0c0c0";
44
45   // Now initialize the mapping between FormatCodes and FormatTypes...
46   _formatCodes["%O"] = None;
47   _formatCodes["%B"] = Bold;
48   _formatCodes["%S"] = Italic;
49   _formatCodes["%U"] = Underline;
50   _formatCodes["%R"] = Reverse;
51
52   _formatCodes["%D0"] = PlainMsg;
53   _formatCodes["%Dn"] = NoticeMsg;
54   _formatCodes["%Ds"] = ServerMsg;
55   _formatCodes["%De"] = ErrorMsg;
56   _formatCodes["%Dj"] = JoinMsg;
57   _formatCodes["%Dp"] = PartMsg;
58   _formatCodes["%Dq"] = QuitMsg;
59   _formatCodes["%Dk"] = KickMsg;
60   _formatCodes["%Dr"] = RenameMsg;
61   _formatCodes["%Dm"] = ModeMsg;
62   _formatCodes["%Da"] = ActionMsg;
63
64   _formatCodes["%DT"] = Timestamp;
65   _formatCodes["%DS"] = Sender;
66   _formatCodes["%DN"] = Nick;
67   _formatCodes["%DH"] = Hostmask;
68   _formatCodes["%DC"] = ChannelName;
69   _formatCodes["%DM"] = ModeFlags;
70   _formatCodes["%DU"] = Url;
71
72   // Set color formats
73   for(int i = 0; i < 16; i++) {
74     QString idx = QString("%1").arg(i, (int)2, (int)10, (QChar)'0');
75     _formatCodes[QString("%Dcf%1").arg(idx)] = (FormatType)(FgCol00 + i);
76     _formatCodes[QString("%Dcb%1").arg(idx)] = (FormatType)(BgCol00 + i);
77     QTextCharFormat fgf, bgf;
78     fgf.setForeground(QBrush(QColor(colors[i]))); setFormat((FormatType)(FgCol00 + i), fgf, Settings::Default);
79     bgf.setBackground(QBrush(QColor(colors[i]))); setFormat((FormatType)(BgCol00 + i), bgf, Settings::Default);
80   }
81
82   // Set a few more standard formats
83   QTextCharFormat bold; bold.setFontWeight(QFont::Bold);
84   setFormat(Bold, bold, Settings::Default);
85
86   QTextCharFormat italic; italic.setFontItalic(true);
87   setFormat(Italic, italic, Settings::Default);
88
89   QTextCharFormat underline; underline.setFontUnderline(true);
90   setFormat(Underline, underline, Settings::Default);
91
92   // All other formats should be defined in derived classes.
93 }
94
95 UiStyle::~ UiStyle() {
96   
97 }
98
99 void UiStyle::setFormat(FormatType ftype, QTextCharFormat fmt, Settings::Mode mode) {
100   if(mode == Settings::Default) {
101     _defaultFormats[ftype] = fmt;
102   } else {
103     UiStyleSettings s(_settingsKey);
104     if(fmt != _defaultFormats[ftype]) {
105       _customFormats[ftype] = fmt;
106       s.setCustomFormat(ftype, fmt);
107     } else {
108       _customFormats[ftype] = QTextFormat().toCharFormat();
109       s.removeCustomFormat(ftype);
110     }
111   }
112 }
113
114 QTextCharFormat UiStyle::format(FormatType ftype, Settings::Mode mode) const {
115   if(mode == Settings::Custom && _customFormats[ftype].isValid()) return _customFormats[ftype];
116   else return _defaultFormats[ftype];
117 }
118
119 UiStyle::FormatType UiStyle::formatType(const QString & code) const {
120   if(_formatCodes.contains(code)) return _formatCodes.value(code);
121   return Invalid;
122 }
123
124 QString UiStyle::formatCode(FormatType ftype) const {
125   return _formatCodes.key(ftype);
126 }
127
128 UiStyle::StyledText UiStyle::styleString(QString s) {
129   StyledText result;
130   QList<FormatType> fmtList;
131   fmtList.append(None);
132   QTextLayout::FormatRange curFmtRng;
133   curFmtRng.format = format(None);
134   curFmtRng.start = 0;
135   result.formats.append(curFmtRng);
136   int pos = 0; int length;
137   int fgCol = -1, bgCol = -1;  // marks current mIRC color
138   for(;;) {
139     pos = s.indexOf('%', pos);
140     if(pos < 0) break;
141     if(s[pos+1] == '%') { // escaped %, just remove one and continue
142       s.remove(pos, 1);
143       pos++;
144       continue;
145     } else if(s[pos+1] == 'D' && s[pos+2] == 'c') { // color code
146       if(s[pos+3] == '-') { // color off
147         if(fgCol >= 0) {
148           fmtList.removeAll((FormatType)(FgCol00 + fgCol));
149           fgCol = -1;
150         }
151         if(bgCol >= 0) {
152           fmtList.removeAll((FormatType)(BgCol00 + bgCol));
153           bgCol = -1;
154         }
155         curFmtRng.format = mergedFormat(fmtList);
156         length = 4;
157       } else {
158         int color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
159         //TODO: use 99 as transparent color (re mirc color "standard")
160         color &= 0x0f;
161         int *colptr; FormatType coltype;
162         if(s[pos+3] == 'f') { // foreground
163           colptr = &fgCol; coltype = FgCol00;
164         } else {              // background
165           Q_ASSERT(s[pos+3] == 'b');
166           colptr = &bgCol; coltype = BgCol00;
167         }
168         if(*colptr >= 0) {
169           // color already set, remove format code and add new one
170           Q_ASSERT(fmtList.contains((FormatType)(coltype + *colptr)));
171           fmtList.removeAll((FormatType)(coltype + *colptr));
172           fmtList.append((FormatType)(coltype + color));
173           curFmtRng.format = mergedFormat(fmtList);
174         } else {
175           fmtList.append((FormatType)(coltype + color));
176           curFmtRng.format.merge(format(fmtList.last()));
177         }
178         *colptr = color;
179         length = 6;
180       }
181     } else if(s[pos+1] == 'O') { // reset formatting
182       fmtList.clear(); fmtList.append(None);
183       curFmtRng.format = format(None);
184       fgCol = bgCol = -1;
185       length = 2;
186     } else if(s[pos+1] == 'R') { // reverse
187       // TODO: implement reverse formatting
188
189       length = 2;
190     } else { // all others are toggles
191       QString code = QString("%") + s[pos+1];
192       if(s[pos+1] == 'D') code += s[pos+2];
193       FormatType ftype = formatType(code);
194       if(ftype == Invalid) {
195         qWarning(qPrintable(QString("Invalid format code in string: %1").arg(s)));
196         continue;
197       }
198       //Q_ASSERT(ftype != Invalid);
199       length = code.length();
200       if(!fmtList.contains(ftype)) {
201         // toggle it on
202         fmtList.append(ftype);
203         curFmtRng.format.merge(format(ftype));
204       } else {
205         // toggle it off
206         fmtList.removeAll(ftype);
207         curFmtRng.format = mergedFormat(fmtList);
208       }
209     }
210     s.remove(pos, length); // remove format code from string
211     // now see if something changed and else insert the format
212     if(curFmtRng.format == result.formats.last().format) continue;  // no change, so we just ignore
213     curFmtRng.start = pos;
214     if(pos == result.formats.last().start) {
215       // same starting point -> we just overwrite the old format
216       result.formats.last() = curFmtRng;
217     } else {
218       // fix length of last format
219       result.formats.last().length = pos - result.formats.last().start;
220       result.formats.append(curFmtRng);
221     }
222   }
223   result.formats.last().length = s.length() - result.formats.last().start;
224   if(result.formats.last().length == 0) result.formats.removeLast();
225   result.text = s;
226   return result;
227 }
228
229 QTextCharFormat UiStyle::mergedFormat(QList<FormatType> formatList) {
230   QTextCharFormat fmt;
231   foreach(FormatType ftype, formatList) {
232     fmt.merge(format(ftype));
233   }
234   return fmt;
235 }
236
237