common: Make frequently called util methods more efficient
[quassel.git] / src / qtui / qtuistyle.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "chatviewsettings.h"
22 #include "qtuistyle.h"
23
24 #include <QFile>
25 #include <QFileInfo>
26 #include <QTextStream>
27
28 QtUiStyle::QtUiStyle(QObject *parent) : UiStyle(parent)
29 {
30     ChatViewSettings s;
31     s.notify("UseCustomTimestampFormat", this, SLOT(updateUseCustomTimestampFormat()));
32     updateUseCustomTimestampFormat();
33     s.notify("TimestampFormat", this, SLOT(updateTimestampFormatString()));
34     updateTimestampFormatString();
35     s.notify("ShowSenderBrackets", this, SLOT(updateShowSenderBrackets()));
36     updateShowSenderBrackets();
37
38     // If no style sheet exists, generate it on first run.
39     initializeSettingsQss();
40 }
41
42
43 QtUiStyle::~QtUiStyle() {}
44
45 void QtUiStyle::updateUseCustomTimestampFormat()
46 {
47     ChatViewSettings s;
48     setUseCustomTimestampFormat(s.useCustomTimestampFormat());
49 }
50
51 void QtUiStyle::updateTimestampFormatString()
52 {
53     ChatViewSettings s;
54     setTimestampFormatString(s.timestampFormatString());
55 }
56
57 void QtUiStyle::updateShowSenderBrackets()
58 {
59     ChatViewSettings s;
60     enableSenderBrackets(s.showSenderBrackets());
61 }
62
63
64 void QtUiStyle::initializeSettingsQss()
65 {
66     QFileInfo settingsQss(Quassel::configDirPath() + "settings.qss");
67     // Only initialize if it doesn't already exist
68     if (settingsQss.exists())
69         return;
70
71     // Generate and load the new stylesheet
72     generateSettingsQss();
73     reload();
74 }
75
76 void QtUiStyle::generateSettingsQss() const
77 {
78     QFile settingsQss(Quassel::configDirPath() + "settings.qss");
79
80     if (!settingsQss.open(QFile::WriteOnly|QFile::Truncate)) {
81         qWarning() << "Could not open" << settingsQss.fileName() << "for writing!";
82         return;
83     }
84     QTextStream out(&settingsQss);
85
86     out << "// Style settings made in Quassel's configuration dialog\n"
87         << "// This file is automatically generated, do not edit\n";
88
89     // ChatView
90     ///////////
91     QtUiStyleSettings fs("Fonts");
92     if (fs.value("UseCustomChatViewFont").toBool())
93         out << "\n// ChatView Font\n"
94             << "ChatLine { " << fontDescription(fs.value("ChatView").value<QFont>()) << "; }\n";
95
96     QtUiStyleSettings s("Colors");
97     if (s.value("UseChatViewColors").toBool()) {
98         out << "\n// Custom ChatView Colors\n"
99
100         // markerline is special in that it always used to use a gradient, so we keep this behavior even with the new implementation
101         << "Palette { marker-line: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " << color("MarkerLine", s) << ", stop: 0.1 transparent); }\n"
102         << "ChatView { background: " << color("ChatViewBackground", s) << "; }\n\n"
103         << "ChatLine[label=\"highlight\"] {\n"
104         << "  foreground: " << color("Highlight", s) << ";\n"
105         << "  background: " << color("HighlightBackground", s) << ";\n"
106         << "}\n\n"
107         << "ChatLine::timestamp { foreground: " << color("Timestamp", s) << "; }\n\n"
108
109         << msgTypeQss("plain", "ChannelMsg", s)
110         << msgTypeQss("notice", "ServerMsg", s)
111         << msgTypeQss("action", "ActionMsg", s)
112         << msgTypeQss("nick", "CommandMsg", s)
113         << msgTypeQss("mode", "CommandMsg", s)
114         << msgTypeQss("join", "CommandMsg", s)
115         << msgTypeQss("part", "CommandMsg", s)
116         << msgTypeQss("quit", "CommandMsg", s)
117         << msgTypeQss("kick", "CommandMsg", s)
118         << msgTypeQss("kill", "CommandMsg", s)
119         << msgTypeQss("server", "ServerMsg", s)
120         << msgTypeQss("info", "ServerMsg", s)
121         << msgTypeQss("error", "ErrorMsg", s)
122         << msgTypeQss("daychange", "ServerMsg", s)
123         << msgTypeQss("topic", "CommandMsg", s)
124         << msgTypeQss("netsplit-join", "CommandMsg", s)
125         << msgTypeQss("netsplit-quit", "CommandMsg", s)
126         << msgTypeQss("invite", "CommandMsg", s)
127         << "\n";
128     }
129
130     if (s.value("UseSenderColors", true).toBool()) {
131         out << "\n// Sender Colors\n";
132         // Generate a color palette for easy reuse elsewhere
133         // NOTE: A color palette is not a complete replacement for specifying the colors below, as
134         // specifying the colors one-by-one instead of with QtUi::style()->brush(...) makes it easy
135         // to toggle the specific coloring of sender/nick at the cost of regenerating this file.
136         // See UiStyle::ColorRole
137         out << senderPaletteQss(s);
138
139         out << "ChatLine::sender#plain[sender=\"self\"] { foreground: palette(sender-color-self); }\n\n";
140
141         // Matches qssparser.cpp for UiStyle::PlainMsg
142         for (int i = 0; i < defaultSenderColors.count(); i++)
143             out << senderQss(i, "plain");
144
145         // Only color the nicks in CTCP ACTIONs if sender colors are enabled
146         if (s.value("UseSenderActionColors", true).toBool()) {
147             // For action messages, color the 'sender' column -and- the nick itself
148             out << "\n// Sender Nickname Colors for action messages\n"
149                 << "ChatLine::sender#action[sender=\"self\"] { foreground: palette(sender-color-self); }\n"
150                 << "ChatLine::nick#action[sender=\"self\"] { foreground: palette(sender-color-self); }\n\n";
151
152             // Matches qssparser.cpp for UiStyle::ActionMsg
153             for (int i = 0; i < defaultSenderColors.count(); i++)
154                 out << senderQss(i, "action", true);
155         }
156
157         // Only color the nicks in CTCP ACTIONs if sender colors are enabled
158         if (s.value("UseNickGeneralColors", true).toBool()) {
159             // For action messages, color the 'sender' column -and- the nick itself
160             out << "\n// Nickname colors for all messages\n"
161                 << "ChatLine::nick[sender=\"self\"] { foreground: palette(sender-color-self); }\n\n";
162
163             // Matches qssparser.cpp for any style of message (UiStyle::...)
164             for (int i = 0; i < defaultSenderColors.count(); i++)
165                 out << nickQss(i);
166         }
167
168     }
169
170     // ItemViews
171     ////////////
172
173     UiStyleSettings uiFonts("Fonts");
174     if (uiFonts.value("UseCustomItemViewFont").toBool()) {
175         QString fontDesc = fontDescription(uiFonts.value("ItemView").value<QFont>());
176         out << "\n// ItemView Font\n"
177             << "ChatListItem { " << fontDesc << "; }\n"
178             << "NickListItem { " << fontDesc << "; }\n\n";
179     }
180
181     UiStyleSettings uiColors("Colors");
182     if (uiColors.value("UseBufferViewColors").toBool()) {
183         out << "\n// BufferView Colors\n"
184             << "ChatListItem { foreground: " << color("DefaultBuffer", uiColors) << "; }\n"
185             << chatListItemQss("inactive", "InactiveBuffer", uiColors)
186             << chatListItemQss("channel-event", "ActiveBuffer", uiColors)
187             << chatListItemQss("unread-message", "UnreadBuffer", uiColors)
188             << chatListItemQss("highlighted", "HighlightedBuffer", uiColors);
189     }
190
191     if (uiColors.value("UseNickViewColors").toBool()) {
192         out << "\n// NickView Colors\n"
193             << "NickListItem[type=\"category\"] { foreground: " << color("DefaultBuffer", uiColors) << "; }\n"
194             << "NickListItem[type=\"user\"] { foreground: " << color("OnlineNick", uiColors) << "; }\n"
195             << "NickListItem[type=\"user\", state=\"away\"] { foreground: " << color("AwayNick", uiColors) << "; }\n";
196     }
197
198     settingsQss.close();
199 }
200
201
202 QString QtUiStyle::color(const QString &key, UiSettings &settings, const QColor &defaultColor) const
203 {
204     return settings.value(key, defaultColor).value<QColor>().name();
205 }
206
207
208 QString QtUiStyle::fontDescription(const QFont &font) const
209 {
210     QString desc = "font: ";
211     if (font.italic())
212         desc += "italic ";
213     if (font.bold())
214         desc += "bold ";
215     if (!font.italic() && !font.bold())
216         desc += "normal ";
217     desc += QString("%1pt \"%2\"").arg(font.pointSize()).arg(font.family());
218     return desc;
219 }
220
221
222 QString QtUiStyle::msgTypeQss(const QString &msgType, const QString &key, UiSettings &settings) const
223 {
224     return QString("ChatLine#%1 { foreground: %2; }\n").arg(msgType, color(key, settings));
225 }
226
227
228 QString QtUiStyle::senderPaletteQss(UiSettings &settings) const
229 {
230     QString result;
231     result += "Palette {\n";
232
233     // Generate entries for sender-color-self
234     result += QString("    sender-color-self: %1;\n")
235               .arg(color("SenderSelf", settings, defaultSenderColorSelf));
236
237     // Generate entries for sender-color-HASH
238     for (int i = 0; i < defaultSenderColors.count(); i++) {
239         QString dez = QString::number(i);
240         if (dez.length() == 1) dez.prepend('0');
241         result += QString("    sender-color-0%1: %2;\n")
242                 .arg(QString::number(i, 16), color("Sender"+dez, settings, defaultSenderColors[i]));
243     }
244     result += "}\n\n";
245     return result;
246 }
247
248
249 QString QtUiStyle::senderQss(int i, const QString &messageType, bool includeNick) const
250 {
251     QString dez = QString::number(i);
252     if (dez.length() == 1) dez.prepend('0');
253
254     if (includeNick) {
255         // Include the nickname in the color rules
256         return QString("ChatLine::sender#%1[sender=\"0%2\"] { foreground: palette(sender-color-0%2); }\n"
257                        "ChatLine::nick#%1[sender=\"0%2\"]   { foreground: palette(sender-color-0%2); }\n")
258                 .arg(messageType, QString::number(i, 16));
259     } else {
260         return QString("ChatLine::sender#%1[sender=\"0%2\"] { foreground: palette(sender-color-0%2); }\n")
261                 .arg(messageType, QString::number(i, 16));
262     }
263 }
264
265
266 QString QtUiStyle::nickQss(int i) const
267 {
268     QString dez = QString::number(i);
269     if (dez.length() == 1) dez.prepend('0');
270
271     return QString("ChatLine::nick[sender=\"0%1\"]   { foreground: palette(sender-color-0%1); }\n")
272             .arg(QString::number(i, 16));
273 }
274
275
276 QString QtUiStyle::chatListItemQss(const QString &state, const QString &key, UiSettings &settings) const
277 {
278     return QString("ChatListItem[state=\"%1\"] { foreground: %2; }\n").arg(state, color(key, settings));
279 }