| 1 | #include "css.h" |
| 2 | |
| 3 | #include <algorithm> |
| 4 | #include <cctype> |
| 5 | #include <cmath> |
| 6 | #include <cstdio> |
| 7 | #include <cstdlib> |
| 8 | #include <cstring> |
| 9 | |
| 10 | namespace twlite::css { |
| 11 | |
| 12 | namespace { |
| 13 | |
| 14 | bool space(char c) { return c == ' ' || c == '\t' || c == '\n' || |
| 15 | bool alpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z' |
| 16 | bool digit(char c) { return c >= '0' && c <= '9'; } |
| 17 | |
| 18 | bool valid_name(std::string_view name, size_t max, bool (*first)(char), bool (*rest)(char)) { |
| 19 | if (name.empty() || name.size() > max || !first(name[0])) return false; |
| 20 | for (size_t i = 1; i < name.size(); i++) |
| 21 | if (!rest(name[i])) return false; |
| 22 | return true; |
| 23 | } |
| 24 | |
| 25 | struct Named { |
| 26 | const char* name; |
| 27 | uint32_t rgb; |
| 28 | }; |
| 29 | |
| 30 | // CSS Color 4 named colours. |
| 31 | const Named NAMED[] = { |
| 32 | {"aliceblue", 0xf0f8ff}, {"antiquewhite", 0xfaebd7}, {"aqua", 0x00ffff}, {"aquamarine", 0x7fffd4}, {"azure", 0xf0ffff}, |
| 33 | {"beige", 0xf5f5dc}, {"bisque", 0xffe4c4}, {"black", 0x000000}, {"blanchedalmond", 0xffebcd}, {"blue", 0x0000ff}, |
| 34 | {"blueviolet", 0x8a2be2}, {"brown", 0xa52a2a}, {"burlywood", 0xdeb887}, {"cadetblue", 0x5f9ea0}, {"chartreuse", 0x7fff00}, |
| 35 | {"chocolate", 0xd2691e}, {"coral", 0xff7f50}, {"cornflowerblue", 0x6495ed}, {"cornsilk", 0xfff8dc}, {"crimson", 0xdc143c}, |
| 36 | {"cyan", 0x00ffff}, {"darkblue", 0x00008b}, {"darkcyan", 0x008b8b}, {"darkgoldenrod", 0xb8860b}, {"darkgray", 0xa9a9a9}, |
| 37 | {"darkgreen", 0x006400}, {"darkgrey", 0xa9a9a9}, {"darkkhaki", 0xbdb76b}, {"darkmagenta", 0x8b008b}, {"darkolivegreen", 0x556b2f}, |
| 38 | {"darkorange", 0xff8c00}, {"darkorchid", 0x9932cc}, {"darkred", 0x8b0000}, {"darksalmon", 0xe9967a}, {"darkseagreen", 0x8fbc8f}, |
| 39 | {"darkslateblue", 0x483d8b}, {"darkslategray", 0x2f4f4f}, {"darkslategrey", 0x2f4f4f}, {"darkturquoise", 0x00ced1}, {"darkviolet", 0x9400d3}, |
| 40 | {"deeppink", 0xff1493}, {"deepskyblue", 0x00bfff}, {"dimgray", 0x696969}, {"dimgrey", 0x696969}, {"dodgerblue", 0x1e90ff}, |
| 41 | {"firebrick", 0xb22222}, {"floralwhite", 0xfffaf0}, {"forestgreen", 0x228b22}, {"fuchsia", 0xff00ff}, {"gainsboro", 0xdcdcdc}, |
| 42 | {"ghostwhite", 0xf8f8ff}, {"gold", 0xffd700}, {"goldenrod", 0xdaa520}, {"gray", 0x808080}, {"green", 0x008000}, |
| 43 | {"greenyellow", 0xadff2f}, {"grey", 0x808080}, {"honeydew", 0xf0fff0}, {"hotpink", 0xff69b4}, {"indianred", 0xcd5c5c}, |
| 44 | {"indigo", 0x4b0082}, {"ivory", 0xfffff0}, {"khaki", 0xf0e68c}, {"lavender", 0xe6e6fa}, {"lavenderblush", 0xfff0f5}, |
| 45 | {"lawngreen", 0x7cfc00}, {"lemonchiffon", 0xfffacd}, {"lightblue", 0xadd8e6}, {"lightcoral", 0xf08080}, {"lightcyan", 0xe0ffff}, |
| 46 | {"lightgoldenrodyellow", 0xfafad2}, {"lightgray", 0xd3d3d3}, {"lightgreen", 0x90ee90}, {"lightgrey", 0xd3d3d3}, {"lightpink", 0xffb6c1}, |
| 47 | {"lightsalmon", 0xffa07a}, {"lightseagreen", 0x20b2aa}, {"lightskyblue", 0x87cefa}, {"lightslategray", 0x778899}, {"lightslategrey", 0x778899}, |
| 48 | {"lightsteelblue", 0xb0c4de}, {"lightyellow", 0xffffe0}, {"lime", 0x00ff00}, {"limegreen", 0x32cd32}, {"linen", 0xfaf0e6}, |
| 49 | {"magenta", 0xff00ff}, {"maroon", 0x800000}, {"mediumaquamarine", 0x66cdaa}, {"mediumblue", 0x0000cd}, {"mediumorchid", 0xba55d3}, |
| 50 | {"mediumpurple", 0x9370db}, {"mediumseagreen", 0x3cb371}, {"mediumslateblue", 0x7b68ee}, {"mediumspringgreen", 0x00fa9a}, {"mediumturquoise", 0x48d1cc}, |
| 51 | {"mediumvioletred", 0xc71585}, {"midnightblue", 0x191970}, {"mintcream", 0xf5fffa}, {"mistyrose", 0xffe4e1}, {"moccasin", 0xffe4b5}, |
| 52 | {"navajowhite", 0xffdead}, {"navy", 0x000080}, {"oldlace", 0xfdf5e6}, {"olive", 0x808000}, {"olivedrab", 0x6b8e23}, |
| 53 | {"orange", 0xffa500}, {"orangered", 0xff4500}, {"orchid", 0xda70d6}, {"palegoldenrod", 0xeee8aa}, {"palegreen", 0x98fb98}, |
| 54 | {"paleturquoise", 0xafeeee}, {"palevioletred", 0xdb7093}, {"papayawhip", 0xffefd5}, {"peachpuff", 0xffdab9}, {"peru", 0xcd853f}, |
| 55 | {"pink", 0xffc0cb}, {"plum", 0xdda0dd}, {"powderblue", 0xb0e0e6}, {"purple", 0x800080}, {"rebeccapurple", 0x663399}, |
| 56 | {"red", 0xff0000}, {"rosybrown", 0xbc8f8f}, {"royalblue", 0x4169e1}, {"saddlebrown", 0x8b4513}, {"salmon", 0xfa8072}, |
| 57 | {"sandybrown", 0xf4a460}, {"seagreen", 0x2e8b57}, {"seashell", 0xfff5ee}, {"sienna", 0xa0522d}, {"silver", 0xc0c0c0}, |
| 58 | {"skyblue", 0x87ceeb}, {"slateblue", 0x6a5acd}, {"slategray", 0x708090}, {"slategrey", 0x708090}, {"snow", 0xfffafa}, |
| 59 | {"springgreen", 0x00ff7f}, {"steelblue", 0x4682b4}, {"tan", 0xd2b48c}, {"teal", 0x008080}, {"thistle", 0xd8bfd8}, |
| 60 | {"tomato", 0xff6347}, {"turquoise", 0x40e0d0}, {"violet", 0xee82ee}, {"wheat", 0xf5deb3}, {"white", 0xffffff}, |
| 61 | {"whitesmoke", 0xf5f5f5}, {"yellow", 0xffff00}, {"yellowgreen", 0x9acd32}, |
| 62 | }; |
| 63 | |
| 64 | bool named_color(std::string_view word, Color& out) { |
| 65 | std::string l = lower(std::string(word)); |
| 66 | if (l == "transparent") { |
| 67 | out = Color{0, 0, 0, 0}; |
| 68 | return true; |
| 69 | } |
| 70 | for (const Named& n : NAMED) { |
| 71 | if (l == n.name) { |
| 72 | out = Color{uint8_t(n.rgb >> 16), uint8_t(n.rgb >> 8), uint8_t(n.rgb), 255}; |
| 73 | return true; |
| 74 | } |
| 75 | } |
| 76 | return false; |
| 77 | } |
| 78 | |
| 79 | int hex_value(char c) { |
| 80 | if (digit(c)) return c - '0'; |
| 81 | if (c >= 'a' && c <= 'f') return c - 'a' + 10; |
| 82 | if (c >= 'A' && c <= 'F') return c - 'A' + 10; |
| 83 | return -1; |
| 84 | } |
| 85 | |
| 86 | bool parse_hex(std::string_view hex, double rgba[4]) { |
| 87 | for (char c : hex) |
| 88 | if (hex_value(c) < 0) return false; |
| 89 | switch (hex.size()) { |
| 90 | case 3: case 4: |
| 91 | for (size_t i = 0; i < hex.size(); i++) rgba[i] = hex_value(hex[i]) * 17; |
| 92 | rgba[3] = hex.size() == 4 ? rgba[3] / 255 : 1; |
| 93 | return true; |
| 94 | case 6: case 8: |
| 95 | for (size_t i = 0; i < hex.size() / 2; i++) rgba[i] = hex_value(hex[2 * i]) * 16 |
| 96 | rgba[3] = hex.size() == 8 ? rgba[3] / 255 : 1; |
| 97 | return true; |
| 98 | default: |
| 99 | return false; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// The numbers inside `rgb(...)`/`hsl(...)`, split at commas, spaces and `/`; `%` divides by 100. |
| 104 | std::vector<double> components(std::string_view inner, bool* percent = nullptr) { |
| 105 | std::vector<double> out; |
| 106 | std::string cur; |
| 107 | auto flush = [&] { |
| 108 | if (cur.empty()) return; |
| 109 | bool pct = cur.back() == '%'; |
| 110 | if (pct) cur.pop_back(); |
| 111 | if (ends_with(cur, "deg")) cur.resize(cur.size() - 3); |
| 112 | if (auto v = number(cur)) { |
| 113 | out.push_back(pct ? *v / 100 : *v); |
| 114 | if (percent && out.size() <= 3) percent[out.size() - 1] = pct; |
| 115 | } |
| 116 | cur.clear(); |
| 117 | }; |
| 118 | for (char c : inner) { |
| 119 | if (c == ',' || c == '/' || space(c)) flush(); |
| 120 | else cur.push_back(c); |
| 121 | } |
| 122 | flush(); |
| 123 | return out; |
| 124 | } |
| 125 | |
| 126 | void rgba_string(const double c[4], std::string& out) { |
| 127 | out += "rgba("; |
| 128 | out += format_number(c[0]); |
| 129 | out += ", "; |
| 130 | out += format_number(c[1]); |
| 131 | out += ", "; |
| 132 | out += format_number(c[2]); |
| 133 | out += ", "; |
| 134 | out += format_number(c[3]); |
| 135 | out += ")"; |
| 136 | } |
| 137 | |
| 138 | uint8_t channel(double v) { return uint8_t(std::lround(std::clamp(v, 0.0, 255.0))); } |
| 139 | |
| 140 | // calc() of times, as twidget's CSSTime: + and - of like quantities, * and / by numbers. |
| 141 | struct Quantity { |
| 142 | double value; |
| 143 | bool time; |
| 144 | }; |
| 145 | |
| 146 | struct TimeScanner { |
| 147 | std::string_view s; |
| 148 | size_t i = 0; |
| 149 | |
| 150 | void skip() { while (i < s.size() && space(s[i])) i++; } |
| 151 | bool take(char c) { |
| 152 | skip(); |
| 153 | if (i < s.size() && s[i] == c) { i++; return true; } |
| 154 | return false; |
| 155 | } |
| 156 | bool at_end() { skip(); return i == s.size(); } |
| 157 | |
| 158 | std::optional<Quantity> sum(int depth) { |
| 159 | if (depth >= 16) return std::nullopt; |
| 160 | auto left = product(depth); |
| 161 | if (!left) return std::nullopt; |
| 162 | for (;;) { |
| 163 | if (take('+')) { |
| 164 | auto right = product(depth); |
| 165 | if (!right || right->time != left->time) return std::nullopt; |
| 166 | left->value += right->value; |
| 167 | } else if (take('-')) { |
| 168 | auto right = product(depth); |
| 169 | if (!right || right->time != left->time) return std::nullopt; |
| 170 | left->value -= right->value; |
| 171 | } else return left; |
| 172 | } |
| 173 | } |
| 174 | std::optional<Quantity> product(int depth) { |
| 175 | auto left = factor(depth); |
| 176 | if (!left) return std::nullopt; |
| 177 | for (;;) { |
| 178 | if (take('*')) { |
| 179 | auto right = factor(depth); |
| 180 | if (!right || (left->time && right->time)) return std::nullopt; |
| 181 | left = Quantity{left->value * right->value, left->time || right->time}; |
| 182 | } else if (take('/')) { |
| 183 | auto right = factor(depth); |
| 184 | if (!right || right->time || right->value == 0) return std::nullopt; |
| 185 | left->value /= right->value; |
| 186 | } else return left; |
| 187 | } |
| 188 | } |
| 189 | std::optional<Quantity> factor(int depth) { |
| 190 | skip(); |
| 191 | if (s.substr(i, 5) == "calc(") i += 4; |
| 192 | if (take('(')) { |
| 193 | auto inner = sum(depth + 1); |
| 194 | if (!inner || !take(')')) return std::nullopt; |
| 195 | return inner; |
| 196 | } |
| 197 | size_t start = i; |
| 198 | if (i < s.size() && (s[i] == '-' || s[i] == '+')) i++; |
| 199 | while (i < s.size() && (digit(s[i]) || s[i] == '.')) i++; |
| 200 | if (i == start) return std::nullopt; |
| 201 | auto v = number(s.substr(start, i - start)); |
| 202 | if (!v) return std::nullopt; |
| 203 | if (s.substr(i, 2) == "ms") { i += 2; return Quantity{*v / 1000, true}; } |
| 204 | if (i < s.size() && s[i] == 's') { i++; return Quantity{*v, true}; } |
| 205 | return Quantity{*v, false}; |
| 206 | } |
| 207 | }; |
| 208 | |
| 209 | } // namespace |
| 210 | |
| 211 | std::string trim(std::string_view s) { |
| 212 | size_t a = 0, b = s.size(); |
| 213 | while (a < b && space(s[a])) a++; |
| 214 | while (b > a && space(s[b - 1])) b--; |
| 215 | return std::string(s.substr(a, b - a)); |
| 216 | } |
| 217 | |
| 218 | std::string lower(std::string s) { |
| 219 | for (auto& c : s) c = char(std::tolower((unsigned char)c)); |
| 220 | return s; |
| 221 | } |
| 222 | |
| 223 | bool iequals(std::string_view a, std::string_view b) { |
| 224 | if (a.size() != b.size()) return false; |
| 225 | for (size_t i = 0; i < a.size(); i++) |
| 226 | if (std::tolower((unsigned char)a[i]) != std::tolower((unsigned char)b[i])) return false; |
| 227 | return true; |
| 228 | } |
| 229 | |
| 230 | bool starts_with(std::string_view s, std::string_view prefix) { return s.substr(0, prefix.size()) == prefix; } |
| 231 | bool ends_with(std::string_view s, std::string_view suffix) { return s.size() >= suffix.size() && s.substr(s.size() - |
| 232 | |
| 233 | std::optional<double> number(std::string_view s) { |
| 234 | std::string t = trim(s); |
| 235 | if (t.empty()) return std::nullopt; |
| 236 | char* end = nullptr; |
| 237 | double v = std::strtod(t.c_str(), &end); |
| 238 | if (end != t.c_str() + t.size() || !std::isfinite(v)) return std::nullopt; |
| 239 | return v; |
| 240 | } |
| 241 | |
| 242 | std::vector<std::string> split_top_level(std::string_view text, char separator) { |
| 243 | std::vector<std::string> parts; |
| 244 | std::string current; |
| 245 | int depth = 0; |
| 246 | char quote = 0; |
| 247 | bool escaped = false; |
| 248 | for (char ch : text) { |
| 249 | if (escaped) { escaped = false; current.push_back(ch); continue; } |
| 250 | if (ch == '\\') { escaped = true; current.push_back(ch); continue; } |
| 251 | if (quote) { |
| 252 | if (ch == quote) quote = 0; |
| 253 | current.push_back(ch); |
| 254 | continue; |
| 255 | } |
| 256 | if (ch == '"' || ch == '\'') quote = ch; |
| 257 | else if (ch == '(') depth++; |
| 258 | else if (ch == ')') depth = std::max(0, depth - 1); |
| 259 | if (ch == separator && depth == 0) { |
| 260 | parts.push_back(std::move(current)); |
| 261 | current.clear(); |
| 262 | } else current.push_back(ch); |
| 263 | } |
| 264 | if (!current.empty()) parts.push_back(std::move(current)); |
| 265 | return parts; |
| 266 | } |
| 267 | |
| 268 | std::vector<Declaration> parse_declarations(std::string_view text) { |
| 269 | std::vector<Declaration> result; |
| 270 | for (const std::string& part : split_top_level(text, ';')) { |
| 271 | size_t colon = part.find(':'); |
| 272 | if (colon == std::string::npos) continue; |
| 273 | std::string name = trim(std::string_view(part).substr(0, colon)); |
| 274 | std::string value = trim(std::string_view(part).substr(colon + 1)); |
| 275 | if (name.empty() || value.empty()) continue; |
| 276 | bool important = false; |
| 277 | if (value.size() >= 10 && iequals(std::string_view(value).substr(value.size() - 10), "!important")) { |
| 278 | important = true; |
| 279 | value = trim(std::string_view(value).substr(0, value.size() - 10)); |
| 280 | } |
| 281 | if (!starts_with(name, "--")) name = lower(name); |
| 282 | if (!is_property_name(name)) continue; |
| 283 | result.erase(std::remove_if(result.begin(), result.end(), [&](const Declaration& d) { return d.name == name; }), result.end()); |
| 284 | result.push_back({std::move(name), std::move(value), important}); |
| 285 | } |
| 286 | return result; |
| 287 | } |
| 288 | |
| 289 | bool is_tag_name(std::string_view name) { |
| 290 | return valid_name(name, 64, alpha, [](char c) { return alpha(c) || digit(c) || c == '-'; }); |
| 291 | } |
| 292 | |
| 293 | bool is_attribute_name(std::string_view name) { |
| 294 | return valid_name(name, 64, [](char c) { return alpha(c) || c == '_' || c == ':'; }, |
| 295 | [](char c) { return alpha(c) || digit(c) || c == '_' || c == ':' || c == '.' |
| 296 | } |
| 297 | |
| 298 | bool is_property_name(std::string_view name) { |
| 299 | std::string_view body = starts_with(name, "--") ? name.substr(2) : starts_with(name, "-") ? name.substr(1) : name; |
| 300 | auto ok = [](char c) { return alpha(c) || digit(c) || c == '-' || c == '_'; }; |
| 301 | return valid_name(body, 128, ok, ok); |
| 302 | } |
| 303 | |
| 304 | std::string resolve_light_dark(std::string_view css, bool dark) { |
| 305 | static constexpr std::string_view KEY = "light-dark("; |
| 306 | auto find = [](std::string_view s, size_t from) { |
| 307 | for (size_t i = from; i + KEY.size() <= s.size(); i++) |
| 308 | if (iequals(s.substr(i, KEY.size()), KEY)) return i; |
| 309 | return std::string_view::npos; |
| 310 | }; |
| 311 | if (find(css, 0) == std::string_view::npos) return std::string(css); |
| 312 | std::string out; |
| 313 | size_t pos = 0; |
| 314 | for (int guard = 0; guard < 4096; guard++) { |
| 315 | size_t at = find(css, pos); |
| 316 | if (at == std::string_view::npos) break; |
| 317 | out.append(css.substr(pos, at - pos)); |
| 318 | size_t i = at + KEY.size(); |
| 319 | int depth = 1; |
| 320 | size_t close = i; |
| 321 | for (; close < css.size(); close++) { |
| 322 | if (css[close] == '(') depth++; |
| 323 | else if (css[close] == ')' && --depth == 0) break; |
| 324 | } |
| 325 | auto parts = split_top_level(css.substr(i, close - i), ','); |
| 326 | std::string chosen = parts.size() == 2 ? parts[dark ? 1 : 0] : parts.empty() ? std::string() |
| 327 | // The chosen side may hold another light-dark(). |
| 328 | out += resolve_light_dark(trim(chosen), dark); |
| 329 | pos = close < css.size() ? close + 1 : css.size(); |
| 330 | } |
| 331 | out.append(css.substr(pos)); |
| 332 | return out; |
| 333 | } |
| 334 | |
| 335 | std::optional<double> parse_time(std::string_view text) { |
| 336 | std::string t = lower(trim(text)); |
| 337 | if (starts_with(t, "calc(")) { |
| 338 | if (t.size() > 512) return std::nullopt; |
| 339 | TimeScanner scanner{t}; |
| 340 | auto q = scanner.sum(0); |
| 341 | if (!q || !scanner.at_end() || !q->time || !std::isfinite(q->value)) return std::nullopt; |
| 342 | return q->value; |
| 343 | } |
| 344 | if (ends_with(t, "ms")) { |
| 345 | if (auto v = number(std::string_view(t).substr(0, t.size() - 2))) return *v / 1000; |
| 346 | return std::nullopt; |
| 347 | } |
| 348 | if (ends_with(t, "s")) return number(std::string_view(t).substr(0, t.size() - 1)); |
| 349 | return std::nullopt; |
| 350 | } |
| 351 | |
| 352 | bool parse_color(std::string_view text, Color& out) { |
| 353 | std::string t = lower(trim(text)); |
| 354 | if (t.empty()) return false; |
| 355 | if (t[0] == '#') { |
| 356 | double c[4]; |
| 357 | if (!parse_hex(std::string_view(t).substr(1), c)) return false; |
| 358 | out = Color{channel(c[0]), channel(c[1]), channel(c[2]), channel(c[3] * 255)}; |
| 359 | return true; |
| 360 | } |
| 361 | size_t open = t.find('('); |
| 362 | if (open != std::string::npos && t.back() == ')') { |
| 363 | std::string fn = t.substr(0, open); |
| 364 | std::string_view inner = std::string_view(t).substr(open + 1, t.size() - open - 2); |
| 365 | if (fn == "rgb" || fn == "rgba") { |
| 366 | bool pct[3] = {false, false, false}; |
| 367 | auto v = components(inner, pct); |
| 368 | if (v.size() < 3) return false; |
| 369 | for (int i = 0; i < 3; i++) if (pct[i]) v[i] *= 255; |
| 370 | out = Color{channel(v[0]), channel(v[1]), channel(v[2]), channel((v.size() > 3 ? v[3] : 1) |
| 371 | return true; |
| 372 | } |
| 373 | if (fn == "hsl" || fn == "hsla") { |
| 374 | auto v = components(inner); |
| 375 | if (v.size() < 3) return false; |
| 376 | double h = std::fmod(std::fmod(v[0], 360) + 360, 360) / 360, s = std:: |
| 377 | double q = l < 0.5 ? l * (1 + s) : l + s - l * s, p = 2 * l |
| 378 | auto hue = [&](double t0) { |
| 379 | double t1 = t0 < 0 ? t0 + 1 : t0 > 1 ? t0 - 1 : t0; |
| 380 | if (t1 < 1.0 / 6) return p + (q - p) * 6 * t1; |
| 381 | if (t1 < 1.0 / 2) return q; |
| 382 | if (t1 < 2.0 / 3) return p + (q - p) * (2.0 / 3 - t1) * 6; |
| 383 | return p; |
| 384 | }; |
| 385 | out = Color{channel(hue(h + 1.0 / 3) * 255), channel(hue(h) * 255), channel(hue(h |
| 386 | return true; |
| 387 | } |
| 388 | return false; |
| 389 | } |
| 390 | if (t == "currentcolor") { |
| 391 | out = Color{0, 0, 0, 255}; |
| 392 | return true; |
| 393 | } |
| 394 | return named_color(t, out); |
| 395 | } |
| 396 | |
| 397 | std::string normalize_colors(std::string_view text) { |
| 398 | std::string out; |
| 399 | out.reserve(text.size() + 16); |
| 400 | size_t i = 0; |
| 401 | while (i < text.size()) { |
| 402 | char c = text[i]; |
| 403 | if (c == '#') { |
| 404 | size_t j = i + 1; |
| 405 | while (j < text.size() && hex_value(text[j]) >= 0) j++; |
| 406 | double rgba[4]; |
| 407 | if (parse_hex(text.substr(i + 1, j - i - 1), rgba)) { |
| 408 | rgba_string(rgba, out); |
| 409 | i = j; |
| 410 | continue; |
| 411 | } |
| 412 | } |
| 413 | if (alpha(c) && (i == 0 || !(alpha(text[i - 1]) || digit(text[i - 1]) || text[i |
| 414 | size_t j = i; |
| 415 | while (j < text.size() && (alpha(text[j]) || text[j] == '-')) j++; |
| 416 | std::string_view word = text.substr(i, j - i); |
| 417 | if (j < text.size() && text[j] == '(') { |
| 418 | if (iequals(word, "rgb") || iequals(word, "rgba")) { |
| 419 | size_t close = text.find(')', j); |
| 420 | if (close != std::string_view::npos) { |
| 421 | bool pct[3] = {false, false, false}; |
| 422 | auto v = components(text.substr(j + 1, close - j - 1), pct); |
| 423 | if (v.size() >= 3) { |
| 424 | for (int k = 0; k < 3; k++) if (pct[k]) v[k] *= 255; |
| 425 | double rgba[4] = {v[0], v[1], v[2], v.size() > 3 ? v[3] : 1}; |
| 426 | rgba_string(rgba, out); |
| 427 | i = close + 1; |
| 428 | continue; |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | } else { |
| 433 | Color named; |
| 434 | if (named_color(word, named)) { |
| 435 | double rgba[4] = {double(named.r), double(named.g), double(named.b), named.a / 255.0}; |
| 436 | rgba_string(rgba, out); |
| 437 | i = j; |
| 438 | continue; |
| 439 | } |
| 440 | } |
| 441 | out.append(word); |
| 442 | i = j; |
| 443 | continue; |
| 444 | } |
| 445 | out.push_back(c); |
| 446 | i++; |
| 447 | } |
| 448 | return out; |
| 449 | } |
| 450 | |
| 451 | std::string format_number(double value, int digits) { |
| 452 | if (!std::isfinite(value)) return "0"; |
| 453 | if (value == std::round(value) && std::fabs(value) < 1e9) return std::to_string((long long)value); |
| 454 | char buf[64]; |
| 455 | std::snprintf(buf, sizeof buf, "%.*f", digits, value); |
| 456 | std::string s = buf; |
| 457 | while (!s.empty() && s.back() == '0') s.pop_back(); |
| 458 | if (!s.empty() && s.back() == '.') s.pop_back(); |
| 459 | if (s == "-0") s = "0"; |
| 460 | return s; |
| 461 | } |
| 462 | |
| 463 | Font parse_font(std::string_view font) { |
| 464 | Font f; |
| 465 | std::vector<std::string> tokens; |
| 466 | { |
| 467 | std::string cur; |
| 468 | char quote = 0; |
| 469 | for (char c : font) { |
| 470 | if (quote) { |
| 471 | if (c == quote) quote = 0; |
| 472 | cur.push_back(c); |
| 473 | } else if (c == '"' || c == '\'') { |
| 474 | quote = c; |
| 475 | cur.push_back(c); |
| 476 | } else if (space(c)) { |
| 477 | if (!cur.empty()) tokens.push_back(cur); |
| 478 | cur.clear(); |
| 479 | } else cur.push_back(c); |
| 480 | } |
| 481 | if (!cur.empty()) tokens.push_back(cur); |
| 482 | } |
| 483 | size_t i = 0; |
| 484 | for (; i < tokens.size(); i++) { |
| 485 | std::string t = lower(tokens[i]); |
| 486 | if (t == "italic" || t == "oblique") f.italic = true; |
| 487 | else if (t == "bold" || t == "bolder") f.weight = 700; |
| 488 | else if (t == "lighter") f.weight = 300; |
| 489 | else if (t == "normal" || t == "small-caps") {} |
| 490 | else if (t.size() == 3 && digit(t[0]) && digit(t[1]) && digit(t[2])) f.weight = |
| 491 | else if (digit(t[0]) || t[0] == '.') { |
| 492 | std::string size = t.substr(0, t.find('/')); |
| 493 | float v = float(std::atof(size.c_str())); |
| 494 | if (ends_with(size, "pt")) v *= 96.0f / 72.0f; |
| 495 | else if (ends_with(size, "rem") || ends_with(size, "em")) v *= 16.0f; |
| 496 | else if (ends_with(size, "%")) v *= 16.0f / 100.0f; |
| 497 | if (v > 0 && v < 4096) f.size = v; |
| 498 | i++; |
| 499 | break; |
| 500 | } else break; |
| 501 | } |
| 502 | if (i < tokens.size()) { |
| 503 | f.family.clear(); |
| 504 | for (; i < tokens.size(); i++) { |
| 505 | if (!f.family.empty()) f.family += ' '; |
| 506 | f.family += tokens[i]; |
| 507 | } |
| 508 | } |
| 509 | return f; |
| 510 | } |
| 511 | |
| 512 | // ── transforms ── |
| 513 | |
| 514 | namespace { |
| 515 | |
| 516 | constexpr double PI = 3.14159265358979323846; |
| 517 | |
| 518 | /// A number with its unit, lowercased: `12.5px` → (12.5, "px"). |
| 519 | std::optional<std::pair<double, std::string>> dimension(std::string_view text) { |
| 520 | std::string t = trim(text); |
| 521 | size_t i = 0; |
| 522 | if (i < t.size() && (t[i] == '+' || t[i] == '-')) i++; |
| 523 | while (i < t.size() && (digit(t[i]) || t[i] == '.')) i++; |
| 524 | if (i < t.size() && (t[i] == 'e' || t[i] == 'E') && i + 1 < t.size() && ( |
| 525 | i += 2; |
| 526 | while (i < t.size() && digit(t[i])) i++; |
| 527 | } |
| 528 | auto value = number(std::string_view(t).substr(0, i)); |
| 529 | if (!value) return std::nullopt; |
| 530 | return std::make_pair(*value, lower(t.substr(i))); |
| 531 | } |
| 532 | |
| 533 | std::optional<double> length(std::string_view text, double percent_of) { |
| 534 | auto d = dimension(text); |
| 535 | if (!d) return std::nullopt; |
| 536 | if (d->second == "px" || (d->second.empty() && d->first == 0)) return d->first; |
| 537 | if (d->second == "%") return d->first * percent_of / 100; |
| 538 | return std::nullopt; |
| 539 | } |
| 540 | |
| 541 | std::optional<double> angle(std::string_view text) { |
| 542 | auto d = dimension(text); |
| 543 | if (!d) return std::nullopt; |
| 544 | const std::string& u = d->second; |
| 545 | if (u == "deg" || (u.empty() && d->first == 0)) return d->first * PI / 180; |
| 546 | if (u == "rad") return d->first; |
| 547 | if (u == "grad") return d->first * PI / 200; |
| 548 | if (u == "turn") return d->first * 2 * PI; |
| 549 | return std::nullopt; |
| 550 | } |
| 551 | |
| 552 | std::optional<double> scalar(std::string_view text) { |
| 553 | auto d = dimension(text); |
| 554 | if (!d) return std::nullopt; |
| 555 | if (d->second.empty()) return d->first; |
| 556 | if (d->second == "%") return d->first / 100; |
| 557 | return std::nullopt; |
| 558 | } |
| 559 | |
| 560 | std::vector<std::string> arguments(std::string_view inner) { |
| 561 | std::vector<std::string> out; |
| 562 | for (const std::string& part : split_top_level(inner, ',')) { |
| 563 | std::string token; |
| 564 | for (char c : part) { |
| 565 | if (space(c)) { |
| 566 | if (!token.empty()) out.push_back(std::move(token)); |
| 567 | token.clear(); |
| 568 | } else token.push_back(c); |
| 569 | } |
| 570 | if (!token.empty()) out.push_back(std::move(token)); |
| 571 | } |
| 572 | return out; |
| 573 | } |
| 574 | |
| 575 | Affine rotation(double radians) { |
| 576 | float c = float(std::cos(radians)), s = float(std::sin(radians)); |
| 577 | return Affine{c, s, -s, c, 0, 0}; |
| 578 | } |
| 579 | |
| 580 | std::optional<Affine> function(const std::string& name, const std::vector<std::string>& args, |
| 581 | size_t n = args.size(); |
| 582 | if (name == "matrix") { |
| 583 | if (n != 6) return std::nullopt; |
| 584 | float v[6]; |
| 585 | for (size_t i = 0; i < 6; i++) { |
| 586 | auto x = number(args[i]); |
| 587 | if (!x) return std::nullopt; |
| 588 | v[i] = float(*x); |
| 589 | } |
| 590 | return Affine{v[0], v[1], v[2], v[3], v[4], v[5]}; |
| 591 | } |
| 592 | if (name == "translate" || name == "translate3d") { |
| 593 | if (n < 1 || n > (name == "translate" ? 2u : 3u)) return std::nullopt; |
| 594 | auto x = length(args[0], w); |
| 595 | auto y = n > 1 ? length(args[1], h) : std::optional<double>(0); |
| 596 | if (!x || !y || (n == 3 && length(args[2], 0) != 0.0)) return std::nullopt; |
| 597 | return Affine::translate(float(*x), float(*y)); |
| 598 | } |
| 599 | if (name == "translatex" || name == "translatey") { |
| 600 | if (n != 1) return std::nullopt; |
| 601 | auto v = length(args[0], name == "translatex" ? w : h); |
| 602 | if (!v) return std::nullopt; |
| 603 | return name == "translatex" ? Affine::translate(float(*v), 0) : Affine::translate(0, float(*v)); |
| 604 | } |
| 605 | if (name == "translatez") return n == 1 && length(args[0], 0) == 0.0 ? std::optional< |
| 606 | if (name == "scale" || name == "scale3d") { |
| 607 | if (n < 1 || n > (name == "scale" ? 2u : 3u)) return std::nullopt; |
| 608 | auto x = scalar(args[0]); |
| 609 | auto y = n > 1 ? scalar(args[1]) : x; |
| 610 | if (!x || !y || (n == 3 && scalar(args[2]) != 1.0)) return std::nullopt; |
| 611 | return Affine{float(*x), 0, 0, float(*y), 0, 0}; |
| 612 | } |
| 613 | if (name == "scalex" || name == "scaley") { |
| 614 | auto v = n == 1 ? scalar(args[0]) : std::nullopt; |
| 615 | if (!v) return std::nullopt; |
| 616 | return name == "scalex" ? Affine{float(*v), 0, 0, 1, 0, 0} : Affine{1, 0, 0, |
| 617 | } |
| 618 | if (name == "rotate" || name == "rotatez") { |
| 619 | auto a = n == 1 ? angle(args[0]) : std::nullopt; |
| 620 | if (!a) return std::nullopt; |
| 621 | return rotation(*a); |
| 622 | } |
| 623 | if (name == "skew" || name == "skewx" || name == "skewy") { |
| 624 | if (n < 1 || n > (name == "skew" ? 2u : 1u)) return std::nullopt; |
| 625 | auto ax = name == "skewy" ? std::optional<double>(0) : angle(args[0]); |
| 626 | auto ay = name == "skewy" ? angle(args[0]) : n > 1 ? angle(args[1]) : std:: |
| 627 | if (!ax || !ay) return std::nullopt; |
| 628 | return Affine{1, float(std::tan(*ay)), float(std::tan(*ax)), 1, 0, 0}; |
| 629 | } |
| 630 | return std::nullopt; |
| 631 | } |
| 632 | |
| 633 | } // namespace |
| 634 | |
| 635 | std::optional<Affine> parse_transform(std::string_view text, float w, float h) { |
| 636 | std::string t = trim(text); |
| 637 | if (t.empty() || iequals(t, "none")) return Affine{}; |
| 638 | Affine result; |
| 639 | size_t pos = 0; |
| 640 | while (true) { |
| 641 | while (pos < t.size() && space(t[pos])) pos++; |
| 642 | if (pos == t.size()) break; |
| 643 | size_t open = t.find('(', pos); |
| 644 | if (open == std::string::npos) return std::nullopt; |
| 645 | size_t close = t.find(')', open); |
| 646 | if (close == std::string::npos) return std::nullopt; |
| 647 | std::string name = lower(trim(std::string_view(t).substr(pos, open - pos))); |
| 648 | auto args = arguments(std::string_view(t).substr(open + 1, close - open - 1)); |
| 649 | auto m = function(name, args, w, h); |
| 650 | if (!m) return std::nullopt; |
| 651 | result = result * *m; |
| 652 | pos = close + 1; |
| 653 | } |
| 654 | return result; |
| 655 | } |
| 656 | |
| 657 | std::optional<Affine> parse_translate(std::string_view text, float w, float h) { |
| 658 | std::string t = trim(text); |
| 659 | if (t.empty() || iequals(t, "none")) return Affine{}; |
| 660 | auto args = arguments(t); |
| 661 | if (args.empty() || args.size() > 3) return std::nullopt; |
| 662 | auto x = length(args[0], w); |
| 663 | auto y = args.size() > 1 ? length(args[1], h) : std::optional<double>(0); |
| 664 | if (!x || !y || (args.size() == 3 && length(args[2], 0) != 0.0)) return |
| 665 | return Affine::translate(float(*x), float(*y)); |
| 666 | } |
| 667 | |
| 668 | std::optional<Affine> parse_rotate(std::string_view text) { |
| 669 | std::string t = trim(text); |
| 670 | if (t.empty() || iequals(t, "none")) return Affine{}; |
| 671 | auto args = arguments(t); |
| 672 | if (args.size() == 2 && iequals(args[0], "z")) args.erase(args.begin()); |
| 673 | auto a = args.size() == 1 ? angle(args[0]) : std::nullopt; |
| 674 | if (!a) return std::nullopt; |
| 675 | return rotation(*a); |
| 676 | } |
| 677 | |
| 678 | std::optional<Affine> parse_scale(std::string_view text) { |
| 679 | std::string t = trim(text); |
| 680 | if (t.empty() || iequals(t, "none")) return Affine{}; |
| 681 | auto args = arguments(t); |
| 682 | if (args.empty() || args.size() > 3) return std::nullopt; |
| 683 | auto x = scalar(args[0]); |
| 684 | auto y = args.size() > 1 ? scalar(args[1]) : x; |
| 685 | if (!x || !y || (args.size() == 3 && scalar(args[2]) != 1.0)) return std::nullopt; |
| 686 | return Affine{float(*x), 0, 0, float(*y), 0, 0}; |
| 687 | } |
| 688 | |
| 689 | std::optional<std::pair<float, float>> parse_origin(std::string_view text, float w, float h) { |
| 690 | auto args = arguments(trim(text)); |
| 691 | if (args.empty()) return std::make_pair(w / 2, h / 2); |
| 692 | if (args.size() > 3 || (args.size() == 3 && length(args[2], 0) != 0.0)) return |
| 693 | // A vertical keyword first (`top left`) means the same as the other order. |
| 694 | if (args.size() >= 2) { |
| 695 | std::string a = lower(args[0]), b = lower(args[1]); |
| 696 | if (a == "top" || a == "bottom" || b == "left" || b == "right") std::swap(args[0], args[ |
| 697 | } else { |
| 698 | std::string a = lower(args[0]); |
| 699 | if (a == "top" || a == "bottom") args = {"center", args[0]}; |
| 700 | } |
| 701 | auto axis = [](const std::string& v, float size, bool horizontal) -> std::optional<float> { |
| 702 | std::string k = lower(v); |
| 703 | if (k == "center") return size / 2; |
| 704 | if (horizontal ? k == "left" : k == "top") return 0.0f; |
| 705 | if (horizontal ? k == "right" : k == "bottom") return size; |
| 706 | auto l = length(v, size); |
| 707 | return l ? std::optional<float>(float(*l)) : std::nullopt; |
| 708 | }; |
| 709 | auto x = axis(args[0], w, true); |
| 710 | auto y = args.size() > 1 ? axis(args[1], h, false) : std::optional<float>(h / 2); |
| 711 | if (!x || !y) return std::nullopt; |
| 712 | return std::make_pair(*x, *y); |
| 713 | } |
| 714 | |
| 715 | std::optional<float> parse_opacity(std::string_view text) { |
| 716 | auto v = scalar(text); |
| 717 | if (!v) return std::nullopt; |
| 718 | return float(std::clamp(*v, 0.0, 1.0)); |
| 719 | } |
| 720 | |
| 721 | } // namespace twlite::css |
| 722 | |