| 1 | #include "animations.h" |
| 2 | |
| 3 | #include "css.h" |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <cctype> |
| 7 | #include <cmath> |
| 8 | #include <limits> |
| 9 | #include <set> |
| 10 | |
| 11 | using twidget::Json; |
| 12 | |
| 13 | namespace twlite { |
| 14 | |
| 15 | namespace { |
| 16 | |
| 17 | constexpr double INF = std::numeric_limits<double>::infinity(); |
| 18 | |
| 19 | bool is_digit(char c) { return c >= '0' && c <= '9'; } |
| 20 | bool is_letter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z' |
| 21 | |
| 22 | const std::unordered_map<std::string, std::string>& initial_values() { |
| 23 | static const std::unordered_map<std::string, std::string> v = { |
| 24 | {"opacity", "1"}, {"transform", "none"}, {"translate", "0px"}, {"scale", "1"}, {"rotate", "0deg"}, {"filter", "none"}, {"letter-spacing", "0px"}, |
| 25 | }; |
| 26 | return v; |
| 27 | } |
| 28 | |
| 29 | const std::string* initial_value(const std::string& property) { |
| 30 | auto it = initial_values().find(property); |
| 31 | return it == initial_values().end() ? nullptr : &it->second; |
| 32 | } |
| 33 | |
| 34 | void merge(StyleValues& into, const std::string& property, std::string value) { |
| 35 | into.erase(std::remove_if(into.begin(), into.end(), [&](const auto& p) { return p.first == property; }), into.end()); |
| 36 | into.emplace_back(property, std::move(value)); |
| 37 | } |
| 38 | |
| 39 | const std::string* last_value(const StyleValues& values, const std::string& property) { |
| 40 | for (auto it = values.rbegin(); it != values.rend(); ++it) |
| 41 | if (it->first == property) return &it->second; |
| 42 | return nullptr; |
| 43 | } |
| 44 | |
| 45 | double bezier_at(double x1, double y1, double x2, double y2, double x) { |
| 46 | if (x <= 0) return 0; |
| 47 | if (x >= 1) return 1; |
| 48 | double cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx; |
| 49 | double cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by; |
| 50 | auto sample_x = [&](double t) { return ((ax * t + bx) * t + cx) * t; }; |
| 51 | auto sample_y = [&](double t) { return ((ay * t + by) * t + cy) * t; }; |
| 52 | auto derivative_x = [&](double t) { return (3 * ax * t + 2 * bx) * t + cx; }; |
| 53 | double t = x; |
| 54 | for (int i = 0; i < 8; i++) { |
| 55 | double error = sample_x(t) - x; |
| 56 | if (std::fabs(error) < 1e-6) return sample_y(t); |
| 57 | double d = derivative_x(t); |
| 58 | if (std::fabs(d) < 1e-6) break; |
| 59 | t -= error / d; |
| 60 | } |
| 61 | double lo = 0, hi = 1; |
| 62 | t = x; |
| 63 | for (int i = 0; i < 30; i++) { |
| 64 | double value = sample_x(t); |
| 65 | if (std::fabs(value - x) < 1e-6) break; |
| 66 | if (value < x) lo = t; else hi = t; |
| 67 | t = (lo + hi) / 2; |
| 68 | } |
| 69 | return sample_y(t); |
| 70 | } |
| 71 | |
| 72 | std::optional<Timing> linear_function(std::string_view body) { |
| 73 | struct Point { double output; std::optional<double> input; }; |
| 74 | std::vector<Point> points; |
| 75 | for (const std::string& item : css::split_top_level(body, ',')) { |
| 76 | std::vector<std::string> parts; |
| 77 | for (const std::string& p : css::split_top_level(item, ' ')) |
| 78 | if (!css::trim(p).empty()) parts.push_back(css::trim(p)); |
| 79 | if (parts.empty()) return std::nullopt; |
| 80 | auto output = css::number(parts[0]); |
| 81 | if (!output) return std::nullopt; |
| 82 | if (parts.size() == 1) points.push_back({*output, std::nullopt}); |
| 83 | for (size_t i = 1; i < parts.size(); i++) { |
| 84 | if (!css::ends_with(parts[i], "%")) return std::nullopt; |
| 85 | auto input = css::number(std::string_view(parts[i]).substr(0, parts[i].size() - 1)); |
| 86 | if (!input) return std::nullopt; |
| 87 | points.push_back({*output, *input / 100}); |
| 88 | } |
| 89 | if (points.size() > 10000) return std::nullopt; |
| 90 | } |
| 91 | Timing t; |
| 92 | t.kind = Timing::Points; |
| 93 | if (points.empty()) return std::nullopt; |
| 94 | if (points.size() == 1) { |
| 95 | t.points = {{0, points[0].output}, {1, points[0].output}}; |
| 96 | return t; |
| 97 | } |
| 98 | if (!points[0].input) points[0].input = 0; |
| 99 | if (!points.back().input) { |
| 100 | double largest = 1; |
| 101 | for (const auto& p : points) if (p.input) largest = std::max(largest, *p.input); |
| 102 | points.back().input = largest; |
| 103 | } |
| 104 | double largest = *points[0].input; |
| 105 | for (auto& p : points) { |
| 106 | if (p.input) { |
| 107 | largest = std::max(largest, *p.input); |
| 108 | p.input = largest; |
| 109 | } |
| 110 | } |
| 111 | for (size_t i = 0; i < points.size(); i++) { |
| 112 | if (points[i].input) continue; |
| 113 | size_t start = i - 1, end = i; |
| 114 | while (!points[end].input) end++; |
| 115 | double from = *points[start].input, to = *points[end].input; |
| 116 | for (size_t k = start + 1; k < end; k++) points[k].input = from + (to - from) * double(k - start) / double(end |
| 117 | i = end; |
| 118 | } |
| 119 | for (const auto& p : points) t.points.emplace_back(*p.input, p.output); |
| 120 | return t; |
| 121 | } |
| 122 | |
| 123 | // ── interpolation tokens ── |
| 124 | |
| 125 | struct Token { |
| 126 | bool number = false; |
| 127 | double value = 0; |
| 128 | std::string text; // the unit of a number, or the text between numbers |
| 129 | }; |
| 130 | |
| 131 | std::vector<Token> tokenize(std::string_view s) { |
| 132 | std::vector<Token> tokens; |
| 133 | std::string pending; |
| 134 | auto flush = [&] { |
| 135 | if (!pending.empty()) tokens.push_back(Token{false, 0, std::move(pending)}); |
| 136 | pending.clear(); |
| 137 | }; |
| 138 | size_t i = 0, n = s.size(); |
| 139 | while (i < n) { |
| 140 | char c = s[i]; |
| 141 | bool starts = is_digit(c) || (c == '.' && i + 1 < n && is_digit(s[i + 1])) || ((c |
| 142 | char previous = i > 0 ? s[i - 1] : 0; |
| 143 | bool ident_part = i > 0 && (is_letter(previous) || (previous == '-' && i > 1 && is_letter(s[i - |
| 144 | if (starts && !(ident_part && c != '-') && previous != '#') { |
| 145 | size_t j = i + 1; |
| 146 | while (j < n && (is_digit(s[j]) || s[j] == '.' || ((s[j] == 'e' || s[j] == 'E') && j + |
| 147 | if (s[j] == 'e' || s[j] == 'E') j++; |
| 148 | j++; |
| 149 | } |
| 150 | size_t k = j; |
| 151 | while (k < n && (is_letter(s[k]) || s[k] == '%')) k++; |
| 152 | if (auto v = css::number(s.substr(i, j - i))) { |
| 153 | flush(); |
| 154 | tokens.push_back(Token{true, *v, std::string(s.substr(j, k - j))}); |
| 155 | i = k; |
| 156 | continue; |
| 157 | } |
| 158 | } |
| 159 | pending.push_back(c); |
| 160 | i++; |
| 161 | } |
| 162 | flush(); |
| 163 | return tokens; |
| 164 | } |
| 165 | |
| 166 | /// The functions of a transform list: (name lowercased, whole `name(args)` text). |
| 167 | std::vector<std::pair<std::string, std::string>> functions(std::string_view transform, std::string* rest_out |
| 168 | std::vector<std::pair<std::string, std::string>> out; |
| 169 | size_t pos = 0; |
| 170 | for (;;) { |
| 171 | size_t open = transform.find('(', pos); |
| 172 | if (open == std::string_view::npos) break; |
| 173 | size_t close = transform.find(')', open); |
| 174 | if (close == std::string_view::npos) break; |
| 175 | out.emplace_back(css::lower(css::trim(transform.substr(pos, open - pos))), css::trim(transform.substr(pos, close + 1 - pos))); |
| 176 | pos = close + 1; |
| 177 | } |
| 178 | if (rest_out) *rest_out = std::string(transform.substr(pos)); |
| 179 | return out; |
| 180 | } |
| 181 | |
| 182 | /// Each function's arguments joined back as `name(a, b)`. |
| 183 | std::vector<std::string> arguments(const std::string& fn) { |
| 184 | size_t open = fn.find('('), close = fn.rfind(')'); |
| 185 | std::vector<std::string> out; |
| 186 | if (open == std::string::npos || close == std::string::npos || close < open) return out; |
| 187 | for (const std::string& a : css::split_top_level(std::string_view(fn).substr(open + 1, close - open - 1), ',')) out. |
| 188 | return out; |
| 189 | } |
| 190 | |
| 191 | /// One-argument shorthands rewritten to their two-argument forms, so `translateX(4px)` pairs with `translate(0, 8px)`. |
| 192 | std::optional<std::string> primitive(std::string_view transform) { |
| 193 | std::string rest; |
| 194 | auto list = functions(transform, &rest); |
| 195 | if (list.empty() || !css::trim(rest).empty()) return std::nullopt; |
| 196 | std::string out; |
| 197 | for (const auto& [name, whole] : list) { |
| 198 | auto args = arguments(whole); |
| 199 | std::string item; |
| 200 | if (args.size() == 1) { |
| 201 | const std::string& a = args[0]; |
| 202 | if (name == "translatex" || name == "translate") item = "translate(" + a + ", 0)"; |
| 203 | else if (name == "translatey") item = "translate(0, " + a + ")"; |
| 204 | else if (name == "scalex") item = "scale(" + a + ", 1)"; |
| 205 | else if (name == "scaley") item = "scale(1, " + a + ")"; |
| 206 | else if (name == "scale") item = "scale(" + a + ", " + a + ")"; |
| 207 | else if (name == "skewx" || name == "skew") item = "skew(" + a + ", 0)"; |
| 208 | else if (name == "skewy") item = "skew(0, " + a + ")"; |
| 209 | } |
| 210 | if (item.empty()) { |
| 211 | item = name + "("; |
| 212 | for (size_t i = 0; i < args.size(); i++) item += (i ? ", " : "") + args[i]; |
| 213 | item += ")"; |
| 214 | } |
| 215 | if (!out.empty()) out += ' '; |
| 216 | out += item; |
| 217 | } |
| 218 | return out; |
| 219 | } |
| 220 | |
| 221 | /// The identity of each function in a transform or filter list: `rotate(30deg)` → `rotate(0deg)`. |
| 222 | std::string identity(std::string_view transform) { |
| 223 | static const std::set<std::string> ones = {"scale", "scalex", "scaley", "scale3d", "brightness", "contrast", "opacity", "saturate"}; |
| 224 | auto list = functions(transform); |
| 225 | if (list.empty()) return std::string(transform); |
| 226 | std::string out; |
| 227 | for (const auto& [name, whole] : list) { |
| 228 | size_t open = whole.find('('), close = whole.rfind(')'); |
| 229 | std::string original = whole.substr(0, open); |
| 230 | std::string inner = whole.substr(open + 1, close - open - 1); |
| 231 | std::string args; |
| 232 | bool first = true; |
| 233 | for (const std::string& arg : css::split_top_level(inner, ',')) { |
| 234 | size_t lead = 0; |
| 235 | while (lead < arg.size() && (arg[lead] == ' ' || arg[lead] == '\t')) lead++; |
| 236 | std::string value; |
| 237 | if (ones.count(name)) value = "1"; |
| 238 | else { |
| 239 | std::string t = css::trim(arg); |
| 240 | size_t u = 0; |
| 241 | while (u < t.size() && (is_digit(t[u]) || t[u] == '.' || t[u] == '-' || t[u] == '+')) u++; |
| 242 | value = "0" + t.substr(u); |
| 243 | } |
| 244 | args += (first ? "" : ",") + arg.substr(0, lead) + value; |
| 245 | first = false; |
| 246 | } |
| 247 | out += (out.empty() ? "" : " ") + original + "(" + args + ")"; |
| 248 | } |
| 249 | return out; |
| 250 | } |
| 251 | |
| 252 | /// A shorter transform list padded with the identities of the longer one's extra functions. |
| 253 | std::optional<std::pair<std::string, std::string>> padded(const std::string& a, const std:: |
| 254 | auto x = functions(a), y = functions(b); |
| 255 | bool a_short = x.size() < y.size(); |
| 256 | const auto& shorter = a_short ? x : y; |
| 257 | const auto& longer = a_short ? y : x; |
| 258 | if (shorter.empty() && longer.empty()) return std::nullopt; |
| 259 | for (size_t i = 0; i < shorter.size(); i++) |
| 260 | if (shorter[i].first != longer[i].first) return std::nullopt; |
| 261 | std::string extra; |
| 262 | for (size_t i = shorter.size(); i < longer.size(); i++) extra += (extra.empty() ? "" : " ") + identity(longer[i].second); |
| 263 | if (a_short) return std::make_pair(a + " " + extra, b); |
| 264 | return std::make_pair(a, b + " " + extra); |
| 265 | } |
| 266 | |
| 267 | bool translation_list(std::string_view text) { |
| 268 | std::string t = css::lower(css::trim(text)); |
| 269 | std::string rest; |
| 270 | auto list = functions(t, &rest); |
| 271 | if (list.empty() || !css::trim(rest).empty()) return false; |
| 272 | for (const auto& [name, whole] : list) { |
| 273 | if (name != "translate" && name != "translatex" && name != "translatey") return false; |
| 274 | size_t open = whole.find('('); |
| 275 | if (whole.find('(', open + 1) != std::string::npos) return false; |
| 276 | } |
| 277 | return true; |
| 278 | } |
| 279 | |
| 280 | std::string scaled_tokens(std::string_view text, double factor) { |
| 281 | std::string out; |
| 282 | for (const Token& t : tokenize(text)) out += t.number ? css::format_number(t.value * factor) + t.text : t.text; |
| 283 | return out; |
| 284 | } |
| 285 | |
| 286 | std::optional<std::pair<std::vector<Token>, std::vector<Token>>> pair_tokens(const std::string& a, |
| 287 | thread_local std::unordered_map<std::string, std::optional<std::pair<std::vector<Token>, std::vector<Token>>>> cache; |
| 288 | std::string key = a + '\x01' + b; |
| 289 | if (auto it = cache.find(key); it != cache.end()) return it->second; |
| 290 | std::string from = css::normalize_colors(a), to = css::normalize_colors(b); |
| 291 | if (css::iequals(from, "none") && to.find('(') != std::string::npos) from = identity(to); |
| 292 | else if (css::iequals(to, "none") && from.find('(') != std::string::npos) to = identity(from); |
| 293 | auto left = tokenize(from), right = tokenize(to); |
| 294 | if (left.size() != right.size()) { |
| 295 | auto pa = primitive(from), pb = primitive(to); |
| 296 | if (pa && pb) { |
| 297 | left = tokenize(*pa); |
| 298 | right = tokenize(*pb); |
| 299 | if (left.size() != right.size()) { |
| 300 | if (auto p = padded(*pa, *pb)) { |
| 301 | left = tokenize(p->first); |
| 302 | right = tokenize(p->second); |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | std::optional<std::pair<std::vector<Token>, std::vector<Token>>> result; |
| 308 | if (left.size() == right.size()) result = std::make_pair(std::move(left), std::move(right)); |
| 309 | if (cache.size() >= 2048) cache.clear(); |
| 310 | if (key.size() <= 4096) cache.emplace(std::move(key), result); |
| 311 | return result; |
| 312 | } |
| 313 | |
| 314 | // ── Web Animations composite (add / accumulate) ── |
| 315 | |
| 316 | std::vector<Token> web_tokenize(std::string_view s) { |
| 317 | std::vector<Token> tokens; |
| 318 | std::string pending; |
| 319 | size_t i = 0, n = s.size(); |
| 320 | while (i < n) { |
| 321 | char c = s[i]; |
| 322 | char next = i + 1 < n ? s[i + 1] : 0; |
| 323 | char previous = i > 0 ? s[i - 1] : 0; |
| 324 | bool starts = is_digit(c) || (c == '.' && is_digit(next)) || ((c == '-' || c == '+') && ( |
| 325 | bool in_word = i > 0 && (is_letter(previous) || previous == '#' || (previous == '-' && c != '-')); |
| 326 | if (starts && !in_word) { |
| 327 | size_t j = i + 1; |
| 328 | while (j < n && (is_digit(s[j]) || s[j] == '.' || ((s[j] == 'e' || s[j] == 'E') && j + |
| 329 | j += (s[j] == 'e' || s[j] == 'E') ? 2 : 1; |
| 330 | size_t k = j; |
| 331 | while (k < n && (is_letter(s[k]) || s[k] == '%')) k++; |
| 332 | if (auto v = css::number(s.substr(i, j - i))) { |
| 333 | if (!pending.empty()) tokens.push_back(Token{false, 0, std::move(pending)}); |
| 334 | pending.clear(); |
| 335 | tokens.push_back(Token{true, *v, std::string(s.substr(j, k - j))}); |
| 336 | i = k; |
| 337 | continue; |
| 338 | } |
| 339 | } |
| 340 | pending.push_back(c); |
| 341 | i++; |
| 342 | } |
| 343 | if (!pending.empty()) tokens.push_back(Token{false, 0, std::move(pending)}); |
| 344 | return tokens; |
| 345 | } |
| 346 | |
| 347 | std::string web_render(const std::vector<Token>& tokens) { |
| 348 | std::string out; |
| 349 | for (const Token& t : tokens) out += t.number ? css::format_number(t.value, 6) + t.text : t.text; |
| 350 | return out; |
| 351 | } |
| 352 | |
| 353 | /// The function a text token opens: `"rotate("` → `rotate`, `") scale("` → `scale`. |
| 354 | std::optional<std::string> opened_function(const std::string& text) { |
| 355 | size_t open = text.rfind('('); |
| 356 | if (open == std::string::npos) return std::nullopt; |
| 357 | std::string before = text.substr(0, open); |
| 358 | size_t start = before.find_last_of(" ,"); |
| 359 | return css::lower(start == std::string::npos ? before : before.substr(start + 1)); |
| 360 | } |
| 361 | |
| 362 | bool unit_scale(const std::string& fn) { return fn == "scale" || fn == "scalex" || fn == "scaley" |
| 363 | |
| 364 | std::optional<std::string> web_combine(const std::string& a, const std::string& b, bool scale_aware |
| 365 | auto left = web_tokenize(css::normalize_colors(a)), right = web_tokenize(css::normalize_colors(b)); |
| 366 | if (left.size() != right.size()) return std::nullopt; |
| 367 | std::vector<Token> out; |
| 368 | std::string function; |
| 369 | int color_channel = -1; |
| 370 | for (size_t i = 0; i < left.size(); i++) { |
| 371 | const Token &x = left[i], &y = right[i]; |
| 372 | if (!x.number && !y.number && css::iequals(x.text, y.text)) { |
| 373 | out.push_back(x); |
| 374 | if (auto fn = opened_function(x.text)) { |
| 375 | function = *fn; |
| 376 | color_channel = function == "rgba" ? 0 : -1; |
| 377 | } else if (color_channel >= 0) color_channel++; |
| 378 | } else if (x.number && y.number && (x.text == y.text || x.value == 0 || y.value == 0)) { |
| 379 | double value = x.value + y.value; |
| 380 | if (scale_aware && unit_scale(function)) value = x.value + y.value - 1; |
| 381 | if (color_channel >= 0) value = color_channel < 3 ? std::clamp(value, 0.0, 255.0) : std::clamp(value, 0.0, |
| 382 | out.push_back(Token{true, value, x.text.empty() ? y.text : x.text}); |
| 383 | } else return std::nullopt; |
| 384 | } |
| 385 | return web_render(out); |
| 386 | } |
| 387 | |
| 388 | std::string web_add(const std::string& underlying, const std::string& value, const std::string& |
| 389 | if (property == "transform") { |
| 390 | std::string u = css::trim(underlying), v = css::trim(value); |
| 391 | if (u.empty() || css::iequals(u, "none")) return v; |
| 392 | if (v.empty() || css::iequals(v, "none")) return u; |
| 393 | if (accumulate) { |
| 394 | if (auto c = web_combine(u, v, true)) return *c; |
| 395 | } |
| 396 | return u + " " + v; |
| 397 | } |
| 398 | if (auto c = web_combine(underlying, value, false)) return *c; |
| 399 | return value; |
| 400 | } |
| 401 | |
| 402 | std::string web_scaled(const std::string& value, double factor) { |
| 403 | std::string function; |
| 404 | auto tokens = web_tokenize(css::normalize_colors(value)); |
| 405 | for (Token& t : tokens) { |
| 406 | if (!t.number) { |
| 407 | if (auto fn = opened_function(t.text)) function = *fn; |
| 408 | } else if (unit_scale(function)) t.value = (t.value - 1) * factor + 1; |
| 409 | else t.value *= factor; |
| 410 | } |
| 411 | return web_render(tokens); |
| 412 | } |
| 413 | |
| 414 | // ── Web Animations timing ── |
| 415 | |
| 416 | struct Computed { |
| 417 | bool before = false, after = false; |
| 418 | std::optional<double> active_time; |
| 419 | double progress = 0; |
| 420 | double iteration = 0; |
| 421 | }; |
| 422 | |
| 423 | std::optional<Computed> compute(const WebAnimation& a, std::optional<double> local_time, bool forwards) { |
| 424 | if (!local_time || !std::isfinite(*local_time)) return std::nullopt; |
| 425 | double local = *local_time; |
| 426 | double active = (a.duration == 0 || a.iterations == 0) ? 0 : a.duration * a.iterations; |
| 427 | double end = std::max(a.delay + active + a.end_delay, 0.0); |
| 428 | double before_active = std::max(std::min(a.delay, end), 0.0); |
| 429 | double active_after = std::max(std::min(a.delay + active, end), 0.0); |
| 430 | bool fills_backwards = a.fill == "backwards" || a.fill == "both"; |
| 431 | bool fills_forwards = a.fill == "forwards" || a.fill == "both"; |
| 432 | Computed r; |
| 433 | if (local < before_active || (!forwards && local == before_active)) r.before = true; |
| 434 | else if (local > active_after || (forwards && local == active_after)) r.after = true; |
| 435 | if (r.before) r.active_time = fills_backwards ? std::optional<double>(std::max(local - a.delay, 0.0)) : std::nullopt; |
| 436 | else if (r.after) r.active_time = fills_forwards ? std::optional<double>(std::max(std::min(local - a.delay, active), 0.0)) : std |
| 437 | else r.active_time = local - a.delay; |
| 438 | if (!r.active_time) return r; |
| 439 | double active_time = *r.active_time; |
| 440 | double overall = a.duration == 0 ? (r.before ? 0 : a.iterations) : active_time / a.duration; |
| 441 | overall += a.iteration_start; |
| 442 | double simple = std::isinf(overall) ? std::fmod(a.iteration_start, 1.0) : std::fmod(overall, 1.0); |
| 443 | if (simple == 0 && !r.before && active_time == active && a.iterations != 0) simple = 1; |
| 444 | double iteration; |
| 445 | if (r.after && std::isinf(a.iterations)) iteration = INF; |
| 446 | else if (simple == 1) iteration = std::floor(overall) - 1; |
| 447 | else iteration = std::floor(overall); |
| 448 | r.iteration = iteration; |
| 449 | bool forwards_direction = true; |
| 450 | if (a.direction == "reverse") forwards_direction = false; |
| 451 | else if ((a.direction == "alternate" || a.direction == "alternate-reverse") && std::isfinite(iteration)) { |
| 452 | double d = iteration + (a.direction == "alternate-reverse" ? 1 : 0); |
| 453 | forwards_direction = std::fmod(d, 2.0) == 0; |
| 454 | } |
| 455 | double directed = forwards_direction ? simple : 1 - simple; |
| 456 | bool before_flag = (forwards_direction && r.before) || (!forwards_direction && r.after); |
| 457 | r.progress = a.easing.web(directed, before_flag); |
| 458 | return r; |
| 459 | } |
| 460 | |
| 461 | std::optional<double> local_time(const WebAnimation& a, double now) { |
| 462 | if (a.hold_ms) return *a.hold_ms; |
| 463 | if (!a.start_ms) return std::nullopt; |
| 464 | return (now * 1000 - *a.start_ms) * a.rate; |
| 465 | } |
| 466 | |
| 467 | std::optional<std::string> web_value(const WebAnimation& a, const std::string& property, double progress, double |
| 468 | const std::function<std::string(const std::string&)>& underlying) { |
| 469 | struct F { |
| 470 | double offset; |
| 471 | const std::string* value; |
| 472 | const Timing* easing; |
| 473 | std::string composite; |
| 474 | }; |
| 475 | static const Timing LINEAR; |
| 476 | std::vector<F> frames; |
| 477 | for (const auto& frame : a.frames) { |
| 478 | if (const std::string* v = last_value(frame.values, property)) |
| 479 | frames.push_back({frame.offset, v, &frame.easing, frame.composite.empty() ? a.composite : frame.composite}); |
| 480 | } |
| 481 | if (frames.empty()) return std::nullopt; |
| 482 | if (std::none_of(frames.begin(), frames.end(), [](const F& f) { return f.offset == 0; })) frames.insert(frames.begin(), {0, |
| 483 | if (std::none_of(frames.begin(), frames.end(), [](const F& f) { return f.offset == 1; })) frames.push_back({1, nullptr, |
| 484 | std::string base = underlying(property); |
| 485 | const std::string* last = nullptr; |
| 486 | for (auto it = frames.rbegin(); it != frames.rend(); ++it) |
| 487 | if (it->offset == 1) { last = it->value; break; } |
| 488 | auto resolve = [&](size_t index) -> std::string { |
| 489 | const F& frame = frames[index]; |
| 490 | if (!frame.value) return base; |
| 491 | std::string value = *frame.value; |
| 492 | if (a.iteration_composite == "accumulate" && iteration > 0 && std::isfinite(iteration) && last) |
| 493 | value = web_add(web_scaled(*last, iteration), value, property, true); |
| 494 | if (frame.composite == "add") return web_add(base, value, property, false); |
| 495 | if (frame.composite == "accumulate") return web_add(base, value, property, true); |
| 496 | return value; |
| 497 | }; |
| 498 | std::vector<size_t> zeros, ones; |
| 499 | for (size_t i = 0; i < frames.size(); i++) { |
| 500 | if (frames[i].offset == 0) zeros.push_back(i); |
| 501 | if (frames[i].offset == 1) ones.push_back(i); |
| 502 | } |
| 503 | if (progress < 0 && zeros.size() > 1) return resolve(zeros.front()); |
| 504 | if (progress >= 1 && ones.size() > 1) return resolve(ones.back()); |
| 505 | size_t start = 0; |
| 506 | if (progress < 0) start = 0; |
| 507 | else if (progress >= 1) start = frames.size() - 2; |
| 508 | else { |
| 509 | for (size_t i = 0; i < frames.size(); i++) |
| 510 | if (frames[i].offset <= progress && frames[i].offset < 1) start = i; |
| 511 | } |
| 512 | size_t end = std::min(start + 1, frames.size() - 1); |
| 513 | if (start == end) return resolve(start); |
| 514 | const F &fa = frames[start], &fb = frames[end]; |
| 515 | double span = fb.offset - fa.offset; |
| 516 | double local = span == 0 ? 0 : (progress - fa.offset) / span; |
| 517 | return interpolate(resolve(start), resolve(end), fa.easing->web(local, false)); |
| 518 | } |
| 519 | |
| 520 | } // namespace |
| 521 | |
| 522 | // ───────────────────────── Timing ───────────────────────── |
| 523 | |
| 524 | Timing Timing::ease() { |
| 525 | Timing t; |
| 526 | t.kind = Bezier; |
| 527 | t.x1 = 0.25; t.y1 = 0.1; t.x2 = 0.25; t.y2 = 1; |
| 528 | t.text = "ease"; |
| 529 | return t; |
| 530 | } |
| 531 | |
| 532 | std::optional<Timing> Timing::parse(std::string_view raw) { |
| 533 | std::string t = css::lower(css::trim(raw)); |
| 534 | Timing out; |
| 535 | out.text = t; |
| 536 | auto bezier = [&](double a, double b, double c, double d) { |
| 537 | out.kind = Bezier; |
| 538 | out.x1 = a; out.y1 = b; out.x2 = c; out.y2 = d; |
| 539 | return out; |
| 540 | }; |
| 541 | if (t == "linear") { out.kind = Linear; return out; } |
| 542 | if (t == "ease") return bezier(0.25, 0.1, 0.25, 1); |
| 543 | if (t == "ease-in") return bezier(0.42, 0, 1, 1); |
| 544 | if (t == "ease-out") return bezier(0, 0, 0.58, 1); |
| 545 | if (t == "ease-in-out") return bezier(0.42, 0, 0.58, 1); |
| 546 | if (t == "step-start" || t == "step-end") { |
| 547 | out.kind = Steps; |
| 548 | out.steps = 1; |
| 549 | out.jump = t == "step-start" ? JumpStart : JumpEnd; |
| 550 | return out; |
| 551 | } |
| 552 | if (css::starts_with(t, "cubic-bezier(") && css::ends_with(t, ")")) { |
| 553 | auto parts = css::split_top_level(std::string_view(t).substr(13, t.size() - 14), ','); |
| 554 | if (parts.size() != 4) return std::nullopt; |
| 555 | double v[4]; |
| 556 | for (int i = 0; i < 4; i++) { |
| 557 | auto n = css::number(parts[i]); |
| 558 | if (!n) return std::nullopt; |
| 559 | v[i] = *n; |
| 560 | } |
| 561 | return bezier(v[0], v[1], v[2], v[3]); |
| 562 | } |
| 563 | if (css::starts_with(t, "steps(") && css::ends_with(t, ")")) { |
| 564 | auto parts = css::split_top_level(std::string_view(t).substr(6, t.size() - 7), ','); |
| 565 | if (parts.empty() || parts.size() > 2) return std::nullopt; |
| 566 | auto n = css::number(parts[0]); |
| 567 | if (!n || *n < 1 || *n != std::floor(*n) || *n > |
| 568 | std::string position = parts.size() > 1 ? css::trim(parts[1]) : "end"; |
| 569 | out.kind = Steps; |
| 570 | out.steps = int(*n); |
| 571 | if (position == "start" || position == "jump-start") out.jump = JumpStart; |
| 572 | else if (position == "end" || position == "jump-end") out.jump = JumpEnd; |
| 573 | else if (position == "jump-both") out.jump = JumpBoth; |
| 574 | else if (position == "jump-none") out.jump = JumpNone; |
| 575 | else return std::nullopt; |
| 576 | return out; |
| 577 | } |
| 578 | if (css::starts_with(t, "linear(") && css::ends_with(t, ")")) { |
| 579 | auto f = linear_function(std::string_view(t).substr(7, t.size() - 8)); |
| 580 | if (f) f->text = t; |
| 581 | return f; |
| 582 | } |
| 583 | return std::nullopt; |
| 584 | } |
| 585 | |
| 586 | double Timing::css(double x) const { |
| 587 | switch (kind) { |
| 588 | case Linear: return x; |
| 589 | case Bezier: return bezier_at(x1, y1, x2, y2, x); |
| 590 | case Steps: { |
| 591 | double n = steps; |
| 592 | double step = jump == JumpStart ? std::ceil(x * n) : std::floor(x * n); |
| 593 | return std::clamp(step / n, 0.0, 1.0); |
| 594 | } |
| 595 | case Points: { |
| 596 | const auto& p = points; |
| 597 | auto segment = [&](size_t a, size_t b) { |
| 598 | if (p[b].first == p[a].first) return x <= p[a].first ? p[a].second : p[b].second; |
| 599 | return p[a].second + (p[b].second - p[a].second) * (x - p[a].first) / (p[b].first - p[a].first); |
| 600 | }; |
| 601 | if (x <= p[0].first) return p[1].first == p[0].first ? p[0].second : segment(0, 1); |
| 602 | for (size_t k = 1; k < p.size(); k++) { |
| 603 | if (x <= p[k].first) return p[k].first == p[k - 1].first ? p[k].second : segment(k - 1, k); |
| 604 | } |
| 605 | size_t n = p.size(); |
| 606 | return p[n - 1].first == p[n - 2].first ? p[n - 1].second : segment(n - 2, n - 1); |
| 607 | } |
| 608 | } |
| 609 | return x; |
| 610 | } |
| 611 | |
| 612 | double Timing::web(double x, bool before) const { |
| 613 | if (kind == Steps) { |
| 614 | double n = steps; |
| 615 | double step = std::floor(x * n); |
| 616 | if (jump == JumpStart || jump == JumpBoth) step += 1; |
| 617 | if (before && std::fmod(x * n, 1.0) == 0) step -= 1; |
| 618 | if (x >= 0 && step < 0) step = 0; |
| 619 | double jumps = jump == JumpBoth ? n + 1 : jump == JumpNone ? n - 1 : n; |
| 620 | if (x <= 1 && step > jumps) step = jumps; |
| 621 | return step / jumps; |
| 622 | } |
| 623 | if (kind == Bezier) { |
| 624 | // Outside [0, 1] a cubic-bézier continues along its end tangents. |
| 625 | if (x < 0) { |
| 626 | double slope = x1 > 0 ? y1 / x1 : (y1 == 0 && x2 > 0 ? y2 / x2 : |
| 627 | return slope * x; |
| 628 | } |
| 629 | if (x > 1) { |
| 630 | double slope = x2 < 1 ? (y2 - 1) / (x2 - 1) : (y2 == 1 && x1 < |
| 631 | return 1 + slope * (x - 1); |
| 632 | } |
| 633 | } |
| 634 | return css(x); |
| 635 | } |
| 636 | |
| 637 | // ───────────────────────── keyframes and specs ───────────────────────── |
| 638 | |
| 639 | void parse_keyframes(std::string_view css_text, KeyframeRules& rules) { |
| 640 | size_t pos = 0; |
| 641 | for (;;) { |
| 642 | size_t at = std::string_view::npos; |
| 643 | for (size_t i = pos; i + 9 <= css_text.size(); i++) { |
| 644 | if (css::iequals(css_text.substr(i, 9), "keyframes")) { at = i; break; } |
| 645 | } |
| 646 | if (at == std::string_view::npos) return; |
| 647 | std::string_view before = css_text.substr(0, at); |
| 648 | size_t open = css_text.find('{', at + 9); |
| 649 | if (!(css::ends_with(before, "@") || css::ends_with(before, "@-webkit-")) || open == std::string_view::npos) { |
| 650 | pos = at + 9; |
| 651 | continue; |
| 652 | } |
| 653 | std::string name = css::trim(css_text.substr(at + 9, open - at - 9)); |
| 654 | while (!name.empty() && (name.front() == '"' || name.front() == '\'')) name.erase(name.begin()); |
| 655 | while (!name.empty() && (name.back() == '"' || name.back() == '\'')) name.pop_back(); |
| 656 | int depth = 0; |
| 657 | size_t close = std::string_view::npos; |
| 658 | for (size_t i = open; i < css_text.size(); i++) { |
| 659 | if (css_text[i] == '{') depth++; |
| 660 | else if (css_text[i] == '}' && --depth == 0) { close = i; break; } |
| 661 | } |
| 662 | if (close == std::string_view::npos) return; |
| 663 | std::string_view body = css_text.substr(open + 1, close - open - 1); |
| 664 | std::vector<Keyframe> frames; |
| 665 | size_t p = 0; |
| 666 | for (;;) { |
| 667 | size_t fo = body.find('{', p); |
| 668 | if (fo == std::string_view::npos) break; |
| 669 | size_t fc = body.find('}', fo); |
| 670 | if (fc == std::string_view::npos) break; |
| 671 | StyleValues declarations; |
| 672 | std::optional<Timing> timing; |
| 673 | for (const auto& d : css::parse_declarations(body.substr(fo + 1, fc - fo - 1))) { |
| 674 | if (d.name == "animation-timing-function") timing = Timing::parse(d.value); |
| 675 | else declarations.emplace_back(d.name, d.value); |
| 676 | } |
| 677 | for (const std::string& raw : css::split_top_level(body.substr(p, fo - p), ',')) { |
| 678 | std::string selector = css::lower(css::trim(raw)); |
| 679 | std::optional<double> offset; |
| 680 | if (selector == "from") offset = 0; |
| 681 | else if (selector == "to") offset = 1; |
| 682 | else if (css::ends_with(selector, "%")) { |
| 683 | if (auto v = css::number(std::string_view(selector).substr(0, selector.size() - 1))) offset = *v / |
| 684 | } |
| 685 | if (offset) frames.push_back(Keyframe{*offset, declarations, timing}); |
| 686 | } |
| 687 | p = fc + 1; |
| 688 | } |
| 689 | std::stable_sort(frames.begin(), frames.end(), [](const Keyframe& a, const Keyframe& b) { return a.offset < b.offset; }); |
| 690 | rules[name] = std::move(frames); |
| 691 | pos = close + 1; |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | Timing AnimationSpec::timing() const { |
| 696 | auto t = Timing::parse(timing_text); |
| 697 | return t ? *t : Timing::ease(); |
| 698 | } |
| 699 | |
| 700 | std::vector<AnimationSpec> AnimationSpec::list(const Declared& declarations) { |
| 701 | std::vector<AnimationSpec> specs; |
| 702 | if (auto it = declarations.find("animation"); it != declarations.end()) { |
| 703 | for (const std::string& item : css::split_top_level(it->second, ',')) { |
| 704 | AnimationSpec spec; |
| 705 | bool saw_duration = false; |
| 706 | for (const std::string& token : css::split_top_level(css::trim(item), ' ')) { |
| 707 | if (token.empty()) continue; |
| 708 | std::string t = css::lower(token); |
| 709 | if (auto time = css::parse_time(t)) { |
| 710 | if (saw_duration) spec.delay = *time; |
| 711 | else { spec.duration = *time; saw_duration = true; } |
| 712 | } else if (Timing::parse(t)) spec.timing_text = t; |
| 713 | else if (t == "infinite") spec.iterations = INF; |
| 714 | else if (auto n = css::number(t)) spec.iterations = *n; |
| 715 | else if (t == "normal" || t == "reverse" || t == "alternate" || t == "alternate-reverse") spec.direction = t; |
| 716 | else if (t == "forwards" || t == "backwards" || t == "both") spec.fill = t; |
| 717 | else if (t == "paused" || t == "running") spec.paused = t == "paused"; |
| 718 | else spec.name = token; |
| 719 | } |
| 720 | specs.push_back(std::move(spec)); |
| 721 | } |
| 722 | } |
| 723 | auto longhand = [&](const char* key, auto apply) { |
| 724 | auto it = declarations.find(key); |
| 725 | if (it == declarations.end()) return; |
| 726 | std::vector<std::string> items; |
| 727 | for (const std::string& s : css::split_top_level(it->second, ',')) items.push_back(css::trim(s)); |
| 728 | if (items.empty()) return; |
| 729 | if (specs.empty()) specs.resize(items.size()); |
| 730 | for (size_t i = 0; i < specs.size(); i++) apply(specs[i], items[i % items.size()]); |
| 731 | }; |
| 732 | longhand("animation-name", [](AnimationSpec& s, const std::string& v) { s.name = v; }); |
| 733 | longhand("animation-duration", [](AnimationSpec& s, const std::string& v) { s.duration = css::parse_time(v).value_or(0); }); |
| 734 | longhand("animation-timing-function", [](AnimationSpec& s, const std::string& v) { s.timing_text = v; }); |
| 735 | longhand("animation-delay", [](AnimationSpec& s, const std::string& v) { s.delay = css::parse_time(v).value_or(0); }); |
| 736 | longhand("animation-iteration-count", [](AnimationSpec& s, const std::string& v) { s.iterations = v == "infinite" ? INF : css |
| 737 | longhand("animation-direction", [](AnimationSpec& s, const std::string& v) { s.direction = v; }); |
| 738 | longhand("animation-fill-mode", [](AnimationSpec& s, const std::string& v) { s.fill = v; }); |
| 739 | longhand("animation-play-state", [](AnimationSpec& s, const std::string& v) { s.paused = v == "paused"; }); |
| 740 | specs.erase(std::remove_if(specs.begin(), specs.end(), [](const AnimationSpec& s) { return s.name == "none" || s.name.empty(); }), specs.end()); |
| 741 | return specs; |
| 742 | } |
| 743 | |
| 744 | std::vector<TransitionSpec> TransitionSpec::list(const Declared& declarations) { |
| 745 | std::vector<TransitionSpec> specs; |
| 746 | if (auto it = declarations.find("transition"); it != declarations.end()) { |
| 747 | for (const std::string& item : css::split_top_level(it->second, ',')) { |
| 748 | TransitionSpec spec; |
| 749 | spec.property = "all"; |
| 750 | bool saw_duration = false; |
| 751 | for (const std::string& token : css::split_top_level(css::trim(item), ' ')) { |
| 752 | if (token.empty()) continue; |
| 753 | if (auto time = css::parse_time(token)) { |
| 754 | if (saw_duration) spec.delay = *time; |
| 755 | else { spec.duration = *time; saw_duration = true; } |
| 756 | } else if (auto timing = Timing::parse(token)) spec.timing = *timing; |
| 757 | else spec.property = css::lower(token); |
| 758 | } |
| 759 | specs.push_back(std::move(spec)); |
| 760 | } |
| 761 | } |
| 762 | auto items = [&](const char* key) { |
| 763 | std::vector<std::string> out; |
| 764 | if (auto it = declarations.find(key); it != declarations.end()) |
| 765 | for (const std::string& s : css::split_top_level(it->second, ',')) out.push_back(css::trim(s)); |
| 766 | return out; |
| 767 | }; |
| 768 | auto properties = items("transition-property"); |
| 769 | auto durations = items("transition-duration"); |
| 770 | if (!properties.empty()) { |
| 771 | auto timings = items("transition-timing-function"); |
| 772 | auto delays = items("transition-delay"); |
| 773 | std::vector<TransitionSpec> next; |
| 774 | for (size_t i = 0; i < properties.size(); i++) { |
| 775 | TransitionSpec base = i < specs.size() ? specs[i] : TransitionSpec{properties[i], 0, Timing::ease(), 0}; |
| 776 | TransitionSpec s; |
| 777 | s.property = css::lower(properties[i]); |
| 778 | s.duration = durations.empty() ? base.duration : css::parse_time(durations[i % durations.size()]).value_or(0); |
| 779 | s.timing = timings.empty() ? base.timing : Timing::parse(timings[i % timings.size()]).value_or(Timing::ease()); |
| 780 | s.delay = delays.empty() ? base.delay : css::parse_time(delays[i % delays.size()]).value_or(0); |
| 781 | next.push_back(std::move(s)); |
| 782 | } |
| 783 | specs = std::move(next); |
| 784 | } else if (!durations.empty()) { |
| 785 | for (size_t i = 0; i < specs.size(); i++) specs[i].duration = css::parse_time(durations[i % durations.size()]).value_or(0); |
| 786 | } |
| 787 | specs.erase(std::remove_if(specs.begin(), specs.end(), [](const TransitionSpec& s) { return s.duration <= 0 || s.property == "none"; }), specs. |
| 788 | return specs; |
| 789 | } |
| 790 | |
| 791 | // ───────────────────────── interpolation ───────────────────────── |
| 792 | |
| 793 | std::string interpolate(const std::string& a, const std::string& b, double t) { |
| 794 | if (t == 0 || !std::isfinite(t)) return a; |
| 795 | if (t == 1) return b; |
| 796 | auto flip = [&] { return t < 0.5 ? a : b; }; |
| 797 | auto pair = pair_tokens(a, b); |
| 798 | if (!pair) return flip(); |
| 799 | std::string out; |
| 800 | const auto& [left, right] = *pair; |
| 801 | for (size_t i = 0; i < left.size(); i++) { |
| 802 | const Token &x = left[i], &y = right[i]; |
| 803 | if (x.number && y.number && (x.text == y.text || x.value == 0 || y.value == 0)) { |
| 804 | out += css::format_number(x.value + (y.value - x.value) * t); |
| 805 | out += x.text.empty() ? y.text : x.text; |
| 806 | } else if (!x.number && !y.number && x.text == y.text) { |
| 807 | out += x.text; |
| 808 | } else { |
| 809 | // Mixed units or different functions: two translation lists still compose by weight. |
| 810 | if (translation_list(a) && translation_list(b)) return scaled_tokens(css::trim(a), 1 - t) + " " + scaled_tokens(css |
| 811 | return flip(); |
| 812 | } |
| 813 | } |
| 814 | return out; |
| 815 | } |
| 816 | |
| 817 | // ───────────────────────── Web Animations records ───────────────────────── |
| 818 | |
| 819 | std::optional<WebAnimation> WebAnimation::parse(const Json& o, double clock_offset_ms) { |
| 820 | constexpr double MAX_MS = 86400.0 * 1000; |
| 821 | constexpr size_t MAX_KEYFRAMES = 64, MAX_VALUES = 64; |
| 822 | const Json* aid = o.find("aid"); |
| 823 | const Json* target = o.find("target"); |
| 824 | const Json* frames = o.find("keyframes"); |
| 825 | if (!aid || !aid->isNumber() || !target || !target->isNumber() || !frames || !frames->isArray() |
| 826 | WebAnimation a; |
| 827 | a.aid = int64_t(aid->asNumber()); |
| 828 | a.target = int64_t(target->asNumber()); |
| 829 | const Json& timing = o["timing"]; |
| 830 | auto ms = [&](const char* key, double fallback) -> std::optional<double> { |
| 831 | const Json* v = timing.find(key); |
| 832 | if (!v || v->isNull()) return fallback; |
| 833 | if (!v->isNumber() || !std::isfinite(v->asNumber()) || std::fabs(v->asNumber()) > MAX_MS) return std::nullopt; |
| 834 | return v->asNumber(); |
| 835 | }; |
| 836 | auto duration = ms("duration", 0), delay = ms("delay", 0), end_delay = ms("endDelay", 0); |
| 837 | if (!duration || *duration < 0 || !delay || !end_delay) return std::nullopt; |
| 838 | a.duration = *duration; |
| 839 | a.delay = *delay; |
| 840 | a.end_delay = *end_delay; |
| 841 | if (const Json* it = timing.find("iterations")) { |
| 842 | if (it->isNull()) a.iterations = INF; |
| 843 | else if (!it->isNumber() || it->asNumber() < 0 || it->asNumber() > 1e9) return std::nullopt; |
| 844 | else a.iterations = it->asNumber(); |
| 845 | } |
| 846 | if (const Json* start = timing.find("iterationStart"); start && start->isNumber()) { |
| 847 | if (start->asNumber() < 0 || start->asNumber() > 1e9) return std::nullopt; |
| 848 | a.iteration_start = start->asNumber(); |
| 849 | } |
| 850 | std::string direction = timing["direction"].isString() ? timing["direction"].asString() : "normal"; |
| 851 | std::string fill = timing["fill"].isString() ? timing["fill"].asString() : "none"; |
| 852 | if (direction != "normal" && direction != "reverse" && direction != "alternate" && direction != "alternate-reverse") return std::nullopt; |
| 853 | if (fill != "none" && fill != "forwards" && fill != "backwards" && fill != "both" && fill != "auto") |
| 854 | a.direction = direction; |
| 855 | a.fill = fill == "auto" ? "none" : fill; |
| 856 | auto parse_easing = [](const Json& v) -> std::optional<Timing> { |
| 857 | std::string text = v.isString() ? v.asString() : "linear"; |
| 858 | if (text.empty() || text.size() > 4096) return std::nullopt; |
| 859 | auto t = Timing::parse(text); |
| 860 | if (!t) return std::nullopt; |
| 861 | // Stricter than CSS: control points stay in x ∈ [0, 1], and linear() is bounded. |
| 862 | if (t->kind == Timing::Bezier && (t->x1 < 0 || t->x1 > 1 || t->x2 < 0 || t->x2 > 1)) |
| 863 | if (t->kind == Timing::Steps && t->jump == Timing::JumpNone && t->steps < 2) return std::nullopt; |
| 864 | if (t->kind == Timing::Points && t->points.size() > 256) return std::nullopt; |
| 865 | return t; |
| 866 | }; |
| 867 | auto easing = parse_easing(timing["easing"]); |
| 868 | if (!easing) return std::nullopt; |
| 869 | a.easing = *easing; |
| 870 | double previous = 0; |
| 871 | for (const Json& raw : frames->arr()) { |
| 872 | const Json* offset = raw.find("offset"); |
| 873 | if (!offset || !offset->isNumber() || offset->asNumber() < previous || offset->asNumber() > 1) return std::nullopt; |
| 874 | auto frame_easing = parse_easing(raw["easing"]); |
| 875 | if (!frame_easing) return std::nullopt; |
| 876 | previous = offset->asNumber(); |
| 877 | Frame f; |
| 878 | f.offset = previous; |
| 879 | f.easing = *frame_easing; |
| 880 | if (const Json* c = raw.find("composite"); c && c->isString()) { |
| 881 | if (c->asString() != "replace" && c->asString() != "add" && c->asString() != "accumulate") return std::nullopt; |
| 882 | f.composite = c->asString(); |
| 883 | } |
| 884 | const auto& values = raw["values"].obj(); |
| 885 | if (values.size() > MAX_VALUES) return std::nullopt; |
| 886 | std::vector<std::pair<std::string, std::string>> sorted; |
| 887 | for (const auto& [name, value] : values) |
| 888 | if (value.isString()) sorted.emplace_back(name, value.asString()); |
| 889 | std::sort(sorted.begin(), sorted.end()); |
| 890 | for (auto& [name, value] : sorted) { |
| 891 | if (std::find(a.properties.begin(), a.properties.end(), name) == a.properties.end()) a.properties.push_back(name); |
| 892 | f.values.emplace_back(std::move(name), std::move(value)); |
| 893 | } |
| 894 | a.frames.push_back(std::move(f)); |
| 895 | } |
| 896 | a.composite = o["composite"].isString() ? o["composite"].asString() : "replace"; |
| 897 | a.iteration_composite = o["iterationComposite"].isString() ? o["iterationComposite"].asString() : "replace"; |
| 898 | if (a.composite != "replace" && a.composite != "add" && a.composite != "accumulate") return std::nullopt; |
| 899 | if (a.iteration_composite != "replace" && a.iteration_composite != "accumulate") return std::nullopt; |
| 900 | if (const Json* s = o.find("startTime"); s && s->isNumber()) { |
| 901 | if (!std::isfinite(s->asNumber())) return std::nullopt; |
| 902 | a.start_ms = s->asNumber() + clock_offset_ms; |
| 903 | } |
| 904 | if (const Json* h = o.find("holdTime"); h && h->isNumber()) { |
| 905 | if (!std::isfinite(h->asNumber()) || std::fabs(h->asNumber()) > 1e12) return std::nullopt; |
| 906 | a.hold_ms = h->asNumber(); |
| 907 | } |
| 908 | a.rate = o["playbackRate"].isNumber() ? o["playbackRate"].asNumber() : 1; |
| 909 | if (!std::isfinite(a.rate) || std::fabs(a.rate) > 1000 || (!a.start_ms && !a.hold_ms)) return std::nullopt; |
| 910 | return a; |
| 911 | } |
| 912 | |
| 913 | // ───────────────────────── Animator ───────────────────────── |
| 914 | |
| 915 | const std::vector<std::string>& Animator::watched() { |
| 916 | static const std::vector<std::string> names = { |
| 917 | "animation", "animation-name", "animation-duration", "animation-timing-function", "animation-delay", "animation-iteration-count", |
| 918 | "animation-direction", "animation-fill-mode", "animation-play-state", "transition", "transition-property", "transition-duration", |
| 919 | "transition-timing-function", "transition-delay", "transform", "opacity", "color", "background-color", "background", "width", "height", |
| 920 | "top", "left", "right", "bottom", "box-shadow", "border-color", "max-height", "stroke-dashoffset", "fill", "stroke", "translate", |
| 921 | "scale", "rotate", "filter", "letter-spacing", "font-size", "margin-top", "margin-left", "flex-grow", "transform-origin", |
| 922 | "backdrop-filter", |
| 923 | }; |
| 924 | return names; |
| 925 | } |
| 926 | |
| 927 | const std::vector<std::string>& Animator::entry_properties() { |
| 928 | static const std::vector<std::string> names = {"animation", "animation-name", "transition", "transition-property", "backdrop-filter", "filter", "box-shadow"}; |
| 929 | return names; |
| 930 | } |
| 931 | |
| 932 | void Animator::set_style_sheets(const std::vector<std::string>& texts) { |
| 933 | KeyframeRules rules; |
| 934 | for (const std::string& text : texts) parse_keyframes(text, rules); |
| 935 | keyframes_ = std::move(rules); |
| 936 | } |
| 937 | |
| 938 | std::string Animator::underlying_value(int64_t id, const std::string& property) const { |
| 939 | if (auto b = bases_.find(id); b != bases_.end()) |
| 940 | if (auto v = b->second.find(property); v != b->second.end()) return v->second; |
| 941 | if (auto u = underlying.find(id); u != underlying.end()) |
| 942 | if (auto v = u->second.find(property); v != u->second.end()) return v->second; |
| 943 | if (const std::string* initial = initial_value(property)) return *initial; |
| 944 | return {}; |
| 945 | } |
| 946 | |
| 947 | std::optional<std::string> Animator::transition_value(int64_t id, const std::string& property, double now) const { |
| 948 | auto list = transitions_.find(id); |
| 949 | if (list == transitions_.end()) return std::nullopt; |
| 950 | auto it = list->second.find(property); |
| 951 | if (it == list->second.end()) return std::nullopt; |
| 952 | const Transition& t = it->second; |
| 953 | double elapsed = now - t.start - t.spec.delay; |
| 954 | if (elapsed <= 0) return t.from; |
| 955 | double progress = std::min(1.0, elapsed / t.spec.duration); |
| 956 | return interpolate(t.from, t.to, t.spec.timing.css(progress)); |
| 957 | } |
| 958 | |
| 959 | void Animator::update(const std::unordered_map<int64_t, Declared>& declarations, double now) { |
| 960 | std::unordered_map<int64_t, std::vector<Running>> next_running; |
| 961 | for (const auto& [id, values] : declarations) { |
| 962 | auto specs = AnimationSpec::list(values); |
| 963 | if (!specs.empty()) { |
| 964 | const auto& previous = running_[id]; |
| 965 | auto& next = next_running[id]; |
| 966 | for (auto& spec : specs) { |
| 967 | auto existing = std::find_if(previous.begin(), previous.end(), [&](const Running& r) { return r.spec.name == spec.name; }); |
| 968 | if (existing != previous.end()) { |
| 969 | if (existing->spec == spec) next.push_back(*existing); |
| 970 | else next.push_back(Running{spec, existing->start, existing->iteration, false}); |
| 971 | continue; |
| 972 | } |
| 973 | if (keyframes_.count(spec.name)) events_.push_back({"animationstart", id, spec.name, 0}); |
| 974 | next.push_back(Running{spec, now, 0, false}); |
| 975 | } |
| 976 | } |
| 977 | auto transition_specs = TransitionSpec::list(values); |
| 978 | bool known = bases_.count(id) != 0; |
| 979 | Declared base = known ? bases_[id] : Declared{}; |
| 980 | for (const std::string& property : watched()) { |
| 981 | if (css::starts_with(property, "animation") || css::starts_with(property, "transition")) continue; |
| 982 | auto nv = values.find(property); |
| 983 | const std::string* new_value = nv == values.end() ? nullptr : &nv->second; |
| 984 | std::optional<std::string> old_value; |
| 985 | if (auto ov = base.find(property); ov != base.end()) old_value = ov->second; |
| 986 | // A transition from unset starts at the property's initial value. |
| 987 | else if (known && new_value) { |
| 988 | if (const std::string* initial = initial_value(property)) old_value = *initial; |
| 989 | } |
| 990 | if (old_value && new_value && *old_value != *new_value) { |
| 991 | auto spec = std::find_if(transition_specs.rbegin(), transition_specs.rend(), [&](const TransitionSpec& s) { return s.property == property || s.property == |
| 992 | if (spec == transition_specs.rend()) { |
| 993 | if (auto t = transitions_.find(id); t != transitions_.end()) t->second.erase(property); |
| 994 | } else { |
| 995 | std::string current = transition_value(id, property, now).value_or(*old_value); |
| 996 | transitions_[id][property] = Transition{std::move(current), *new_value, now, *spec}; |
| 997 | } |
| 998 | } else if (!new_value) { |
| 999 | if (auto t = transitions_.find(id); t != transitions_.end()) t->second.erase(property); |
| 1000 | } |
| 1001 | if (new_value) base[property] = *new_value; |
| 1002 | else base.erase(property); |
| 1003 | } |
| 1004 | bases_[id] = std::move(base); |
| 1005 | if (auto t = transitions_.find(id); t != transitions_.end() && t->second.empty()) transitions_.erase(t); |
| 1006 | } |
| 1007 | for (auto it = bases_.begin(); it != bases_.end();) { |
| 1008 | if (!declarations.count(it->first)) { |
| 1009 | transitions_.erase(it->first); |
| 1010 | it = bases_.erase(it); |
| 1011 | } else ++it; |
| 1012 | } |
| 1013 | running_ = std::move(next_running); |
| 1014 | prune_overrides(); |
| 1015 | } |
| 1016 | |
| 1017 | StyleValues Animator::values(const std::vector<Keyframe>& frames, const Declared& base, double progress, const |
| 1018 | std::vector<std::string> properties; |
| 1019 | for (const auto& f : frames) |
| 1020 | for (const auto& [name, value] : f.declarations) |
| 1021 | if (std::find(properties.begin(), properties.end(), name) == properties.end()) properties.push_back(name); |
| 1022 | StyleValues result; |
| 1023 | Timing spec_timing = spec.timing(); |
| 1024 | for (const std::string& property : properties) { |
| 1025 | struct Stop { |
| 1026 | double offset; |
| 1027 | std::string value; |
| 1028 | const std::optional<Timing>* timing; |
| 1029 | }; |
| 1030 | static const std::optional<Timing> NONE; |
| 1031 | std::vector<Stop> stops; |
| 1032 | for (const auto& f : frames) |
| 1033 | if (const std::string* v = last_value(f.declarations, property)) stops.push_back({f.offset, *v, &f.timing}); |
| 1034 | const std::string* own = nullptr; |
| 1035 | if (auto b = base.find(property); b != base.end()) own = &b->second; |
| 1036 | else own = initial_value(property); |
| 1037 | if (own && !stops.empty()) { |
| 1038 | if (stops.front().offset > 0) stops.insert(stops.begin(), Stop{0, *own, &frames.front().timing}); |
| 1039 | if (stops.back().offset < 1) stops.push_back(Stop{1, *own, &NONE}); |
| 1040 | } |
| 1041 | if (stops.empty()) continue; |
| 1042 | if (progress <= stops.front().offset) { result.emplace_back(property, stops.front().value); continue; } |
| 1043 | if (progress >= stops.back().offset) { result.emplace_back(property, stops.back().value); continue; } |
| 1044 | for (size_t i = 0; i + 1 < stops.size(); i++) { |
| 1045 | const Stop &a = stops[i], &b = stops[i + 1]; |
| 1046 | if (progress >= a.offset && progress <= b.offset) { |
| 1047 | double span = std::max(b.offset - a.offset, 0.000001); |
| 1048 | double local = (progress - a.offset) / span; |
| 1049 | const Timing& timing = a.timing->has_value() ? **a.timing : spec_timing; |
| 1050 | result.emplace_back(property, interpolate(a.value, b.value, timing.css(local))); |
| 1051 | break; |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | return result; |
| 1056 | } |
| 1057 | |
| 1058 | std::optional<StyleValues> Animator::sample_animation(int64_t id, Running& item, const std::vector<Keyframe>& frames, |
| 1059 | const AnimationSpec& spec = item.spec; |
| 1060 | double local = now - item.start - spec.delay; |
| 1061 | if (auto o = overrides_.find(id); o != overrides_.end()) { |
| 1062 | if (auto it = o->second.find("animation:" + spec.name); it != o->second.end()) { |
| 1063 | if (it->second.cancelled) return std::nullopt; |
| 1064 | local = it->second.local(now) - spec.delay; |
| 1065 | } |
| 1066 | } |
| 1067 | static const Declared EMPTY; |
| 1068 | auto b = bases_.find(id); |
| 1069 | const Declared& base = b == bases_.end() ? EMPTY : b->second; |
| 1070 | auto reversed = [&](int iteration) { |
| 1071 | if (spec.direction == "reverse") return true; |
| 1072 | if (spec.direction == "alternate") return iteration % 2 == 1; |
| 1073 | if (spec.direction == "alternate-reverse") return iteration % 2 == 0; |
| 1074 | return false; |
| 1075 | }; |
| 1076 | if (local < 0) { |
| 1077 | if (spec.fill == "backwards" || spec.fill == "both") |
| 1078 | return values(frames, base, css::starts_with(spec.direction, "reverse") || spec.direction == "alternate-reverse" ? 1 : 0, spec); |
| 1079 | return std::nullopt; |
| 1080 | } |
| 1081 | double duration = std::max(spec.duration, 0.0001); |
| 1082 | double total = spec.iterations * duration; |
| 1083 | if (local >= total) { |
| 1084 | if (!item.ended) { |
| 1085 | item.ended = true; |
| 1086 | if (events) events->push_back({"animationend", id, spec.name, total}); |
| 1087 | } |
| 1088 | if (spec.fill == "forwards" || spec.fill == "both") { |
| 1089 | int last_iteration = std::max(0, int(std::ceil(std::min(spec.iterations, 1e9))) - 1); |
| 1090 | double fraction = std::fmod(spec.iterations, 1.0); |
| 1091 | double progress = fraction == 0 ? 1.0 : fraction; |
| 1092 | if (reversed(last_iteration)) progress = 1 - progress; |
| 1093 | return values(frames, base, progress, spec); |
| 1094 | } |
| 1095 | return std::nullopt; |
| 1096 | } |
| 1097 | int iteration = int(std::min(local / duration, 1e9)); |
| 1098 | if (iteration != item.iteration) { |
| 1099 | item.iteration = iteration; |
| 1100 | if (events) events->push_back({"animationiteration", id, spec.name, local}); |
| 1101 | } |
| 1102 | double progress = (local - iteration * duration) / duration; |
| 1103 | if (reversed(iteration)) progress = 1 - progress; |
| 1104 | return values(frames, base, progress, spec); |
| 1105 | } |
| 1106 | |
| 1107 | StyleOverrides Animator::sample(double now) { |
| 1108 | StyleOverrides out; |
| 1109 | for (auto& [id, list] : running_) { |
| 1110 | for (Running& item : list) { |
| 1111 | auto frames = keyframes_.find(item.spec.name); |
| 1112 | if (frames == keyframes_.end() || frames->second.empty()) continue; |
| 1113 | if (auto values = sample_animation(id, item, frames->second, now, &events_)) |
| 1114 | for (auto& [property, value] : *values) merge(out[id], property, std::move(value)); |
| 1115 | } |
| 1116 | } |
| 1117 | for (auto it = transitions_.begin(); it != transitions_.end();) { |
| 1118 | int64_t id = it->first; |
| 1119 | auto& list = it->second; |
| 1120 | for (auto t = list.begin(); t != list.end();) { |
| 1121 | const std::string& property = t->first; |
| 1122 | const Transition& transition = t->second; |
| 1123 | double elapsed = now - transition.start - transition.spec.delay; |
| 1124 | if (auto o = overrides_.find(id); o != overrides_.end()) { |
| 1125 | if (auto ov = o->second.find("transition:" + property); ov != o->second.end()) { |
| 1126 | if (ov->second.cancelled) { t = list.erase(t); continue; } |
| 1127 | elapsed = ov->second.local(now) - transition.spec.delay; |
| 1128 | } |
| 1129 | } |
| 1130 | if (elapsed >= transition.spec.duration) { |
| 1131 | events_.push_back({"transitionend", id, property, transition.spec.duration}); |
| 1132 | t = list.erase(t); |
| 1133 | continue; |
| 1134 | } |
| 1135 | double progress = std::max(0.0, elapsed) / transition.spec.duration; |
| 1136 | merge(out[id], property, elapsed <= 0 ? transition.from : interpolate(transition.from, transition.to, transition.spec.timing.css(progress))); |
| 1137 | ++t; |
| 1138 | } |
| 1139 | it = list.empty() ? transitions_.erase(it) : std::next(it); |
| 1140 | } |
| 1141 | if (!web_.empty()) sample_web(out, now); |
| 1142 | for (auto it = out.begin(); it != out.end();) it = it->second.empty() ? out.erase(it) : std::next(it); |
| 1143 | return out; |
| 1144 | } |
| 1145 | |
| 1146 | void Animator::sample_web(StyleOverrides& out, double now, int64_t only) const { |
| 1147 | // By target, then in aid order: later animations composite onto earlier ones. |
| 1148 | std::map<int64_t, std::vector<const WebAnimation*>> by_target; |
| 1149 | for (const auto& [aid, a] : web_) |
| 1150 | if (!only || a.target == only) by_target[a.target].push_back(&a); |
| 1151 | for (const auto& [id, list] : by_target) { |
| 1152 | for (const WebAnimation* a : list) { |
| 1153 | auto state = compute(*a, local_time(*a, now), a->rate >= 0); |
| 1154 | if (!state || !state->active_time) continue; |
| 1155 | auto underlying_of = [&](const std::string& property) { |
| 1156 | if (auto o = out.find(id); o != out.end()) |
| 1157 | if (const std::string* v = last_value(o->second, property)) return *v; |
| 1158 | return underlying_value(id, property); |
| 1159 | }; |
| 1160 | StyleValues values; |
| 1161 | for (const std::string& property : a->properties) |
| 1162 | if (auto v = web_value(*a, property, state->progress, state->iteration, underlying_of)) values.emplace_back(property, std::move(*v)); |
| 1163 | for (auto& [property, value] : values) merge(out[id], property, std::move(value)); |
| 1164 | } |
| 1165 | } |
| 1166 | } |
| 1167 | |
| 1168 | bool Animator::active(double now) const { |
| 1169 | static const std::unordered_set<int64_t> NONE; |
| 1170 | return active(now, NONE); |
| 1171 | } |
| 1172 | |
| 1173 | bool Animator::active(double now, const std::unordered_set<int64_t>& skip) const { |
| 1174 | for (const auto& [id, list] : transitions_) |
| 1175 | if (!skip.count(id)) return true; |
| 1176 | for (const auto& [aid, a] : web_) { |
| 1177 | if (!a.running() || skip.count(a.target)) continue; |
| 1178 | auto state = compute(a, local_time(a, now), a.rate >= 0); |
| 1179 | if (!state) continue; |
| 1180 | bool pending = a.rate > 0 ? state->before : state->after; |
| 1181 | if ((!state->before && !state->after) || pending) return true; |
| 1182 | } |
| 1183 | for (const auto& [id, list] : running_) { |
| 1184 | if (skip.count(id)) continue; |
| 1185 | for (const Running& r : list) |
| 1186 | if (!r.ended && !r.spec.paused && keyframes_.count(r.spec.name)) return true; |
| 1187 | } |
| 1188 | return false; |
| 1189 | } |
| 1190 | |
| 1191 | const Animator::Override* Animator::override_of(int64_t id, const std::string& key) const { |
| 1192 | auto o = overrides_.find(id); |
| 1193 | if (o == overrides_.end()) return nullptr; |
| 1194 | auto it = o->second.find(key); |
| 1195 | return it == o->second.end() ? nullptr : &it->second; |
| 1196 | } |
| 1197 | |
| 1198 | std::vector<int64_t> Animator::animated_ids(double now) const { |
| 1199 | std::vector<int64_t> out; |
| 1200 | for (const auto& [id, list] : running_) { |
| 1201 | for (const Running& r : list) { |
| 1202 | if (r.ended || !keyframes_.count(r.spec.name)) continue; |
| 1203 | const Override* o = override_of(id, "animation:" + r.spec.name); |
| 1204 | if (o ? o->cancelled || o->hold.has_value() : r.spec.paused) continue; |
| 1205 | out.push_back(id); |
| 1206 | break; |
| 1207 | } |
| 1208 | } |
| 1209 | for (const auto& [id, list] : transitions_) out.push_back(id); |
| 1210 | for (const auto& [aid, a] : web_) { |
| 1211 | if (!a.running()) continue; |
| 1212 | auto state = compute(a, local_time(a, now), a.rate >= 0); |
| 1213 | if (state && !(a.rate > 0 ? state->after : state->before)) out.push_back(a.target); |
| 1214 | } |
| 1215 | std::sort(out.begin(), out.end()); |
| 1216 | out.erase(std::unique(out.begin(), out.end()), out.end()); |
| 1217 | return out; |
| 1218 | } |
| 1219 | |
| 1220 | std::vector<std::string> Animator::animated_properties(int64_t id) const { |
| 1221 | std::vector<std::string> out; |
| 1222 | auto add = [&](const std::string& p) { |
| 1223 | if (std::find(out.begin(), out.end(), p) == out.end()) out.push_back(p); |
| 1224 | }; |
| 1225 | if (auto r = running_.find(id); r != running_.end()) |
| 1226 | for (const Running& item : r->second) |
| 1227 | if (auto frames = keyframes_.find(item.spec.name); frames != keyframes_.end()) |
| 1228 | for (const Keyframe& f : frames->second) |
| 1229 | for (const auto& [property, value] : f.declarations) add(property); |
| 1230 | if (auto t = transitions_.find(id); t != transitions_.end()) |
| 1231 | for (const auto& [property, transition] : t->second) add(property); |
| 1232 | for (const auto& [aid, a] : web_) |
| 1233 | if (a.target == id) |
| 1234 | for (const std::string& p : a.properties) add(p); |
| 1235 | return out; |
| 1236 | } |
| 1237 | |
| 1238 | StyleValues Animator::peek(int64_t id, double t) const { |
| 1239 | StyleOverrides out; |
| 1240 | if (auto r = running_.find(id); r != running_.end()) { |
| 1241 | for (Running item : r->second) { |
| 1242 | auto frames = keyframes_.find(item.spec.name); |
| 1243 | if (frames == keyframes_.end() || frames->second.empty()) continue; |
| 1244 | if (auto values = sample_animation(id, item, frames->second, t, nullptr)) |
| 1245 | for (auto& [property, value] : *values) merge(out[id], property, std::move(value)); |
| 1246 | } |
| 1247 | } |
| 1248 | if (auto list = transitions_.find(id); list != transitions_.end()) { |
| 1249 | for (const auto& [property, transition] : list->second) { |
| 1250 | double elapsed = t - transition.start - transition.spec.delay; |
| 1251 | if (const Override* o = override_of(id, "transition:" + property)) { |
| 1252 | if (o->cancelled) continue; |
| 1253 | elapsed = o->local(t) - transition.spec.delay; |
| 1254 | } |
| 1255 | // An ended transition leaves the declared value, which the element already has. |
| 1256 | if (elapsed >= transition.spec.duration) continue; |
| 1257 | double progress = std::max(0.0, elapsed) / transition.spec.duration; |
| 1258 | merge(out[id], property, elapsed <= 0 ? transition.from : interpolate(transition.from, transition.to, transition.spec.timing.css(progress))); |
| 1259 | } |
| 1260 | } |
| 1261 | if (!web_.empty()) sample_web(out, t, id); |
| 1262 | auto it = out.find(id); |
| 1263 | return it == out.end() ? StyleValues{} : std::move(it->second); |
| 1264 | } |
| 1265 | |
| 1266 | std::optional<Animator::Plan> Animator::plan(int64_t id, double now, bool iterations) const { |
| 1267 | Plan plan; |
| 1268 | double end = INF, loop = 0, wait = INF, next_iteration = INF; |
| 1269 | bool looping = false; |
| 1270 | // An animation's local time runs `rate` times as fast as the clock from `origin`; it begins |
| 1271 | // after `delay` local seconds and repeats every `period` local seconds. |
| 1272 | auto add = [&](double origin, double rate, double delay, double duration, double count, bool alternate) { |
| 1273 | if (rate <= 0 || duration <= 0) return false; |
| 1274 | double begin = origin + delay / rate; |
| 1275 | if (now < begin) { |
| 1276 | wait = std::min(wait, begin); |
| 1277 | return true; |
| 1278 | } |
| 1279 | double iteration = duration / rate; |
| 1280 | if (std::isinf(count)) { |
| 1281 | double period = iteration * (alternate ? 2 : 1); |
| 1282 | if (looping && std::fabs(period - loop) > 1e-6) return false; |
| 1283 | looping = true; |
| 1284 | loop = period; |
| 1285 | } else { |
| 1286 | end = std::min(end, begin + count * iteration); |
| 1287 | } |
| 1288 | double done = std::floor((now - begin) / iteration) + 1; |
| 1289 | if (std::isinf(count) || done < count) next_iteration = std::min(next_iteration, begin + done * iteration); |
| 1290 | return true; |
| 1291 | }; |
| 1292 | |
| 1293 | if (auto r = running_.find(id); r != running_.end()) { |
| 1294 | for (const Running& item : r->second) { |
| 1295 | if (item.ended || !keyframes_.count(item.spec.name)) continue; |
| 1296 | const AnimationSpec& spec = item.spec; |
| 1297 | double origin = item.start, rate = 1; |
| 1298 | if (const Override* o = override_of(id, "animation:" + spec.name)) { |
| 1299 | if (o->cancelled || o->hold) continue; |
| 1300 | origin = *o->start; |
| 1301 | rate = o->rate; |
| 1302 | } else if (spec.paused) continue; |
| 1303 | bool alternate = spec.direction == "alternate" || spec.direction == "alternate-reverse"; |
| 1304 | if (!add(origin, rate, spec.delay, std::max(spec.duration, 0.0001), spec.iterations, alternate)) return std::nullopt; |
| 1305 | } |
| 1306 | } |
| 1307 | if (auto list = transitions_.find(id); list != transitions_.end()) { |
| 1308 | for (const auto& [property, transition] : list->second) { |
| 1309 | double origin = transition.start, rate = 1; |
| 1310 | if (const Override* o = override_of(id, "transition:" + property)) { |
| 1311 | if (o->cancelled || o->hold) continue; |
| 1312 | origin = *o->start; |
| 1313 | rate = o->rate; |
| 1314 | } |
| 1315 | if (!add(origin, rate, transition.spec.delay, transition.spec.duration, 1, false)) return std::nullopt; |
| 1316 | } |
| 1317 | } |
| 1318 | for (const auto& [aid, a] : web_) { |
| 1319 | if (a.target != id || !a.running()) continue; |
| 1320 | if (a.iteration_composite != "replace") return std::nullopt; |
| 1321 | bool alternate = a.direction == "alternate" || a.direction == "alternate-reverse"; |
| 1322 | // Local milliseconds: (now·1000 − start) · rate, so the origin is start / 1000 seconds. |
| 1323 | if (!add(*a.start_ms / 1000, a.rate, a.delay / 1000, a.duration / 1000, a.iterations, alternate)) return std::nullopt; |
| 1324 | } |
| 1325 | |
| 1326 | plan.wake = std::min(wait, end); |
| 1327 | if (iterations) plan.wake = std::min(plan.wake, next_iteration); |
| 1328 | if (wait < INF && end == INF && !looping) { |
| 1329 | plan.ready = false; |
| 1330 | return plan; |
| 1331 | } |
| 1332 | // Something still waiting changes the picture at `wait`: bake only up to there. |
| 1333 | end = std::min(end, wait); |
| 1334 | plan.start = now; |
| 1335 | if (end < INF) { |
| 1336 | plan.duration = end - now; |
| 1337 | } else if (looping) { |
| 1338 | plan.duration = loop; |
| 1339 | plan.repeat = true; |
| 1340 | } else { |
| 1341 | return std::nullopt; |
| 1342 | } |
| 1343 | if (plan.duration <= 0) return std::nullopt; |
| 1344 | return plan; |
| 1345 | } |
| 1346 | |
| 1347 | uint64_t Animator::signature(int64_t id) const { |
| 1348 | std::string s; |
| 1349 | auto num = [&](double v) { |
| 1350 | s += css::format_number(v, 6); |
| 1351 | s.push_back('|'); |
| 1352 | }; |
| 1353 | auto text = [&](const std::string& v) { |
| 1354 | s += v; |
| 1355 | s.push_back('|'); |
| 1356 | }; |
| 1357 | auto control = [&](const std::string& key) { |
| 1358 | if (const Override* o = override_of(id, key)) { |
| 1359 | text(key); |
| 1360 | num(o->origin); |
| 1361 | num(o->start ? *o->start : -1); |
| 1362 | num(o->hold ? *o->hold : -1); |
| 1363 | num(o->rate); |
| 1364 | num(o->cancelled); |
| 1365 | } |
| 1366 | }; |
| 1367 | if (auto r = running_.find(id); r != running_.end()) { |
| 1368 | for (const Running& item : r->second) { |
| 1369 | const AnimationSpec& spec = item.spec; |
| 1370 | text(spec.name); |
| 1371 | num(item.start); |
| 1372 | num(spec.duration); |
| 1373 | text(spec.timing_text); |
| 1374 | num(spec.delay); |
| 1375 | num(spec.iterations); |
| 1376 | text(spec.direction); |
| 1377 | text(spec.fill); |
| 1378 | num(spec.paused); |
| 1379 | num(item.ended); |
| 1380 | control("animation:" + spec.name); |
| 1381 | } |
| 1382 | } |
| 1383 | if (auto list = transitions_.find(id); list != transitions_.end()) { |
| 1384 | for (const auto& [property, transition] : list->second) { |
| 1385 | text(property); |
| 1386 | text(transition.from); |
| 1387 | text(transition.to); |
| 1388 | num(transition.start); |
| 1389 | num(transition.spec.duration); |
| 1390 | num(transition.spec.delay); |
| 1391 | text(transition.spec.timing.text); |
| 1392 | control("transition:" + property); |
| 1393 | } |
| 1394 | } |
| 1395 | for (const auto& [aid, a] : web_) { |
| 1396 | if (a.target != id) continue; |
| 1397 | num(double(aid)); |
| 1398 | num(a.start_ms ? *a.start_ms : -1); |
| 1399 | num(a.hold_ms ? *a.hold_ms : -1); |
| 1400 | num(a.rate); |
| 1401 | num(a.duration); |
| 1402 | num(a.delay); |
| 1403 | num(a.iterations); |
| 1404 | text(a.direction); |
| 1405 | text(a.fill); |
| 1406 | text(a.easing.text); |
| 1407 | text(a.composite); |
| 1408 | for (const auto& frame : a.frames) { |
| 1409 | num(frame.offset); |
| 1410 | text(frame.easing.text); |
| 1411 | for (const auto& [property, value] : frame.values) { |
| 1412 | text(property); |
| 1413 | text(value); |
| 1414 | } |
| 1415 | } |
| 1416 | } |
| 1417 | for (const char* property : {"transform", "opacity", "translate", "rotate", "scale", "transform-origin"}) text(base_value(id, property)); |
| 1418 | return std::hash<std::string>()(s); |
| 1419 | } |
| 1420 | |
| 1421 | void Animator::apply_web(const Json& message, double clock_offset_ms) { |
| 1422 | constexpr size_t MAX_ANIMATIONS = 1024; |
| 1423 | size_t count = 0; |
| 1424 | for (const Json& item : message["anims"].arr()) { |
| 1425 | if (++count > 4096) break; |
| 1426 | const Json* aid = item.find("aid"); |
| 1427 | if (!aid || !aid->isNumber()) continue; |
| 1428 | if (const Json* css_record = item.find("css"); css_record && css_record->isObject()) { |
| 1429 | const Json* target = item.find("target"); |
| 1430 | const Json* kind = css_record->find("kind"); |
| 1431 | const Json* name = css_record->find("name"); |
| 1432 | const Json* origin = css_record->find("origin"); |
| 1433 | if (!target || !target->isNumber() || !kind || !name || !name->isString() || !origin || |
| 1434 | if (kind->asString() != "animation" && kind->asString() != "transition") continue; |
| 1435 | int64_t id = int64_t(target->asNumber()); |
| 1436 | std::string key = kind->asString() + ":" + name->asString(); |
| 1437 | if (item["remove"].asBool()) { |
| 1438 | if (auto o = overrides_.find(id); o != overrides_.end()) { |
| 1439 | o->second.erase(key); |
| 1440 | if (o->second.empty()) overrides_.erase(o); |
| 1441 | } |
| 1442 | continue; |
| 1443 | } |
| 1444 | double rate = item["playbackRate"].isNumber() ? item["playbackRate"].asNumber() : 1; |
| 1445 | if (!std::isfinite(rate) || std::fabs(rate) > 1000) continue; |
| 1446 | Override o; |
| 1447 | o.origin = origin->asNumber() / 1000; |
| 1448 | o.rate = rate; |
| 1449 | o.cancelled = item["cancelled"].asBool(); |
| 1450 | if (item["startTime"].isNumber()) o.start = (item["startTime"].asNumber() + clock_offset_ms) / 1000; |
| 1451 | if (item["holdTime"].isNumber()) o.hold = item["holdTime"].asNumber() / 1000; |
| 1452 | if (!o.cancelled && !o.start && !o.hold) continue; |
| 1453 | if ((o.start && !std::isfinite(*o.start)) || (o.hold && !std::isfinite(*o.hold))) continue; |
| 1454 | if (!overrides_.count(id) && overrides_.size() >= MAX_ANIMATIONS) continue; |
| 1455 | overrides_[id][key] = o; |
| 1456 | continue; |
| 1457 | } |
| 1458 | int64_t key = int64_t(aid->asNumber()); |
| 1459 | if (item["remove"].asBool()) { |
| 1460 | web_.erase(key); |
| 1461 | continue; |
| 1462 | } |
| 1463 | auto animation = WebAnimation::parse(item, clock_offset_ms); |
| 1464 | if (!animation) { |
| 1465 | web_.erase(key); |
| 1466 | continue; |
| 1467 | } |
| 1468 | if (!web_.count(key) && web_.size() >= MAX_ANIMATIONS) continue; |
| 1469 | web_[key] = std::move(*animation); |
| 1470 | } |
| 1471 | } |
| 1472 | |
| 1473 | std::vector<int64_t> Animator::web_targets() const { |
| 1474 | std::vector<int64_t> out; |
| 1475 | for (const auto& [aid, a] : web_) |
| 1476 | if (std::find(out.begin(), out.end(), a.target) == out.end()) out.push_back(a.target); |
| 1477 | return out; |
| 1478 | } |
| 1479 | |
| 1480 | std::vector<std::string> Animator::web_properties(int64_t id) const { |
| 1481 | std::vector<std::string> out; |
| 1482 | for (const auto& [aid, a] : web_) |
| 1483 | if (a.target == id) |
| 1484 | for (const auto& p : a.properties) |
| 1485 | if (std::find(out.begin(), out.end(), p) == out.end()) out.push_back(p); |
| 1486 | return out; |
| 1487 | } |
| 1488 | |
| 1489 | void Animator::prune(const std::function<bool(int64_t)>& alive) { |
| 1490 | for (auto it = web_.begin(); it != web_.end();) it = alive(it->second.target) ? std::next(it) : web_.erase(it); |
| 1491 | } |
| 1492 | |
| 1493 | void Animator::prune_overrides() { |
| 1494 | for (auto it = overrides_.begin(); it != overrides_.end();) { |
| 1495 | int64_t id = it->first; |
| 1496 | for (auto o = it->second.begin(); o != it->second.end();) { |
| 1497 | const std::string& key = o->first; |
| 1498 | bool alive = false; |
| 1499 | if (css::starts_with(key, "animation:")) { |
| 1500 | std::string name = key.substr(10); |
| 1501 | if (auto r = running_.find(id); r != running_.end()) |
| 1502 | alive = std::any_of(r->second.begin(), r->second.end(), [&](const Running& x) { return x.spec.name == name && std::fabs(x.start |
| 1503 | } else { |
| 1504 | std::string property = key.substr(11); |
| 1505 | alive = o->second.cancelled; |
| 1506 | if (auto t = transitions_.find(id); t != transitions_.end()) |
| 1507 | if (auto p = t->second.find(property); p != t->second.end()) alive = std::fabs(p->second.start - o->second.origin) < 0.002; |
| 1508 | } |
| 1509 | o = alive ? std::next(o) : it->second.erase(o); |
| 1510 | } |
| 1511 | it = it->second.empty() ? overrides_.erase(it) : std::next(it); |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | Json Animator::css_animations(const std::vector<int64_t>& ids, double now) const { |
| 1516 | Json list = Json::array(); |
| 1517 | for (int64_t id : ids) { |
| 1518 | const Override* none = nullptr; |
| 1519 | auto find_override = [&](const std::string& key) -> const Override* { |
| 1520 | auto o = overrides_.find(id); |
| 1521 | if (o == overrides_.end()) return none; |
| 1522 | auto it = o->second.find(key); |
| 1523 | return it == o->second.end() ? none : &it->second; |
| 1524 | }; |
| 1525 | if (auto t = transitions_.find(id); t != transitions_.end()) { |
| 1526 | for (const auto& [property, transition] : t->second) { |
| 1527 | const Override* o = find_override("transition:" + property); |
| 1528 | if (o && o->cancelled) continue; |
| 1529 | Json e = Json::object(); |
| 1530 | e.set("kind", "transition").set("id", double(id)).set("name", property).set("index", 0); |
| 1531 | e.set("origin", transition.start * 1000).set("currentTime", (o ? o->local(now) : now - transition.start) * 1000); |
| 1532 | e.set("playbackRate", o ? o->rate : 1).set("paused", o && o->hold.has_value()); |
| 1533 | e.set("duration", transition.spec.duration * 1000).set("delay", transition.spec.delay * 1000).set("iterations", 1); |
| 1534 | e.set("direction", "normal").set("fill", "backwards").set("easing", transition.spec.timing.text); |
| 1535 | list.push(std::move(e)); |
| 1536 | } |
| 1537 | } |
| 1538 | if (auto r = running_.find(id); r != running_.end()) { |
| 1539 | int index = 0; |
| 1540 | for (const Running& item : r->second) { |
| 1541 | int i = index++; |
| 1542 | if (!keyframes_.count(item.spec.name)) continue; |
| 1543 | const Override* o = find_override("animation:" + item.spec.name); |
| 1544 | if (o && o->cancelled) continue; |
| 1545 | Json e = Json::object(); |
| 1546 | e.set("kind", "animation").set("id", double(id)).set("name", item.spec.name).set("index", i); |
| 1547 | e.set("origin", item.start * 1000).set("currentTime", (o ? o->local(now) : now - item.start) * 1000); |
| 1548 | e.set("playbackRate", o ? o->rate : 1).set("paused", o ? o->hold.has_value() : item.spec.paused); |
| 1549 | e.set("duration", item.spec.duration * 1000).set("delay", item.spec.delay * 1000); |
| 1550 | e.set("direction", item.spec.direction).set("fill", item.spec.fill).set("easing", item.spec.timing_text); |
| 1551 | e.set("iterations", std::isfinite(item.spec.iterations) ? Json(item.spec.iterations) : Json()); |
| 1552 | list.push(std::move(e)); |
| 1553 | } |
| 1554 | } |
| 1555 | } |
| 1556 | return list; |
| 1557 | } |
| 1558 | |
| 1559 | } // namespace twlite |
| 1560 | |