Debian Codegraph @

garglk/theme.cpp

raw symbols SCIP
1 // Copyright (C) 2022-2023 by Chris Spiegel
2 //
3 // This file is part of Gargoyle.
4 //
5 // Gargoyle 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) any later version.
9 //
10 // Gargoyle 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 Gargoyle; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 #include <algorithm>
20 #include <array>
21 #include <exception>
22 #include <fstream>
23 #include <iostream>
24 #include <regex>
25 #include <stdexcept>
26 #include <string>
27 #include <unordered_map>
28 #include <utility>
29 #include <vector>
30
31 #if __cplusplus >= 201703L
32 #include <filesystem>
33 #else
34 #include <dirent.h>
35 #include <sys/types.h>
36 #endif
37
38 #include "format.h"
39 #include "optional.hpp"
40
41 #define JSON_DIAGNOSTICS 1
42 #ifdef __GNUC__
43 // Ignore false positives (see https://github.com/nlohmann/json/issues/3808)
44 #pragma GCC diagnostic push
45 #pragma GCC diagnostic ignored "-Warray-bounds"
46 #include "json.hpp"
47 #pragma GCC diagnostic pop
48 #else
49 #include "json.hpp"
50 #endif
51
52 #include "garglk.h"
53
54 #include THEME_DARK_H
55 #include THEME_LIGHT_H
56
57 using json = nlohmann::json;
58
59 template<size_t...Is, typename T>
60 std::array<T, sizeof...(Is)> make_array(const T &value, std::index_sequence<Is...>) {
61 return {(static_cast<void>(Is), value)...};
62 }
63
64 template<size_t N, typename T>
65 std::array<T, N> make_array(const T &value) {
66 return make_array(value, std::make_index_sequence<N>());
67 }
68
69 Color gli_parse_color(const std::string &str)
70 {
71 static const std::regex color_re(R"(#?[a-fA-F0-9]{6})");
72 std::string r, g, b;
73
74 if (!std::regex_match(str, color_re)) {
75 throw std::runtime_error(Format("invalid color: {}", str));
76 }
77
78 int pos = str[0] == '#' ? 1 : 0;
79
80 r = str.substr(pos + 0, 2);
81 g = str.substr(pos + 2, 2);
82 b = str.substr(pos + 4, 2);
83
84 return Color(std::stoul(r, nullptr, 16),
85 std::stoul(g, nullptr, 16),
86 std::stoul(b, nullptr, 16));
87 }
88
89 static const Color black = Color(0x00, 0x00, 0x00);
90 static const Color white = Color(0xff, 0xff, 0xff);
91 static const Color gray = Color(0x60, 0x60, 0x60);
92
93 namespace {
94
95 struct ColorPair {
96 Color fg;
97 Color bg;
98 };
99
100 }
101
102 namespace {
103
104 struct ThemeStyles {
105 std::array<ColorPair, style_NUMSTYLES> colors;
106
107 void to(Styles &styles) const {
108 for (int i = 0; i < style_NUMSTYLES; i++) {
109 styles[i].fg = colors[i].fg;
110 styles[i].bg = colors[i].bg;
111 }
112 }
113 };
114
115 struct Theme {
116 std::string name;
117 Color windowcolor;
118 Color bordercolor;
119 Color caretcolor;
120 Color linkcolor;
121 Color morecolor;
122 std::pair<Color, Color> scrollbar;
123 ThemeStyles tstyles;
124 ThemeStyles gstyles;
125
126 void apply() const {
127 gli_window_color = windowcolor;
128 gli_window_save = windowcolor;
129 gli_border_color = bordercolor;
130 gli_border_save = bordercolor;
131 gli_caret_color = caretcolor;
132 gli_caret_save = caretcolor;
133 gli_link_color = linkcolor;
134 gli_link_save = linkcolor;
135 gli_more_color = morecolor;
136 gli_more_save = morecolor;
137 gli_scroll_fg = scrollbar.first;
138 gli_scroll_bg = scrollbar.second;
139 tstyles.to(gli_tstyles);
140 gstyles.to(gli_gstyles);
141 }
142
143 static Theme from_json(const json::object_t &jo) {
144 json j = jo;
145
146 auto window = gli_parse_color(j.at("window"));
147 auto border = gli_parse_color(j.at("border"));
148 auto caret = gli_parse_color(j.at("caret"));
149 auto link = gli_parse_color(j.at("link"));
150 auto more = gli_parse_color(j.at("more"));
151 auto text_buffer = get_user_styles(j, "text_buffer");
152 auto text_grid = get_user_styles(j, "text_grid");
153
154 json::object_t scrollbar = j.at("scrollbar");
155 auto scrollbarfg = gli_parse_color(scrollbar.at("fg"));
156 auto scrollbarbg = gli_parse_color(scrollbar.at("bg"));
157
158 return {
159 j.at("name"),
160 window,
161 border,
162 caret,
163 link,
164 more,
165 {scrollbarfg, scrollbarbg},
166 text_buffer,
167 text_grid,
168 };
169 }
170
171 static Theme from_string(const std::string &string) {
172 return from_json(json::parse(string));
173 }
174
175 static Theme from_file(const std::string &filename) {
176 std::ifstream f(filename);
177 if (!f.is_open()) {
178 throw std::runtime_error("unable to open file");
179 }
180
181 return from_json(json::parse(f));
182 }
183
184 private:
185 static ThemeStyles get_user_styles(const json &j, const std::string &wintype)
186 {
187 std::array<nonstd::optional<ColorPair>, style_NUMSTYLES> possible_colors;
188 std::unordered_map<std::string, json> styles = j.at(wintype);
189
190 static const std::unordered_map<std::string, int> stylemap = {
191 {"normal", 0},
192 {"emphasized", 1},
193 {"preformatted", 2},
194 {"header", 3},
195 {"subheader", 4},
196 {"alert", 5},
197 {"note", 6},
198 {"blockquote", 7},
199 {"input", 8},
200 {"user1", 9},
201 {"user2", 10},
202 };
203
204 auto parse_colors = [&possible_colors](const json &style, int i) {
205 auto fg = gli_parse_color(style.at("fg"));
206 auto bg = gli_parse_color(style.at("bg"));
207 possible_colors[i] = ColorPair{fg, bg};
208 };
209
210 if (styles.find("default") != styles.end()) {
211 for (int i = 0; i < style_NUMSTYLES; i++) {
212 parse_colors(styles["default"], i);
213 }
214 }
215
216 styles.erase("default");
217 for (const auto &style : styles) {
218 try {
219 parse_colors(style.second, stylemap.at(style.first));
220 } catch (const std::out_of_range &) {
221 throw std::runtime_error(Format("invalid style in {}: {}", wintype, style.first));
222 }
223 }
224
225 auto colors = make_array<style_NUMSTYLES>(ColorPair{white, black});
226 std::vector<std::string> missing;
227 for (const auto &s : stylemap) {
228 try {
229 colors[s.second] = possible_colors[s.second].value();
230 } catch (const nonstd::bad_optional_access &) {
231 missing.push_back(s.first);
232 }
233 }
234
235 if (!missing.empty()) {
236 throw std::runtime_error(Format("{} is missing the following styles: {}", wintype, garglk::join(missing, ", ")));
237 }
238
239 return {colors};
240 }
241 };
242
243 }
244
245 static std::unordered_map<std::string, Theme> themes;
246
247 std::vector<std::string> garglk::theme::paths()
248 {
249 std::vector<std::string> theme_paths;
250
251 for (const auto &path : garglk::winthemedirs()) {
252 theme_paths.push_back(path);
253 }
254
255 return theme_paths;
256 }
257
258 #if __cplusplus >= 201703
259 static std::vector<std::string> directory_entries(const std::string &dir)
260 {
261 std::vector<std::string> entries;
262
263 try {
264 for (const auto &entry : std::filesystem::directory_iterator(dir)) {
265 entries.push_back(entry.path().string());
266 }
267 } catch (const std::filesystem::filesystem_error &) {
268 }
269
270 return entries;
271 }
272 #else
273 static std::vector<std::string> directory_entries(const std::string &dir)
274 {
275 auto d = garglk::unique(opendir(dir.c_str()), closedir);
276 if (d == nullptr) {
277 return {};
278 }
279
280 std::vector<std::string> entries;
281 dirent *de;
282 while ((de = readdir(d.get())) != nullptr) {
283 entries.push_back(Format("{}/{}", dir, de->d_name));
284 }
285
286 return entries;
287 }
288 #endif
289
290 void garglk::theme::init()
291 {
292 std::vector<std::pair<std::string, std::string>> builtin = {
293 {"dark", theme_dark},
294 {"light", theme_light},
295 };
296
297 themes.clear();
298
299 for (const auto &pair : builtin) {
300 try {
301 themes.insert({pair.first, Theme::from_string(pair.second)});
302 } catch (std::exception &e) {
303 std::cerr << "garglk: fatal error parsing internal " << pair.first << " theme: " << e.what() << std::endl;
304 std::exit(1);
305 }
306 }
307
308 auto paths = garglk::theme::paths();
309
310 // Gargoyle used to set an organization of io.github.garglk and a name
311 // of Gargoyle (in Qt), which led to directories of the form
312 // share/io.github.garglk/Gargoyle, which is fairly ridiculous. Gargoyle
313 // now just sets the name to "gargoyle" and leaves the organization
314 // blank, resulting in the more standard "share/gargoyle"; but themes in
315 // earlier releases were stored in the more verbose location. Existing
316 // user themes in these locations should work, but the locations should
317 // _not_ be part of the "standard" theme paths, or they'll be shown to
318 // the user, e.g. in "gargoyle --paths", and users should be discouraged
319 // from using the older names. So, when doing the actual theme loading,
320 // try loading from the legacy location as well, but ensure the legacy
321 // location has the lowest priority (first in the list), so newer themes
322 // with the same name take precedence.
323 auto legacy = garglk::winlegacythemedir();
324 if (legacy.has_value()) {
325 paths.insert(paths.begin(), *legacy);
326 }
327
328 for (const auto &themedir : paths) {
329 for (const auto &filename : directory_entries(themedir)) {
330 auto dot = filename.find_last_of('.');
331 if (dot != std::string::npos && filename.substr(dot) == ".json") {
332 try {
333 auto theme = Theme::from_file(filename);
334 // C++17: use insert_or_assign()
335 const auto result = themes.insert({theme.name, theme});
336 if (!result.second) {
337 result.first->second = theme;
338 }
339 } catch (const std::exception &e) {
340 std::cerr << "garglk: error parsing theme " << filename << ": " << e.what() << std::endl;
341 }
342 }
343 }
344 }
345
346 garglk::theme::set("system");
347 }
348
349 static std::string system_theme_name()
350 {
351 return windark() ? "dark" : "light";
352 }
353
354 bool garglk::theme::set(std::string name)
355 {
356 if (name == "system") {
357 name = system_theme_name();
358 }
359
360 try {
361 themes.at(name).apply();
362 return true;
363 } catch (const std::out_of_range &) {
364 return false;
365 }
366 }
367
368 std::vector<std::string> garglk::theme::names()
369 {
370 std::vector<std::string> theme_names;
371
372 for (const auto &theme : themes) {
373 theme_names.push_back(theme.first);
374 }
375
376 theme_names.push_back(Format("system ({})", system_theme_name()));
377
378 std::sort(theme_names.begin(), theme_names.end());
379
380 return theme_names;
381 }