| 1 | #include "renderer.h" |
| 2 | |
| 3 | #include "css.h" |
| 4 | #include "theme.h" |
| 5 | #include "tw_ua_stylesheet.h" |
| 6 | |
| 7 | #include <litehtml.h> |
| 8 | #include <litehtml/html_tag.h> |
| 9 | #include <litehtml/render_item.h> |
| 10 | |
| 11 | #include <algorithm> |
| 12 | #include <chrono> |
| 13 | #include <cmath> |
| 14 | #include <cstring> |
| 15 | #include <functional> |
| 16 | #include <set> |
| 17 | |
| 18 | using twidget::Json; |
| 19 | |
| 20 | namespace twlite { |
| 21 | |
| 22 | namespace { |
| 23 | |
| 24 | constexpr double MIN_HEIGHT = 24.0; |
| 25 | constexpr double MAX_HEIGHT = 900.0; |
| 26 | constexpr int MAX_PASSES = 4; |
| 27 | /// A finger jitters a few px during a tap (see renderer.rs TAP_SLOP): moves inside this radius are not forwarded. |
| 28 | constexpr double TAP_SLOP = 8.0; |
| 29 | const char* const ALWAYS_FORWARD[] = {"click", "input", "change", "submit", "reset", "load", "error", "toggle"}; |
| 30 | |
| 31 | /// Chromium/WebKit UA rules litehtml's master.css lacks and widgets rely on. Form controls get a |
| 32 | /// visible box: litehtml has no controls of its own (the container would own them), so they are |
| 33 | /// bordered inline blocks here, with the value as text where the shadow tree knows it. The profile's |
| 34 | /// UA layer (TW_UA_STYLESHEET, generated from packages/core/profile.json) comes after it: the root and |
| 35 | /// text defaults on the theme variables and the client-styled <button>, as every renderer draws them. |
| 36 | const char* const UA_EXTRA = R"css( |
| 37 | button,input,select,textarea,meter,progress{box-sizing:border-box} |
| 38 | input,select,textarea,button{display:inline-block;border:1px solid #8f8f8f;border-radius:3px;background:#fff;color:#000;padding:2px 6px;font:13.333px -apple-system,system-ui,sans-serif;min-height:1.8em;min-width:2em;vertical-align:middle} |
| 39 | button{background:#efefef;padding:1px 6px;text-align:center} |
| 40 | input[type=checkbox],input[type=radio]{min-width:13px;width:13px;height:13px;min-height:13px;padding:0;margin:3px 3px 3px 4px;vertical-align:middle} |
| 41 | input[type=radio]{border-radius:50%} |
| 42 | input[type=range]{border:none;background:transparent;padding:0} |
| 43 | input[type=color]{width:50px;height:27px;padding:2px} |
| 44 | input[type=hidden]{display:none} |
| 45 | textarea{display:block;min-height:3em;white-space:pre-wrap} |
| 46 | progress,meter{display:inline-block;width:10em;height:1em;background:#e6e6e6;border-radius:2px} |
| 47 | canvas{display:inline-block;background:transparent} |
| 48 | svg{display:inline-block} |
| 49 | details>summary{display:block;cursor:pointer} |
| 50 | details:not([open])>*:not(summary){display:none} |
| 51 | dialog:not([open]){display:none} |
| 52 | [hidden]{display:none} |
| 53 | )css"; |
| 54 | |
| 55 | const char* const VOID_TAGS[] = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source" |
| 56 | |
| 57 | bool is_void(const std::string& tag) { |
| 58 | for (const char* v : VOID_TAGS) |
| 59 | if (tag == v) return true; |
| 60 | return false; |
| 61 | } |
| 62 | |
| 63 | bool starts_with_on(const std::string& name) { |
| 64 | return name.size() >= 2 && (name[0] == 'o' || name[0] == 'O') && (name[1] == |
| 65 | } |
| 66 | |
| 67 | std::string lower(std::string s) { |
| 68 | for (auto& c : s) c = char(std::tolower((unsigned char)c)); |
| 69 | return s; |
| 70 | } |
| 71 | |
| 72 | void escape_text(const std::string& s, std::string& out) { |
| 73 | for (char c : s) { |
| 74 | switch (c) { |
| 75 | case '&': out += "&"; break; |
| 76 | case '<': out += "<"; break; |
| 77 | case '>': out += ">"; break; |
| 78 | default: out.push_back(c); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | void escape_attr(const std::string& s, std::string& out) { |
| 84 | for (char c : s) { |
| 85 | switch (c) { |
| 86 | case '&': out += "&"; break; |
| 87 | case '<': out += "<"; break; |
| 88 | case '"': out += """; break; |
| 89 | default: out.push_back(c); |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | Color color_of(const litehtml::web_color& c) { |
| 95 | return Color{c.red, c.green, c.blue, c.alpha}; |
| 96 | } |
| 97 | |
| 98 | Rect rect_of(const litehtml::position& p) { |
| 99 | return Rect{float(p.x), float(p.y), float(p.width), float(p.height)}; |
| 100 | } |
| 101 | |
| 102 | /// The border box of an element in document coordinates (`get_placement()` is the content box; |
| 103 | /// getBoundingClientRect / offsetWidth are border boxes). |
| 104 | Rect border_box_of(const litehtml::element::ptr& el) { |
| 105 | litehtml::position pos = el->get_placement(); |
| 106 | Rect r = rect_of(pos); |
| 107 | if (auto ri = el->get_render_item()) { |
| 108 | const auto& pad = ri->get_paddings(); |
| 109 | const auto& bd = ri->get_borders(); |
| 110 | r.x -= float(pad.left) + float(bd.left); |
| 111 | r.y -= float(pad.top) + float(bd.top); |
| 112 | r.w += float(pad.left) + float(pad.right) + float(bd.left) + float(bd.right); |
| 113 | r.h += float(pad.top) + float(pad.bottom) + float(bd.top) + float(bd.bottom); |
| 114 | } |
| 115 | return r; |
| 116 | } |
| 117 | |
| 118 | Radii radii_of(const litehtml::border_radiuses& r) { |
| 119 | return Radii{float(r.top_left_x), float(r.top_left_y), float(r.top_right_x), float(r.top_right_y), |
| 120 | float(r.bottom_right_x), float(r.bottom_right_y), float(r.bottom_left_x), float(r.bottom_left_y)}; |
| 121 | } |
| 122 | |
| 123 | Json rect_json(const Rect& r) { |
| 124 | Json o = Json::object(); |
| 125 | o.set("x", r.x).set("y", r.y).set("width", r.w).set("height", r.h); |
| 126 | o.set("top", r.y).set("left", r.x).set("right", r.x + r.w).set("bottom", r.y + r.h); |
| 127 | return o; |
| 128 | } |
| 129 | |
| 130 | double now_ms() { |
| 131 | using namespace std::chrono; |
| 132 | return duration<double, std::milli>(steady_clock::now().time_since_epoch()).count(); |
| 133 | } |
| 134 | |
| 135 | std::string base64_encode(const std::vector<uint8_t>& in) { |
| 136 | static const char* A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 137 | std::string out; |
| 138 | out.reserve((in.size() + 2) / 3 * 4); |
| 139 | size_t i = 0; |
| 140 | for (; i + 2 < in.size(); i += 3) { |
| 141 | uint32_t v = (uint32_t(in[i]) << 16) | (uint32_t(in[i + 1]) << 8) | in[i + 2]; |
| 142 | out += A[v >> 18]; out += A[(v >> 12) & 63]; out += A[(v >> 6) & 63]; out += A[v & |
| 143 | } |
| 144 | if (i + 1 == in.size()) { |
| 145 | uint32_t v = uint32_t(in[i]) << 16; |
| 146 | out += A[v >> 18]; out += A[(v >> 12) & 63]; out += "=="; |
| 147 | } else if (i + 2 == in.size()) { |
| 148 | uint32_t v = (uint32_t(in[i]) << 16) | (uint32_t(in[i + 1]) << 8); |
| 149 | out += A[v >> 18]; out += A[(v >> 12) & 63]; out += A[(v >> 6) & 63]; out += '='; |
| 150 | } |
| 151 | return out; |
| 152 | } |
| 153 | |
| 154 | /// What a compositor layer animates; an element animating anything else is painted per frame. |
| 155 | bool is_layer_property(const std::string& property) { |
| 156 | return property == "transform" || property == "opacity" || property == "translate" || property == "rotate" || property == "scale" |
| 157 | } |
| 158 | |
| 159 | /// The `style` attribute is the inline style itself, as in the DOM: setting it replaces what the |
| 160 | /// style ops set, and a style op that removes a property removes it from what the attribute set. |
| 161 | void set_inline_style(std::vector<std::pair<std::string, std::string>>& styles, const std::string& |
| 162 | styles.clear(); |
| 163 | for (auto& d : css::parse_declarations(text)) styles.emplace_back(std::move(d.name), d.important ? d.value + " !important" : std::move(d.value)); |
| 164 | } |
| 165 | |
| 166 | /// Move-type events: only the latest one per type and pointer goes out, once per frame. |
| 167 | bool coalesced(const std::string& type) { |
| 168 | return type == "pointermove" || type == "mousemove" || type == "touchmove" || type == "wheel"; |
| 169 | } |
| 170 | |
| 171 | constexpr int MAX_CANVASES = 64; |
| 172 | /// Layers: at most this many per widget, this many device pixels in all, and no track shorter |
| 173 | /// than this (a frame or two is cheaper to paint than to hand over). |
| 174 | constexpr size_t MAX_LAYERS = 64; |
| 175 | constexpr double MAX_LAYER_PIXELS = 4096.0 * 4096.0; |
| 176 | constexpr double MIN_LAYER_SPAN = 0.1; |
| 177 | constexpr float LAYER_MARGIN = 48; |
| 178 | constexpr double DOUBLE_CLICK_MS = 500; |
| 179 | |
| 180 | } // namespace |
| 181 | |
| 182 | // ───────────────────────── color scheme rewrite ───────────────────────── |
| 183 | |
| 184 | std::string rewrite_color_scheme(const std::string& css, bool dark) { |
| 185 | static const std::string KEY = "prefers-color-scheme"; |
| 186 | std::string out; |
| 187 | out.reserve(css.size()); |
| 188 | size_t pos = 0; |
| 189 | while (true) { |
| 190 | size_t i = css.find(KEY, pos); |
| 191 | if (i == std::string::npos) { |
| 192 | out.append(css, pos, std::string::npos); |
| 193 | break; |
| 194 | } |
| 195 | out.append(css, pos, i - pos); |
| 196 | size_t j = i + KEY.size(); |
| 197 | while (j < css.size() && (css[j] == ' ' || css[j] == '\t' || css[j] == '\n' || css[j] |
| 198 | size_t k = j; |
| 199 | while (k < css.size() && std::isalpha((unsigned char)css[k])) k++; |
| 200 | std::string value = lower(css.substr(j, k - j)); |
| 201 | bool matches = value.empty() ? true : (value == "dark") == dark; // bare `(prefers-color-scheme)` is true |
| 202 | out += matches ? "min-width:0px" : "min-width:999999px"; |
| 203 | pos = k; |
| 204 | } |
| 205 | return out; |
| 206 | } |
| 207 | |
| 208 | // ───────────────────────── shadow tree ───────────────────────── |
| 209 | |
| 210 | struct Renderer::Node { |
| 211 | enum Kind { Element, Text, Comment } kind = Element; |
| 212 | int64_t id = 0; // widget node id, 0 until adopted/registered |
| 213 | std::string tag; |
| 214 | bool svg = false; |
| 215 | std::vector<std::pair<std::string, std::string>> attrs; |
| 216 | std::vector<std::pair<std::string, std::string>> styles; // inline style properties set by `style` ops |
| 217 | std::string data; // text / comment data; stylesheet text of <style> |
| 218 | Node* parent = nullptr; |
| 219 | std::vector<Node*> children; |
| 220 | }; |
| 221 | |
| 222 | // ───────────────────────── litehtml container ───────────────────────── |
| 223 | |
| 224 | class Container : public litehtml::document_container { |
| 225 | public: |
| 226 | Container(Renderer& r, Backend& backend) : r_(r), backend_(backend) {} |
| 227 | ~Container() override { |
| 228 | // The document releases its fonts through this container on destruction: drop it |
| 229 | // (and the element handles that keep its nodes alive) while the font table still exists. |
| 230 | elements_.clear(); |
| 231 | doc_ = nullptr; |
| 232 | } |
| 233 | |
| 234 | // document lifecycle |
| 235 | /// True when the last build patched the previous document instead of parsing a new one. |
| 236 | bool patched() const { return patched_; } |
| 237 | |
| 238 | /// The master CSS of the next document; a change drops the current one (a patch keeps the master it was made with). |
| 239 | void set_master(std::string css) { |
| 240 | if (css == master_css_) return; |
| 241 | master_css_ = std::move(css); |
| 242 | elements_.clear(); |
| 243 | doc_ = nullptr; |
| 244 | } |
| 245 | |
| 246 | void build(const std::string& html, int vp_height) { |
| 247 | bool viewport_changed = vp_height != vp_height_; |
| 248 | vp_height_ = vp_height; |
| 249 | patched_ = false; |
| 250 | #ifdef TW_LITEHTML_TWIDGET |
| 251 | // twidget's litehtml fork patches a document made by createUpdatableFromString in place when the |
| 252 | // new HTML only changes what it can patch (styles, text, classes, attributes, child lists), and |
| 253 | // refuses otherwise, leaving the document as it was. |
| 254 | bool changed = true; |
| 255 | if (doc_ && doc_->update_from_string(html, &changed)) { |
| 256 | patched_ = true; |
| 257 | if (viewport_changed) doc_->media_changed(); |
| 258 | float width = float(r_.width_); |
| 259 | if (!changed && !viewport_changed && width == rendered_width_) return; |
| 260 | if (!doc_->last_patch_paint_only() || viewport_changed || width != rendered_width_) { |
| 261 | doc_->render(litehtml::pixel_t(width)); |
| 262 | rendered_width_ = width; |
| 263 | layouts_++; |
| 264 | } |
| 265 | // A child-list patch replaces elements; a paint-only one cannot. |
| 266 | if (!doc_->last_patch_paint_only()) index(); |
| 267 | return; |
| 268 | } |
| 269 | #endif |
| 270 | elements_.clear(); |
| 271 | doc_ = nullptr; |
| 272 | #ifdef TW_LITEHTML_TWIDGET |
| 273 | doc_ = litehtml::document::createUpdatableFromString(html, this, master_css_); |
| 274 | #else |
| 275 | doc_ = litehtml::document::createFromString(litehtml::estring(html), this, master_css_); |
| 276 | #endif |
| 277 | if (!doc_) return; |
| 278 | rendered_width_ = float(r_.width_); |
| 279 | doc_->render(litehtml::pixel_t(rendered_width_)); |
| 280 | layouts_++; |
| 281 | index(); |
| 282 | } |
| 283 | |
| 284 | void index() { |
| 285 | elements_.clear(); |
| 286 | if (auto root = doc_->root()) { |
| 287 | for (auto& el : root->select_all("[data-twid]")) { |
| 288 | if (const char* a = el->get_attr("data-twid")) elements_[std::strtoll(a, nullptr, 10)] = el; |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | double height() const { return doc_ ? double(doc_->height()) : 0.0; } |
| 293 | #ifdef TW_LITEHTML_TWIDGET |
| 294 | /// The declared values of `names` on every displayed element with a widget id that declares |
| 295 | /// one of `gates`, or whose id is in `always`. What the fork records as raw declarations. |
| 296 | std::unordered_map<int64_t, Declared> declarations(const std::vector<std::string>& names, const std::vector< |
| 297 | std::unordered_map<int64_t, Declared> out; |
| 298 | if (!doc_ || !doc_->root()) return out; |
| 299 | std::function<void(const litehtml::element::ptr&)> visit = [&](const litehtml::element::ptr& el) { |
| 300 | if (el->css().get_display() == litehtml::display_none) return; |
| 301 | if (auto tag = std::dynamic_pointer_cast<litehtml::html_tag>(el)) { |
| 302 | if (const char* a = tag->get_attr("data-twid")) { |
| 303 | int64_t id = std::strtoll(a, nullptr, 10); |
| 304 | bool listed = std::find(always.begin(), always.end(), id) != always.end(); |
| 305 | bool open = listed; |
| 306 | for (size_t i = 0; !open && i < gates.size(); i++) open = !tag->raw_declaration(gates[i]).empty(); |
| 307 | if (open) { |
| 308 | Declared found; |
| 309 | for (const std::string& name : names) { |
| 310 | std::string raw = tag->raw_declaration(name); |
| 311 | if (!raw.empty()) found.emplace(name, std::move(raw)); |
| 312 | } |
| 313 | if (!found.empty() || listed) out[id] = std::move(found); |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | for (const auto& child : el->children()) visit(child); |
| 318 | }; |
| 319 | visit(doc_->root()); |
| 320 | return out; |
| 321 | } |
| 322 | /// Replaces the style attribute of elements in place (the fork's style holes), relaying out |
| 323 | /// only when a value can move boxes. False when the document cannot patch them. |
| 324 | bool restyle(const std::vector<std::pair<litehtml::element::ptr, std::string>>& patches) { |
| 325 | if (!doc_) return false; |
| 326 | bool changed = false; |
| 327 | if (!doc_->update_styles(patches, &changed)) return false; |
| 328 | patched_ = true; |
| 329 | if (changed && !doc_->last_patch_paint_only()) { |
| 330 | rendered_width_ = float(r_.width_); |
| 331 | doc_->render(litehtml::pixel_t(rendered_width_)); |
| 332 | layouts_++; |
| 333 | } |
| 334 | return true; |
| 335 | } |
| 336 | |
| 337 | // compositor layers |
| 338 | |
| 339 | /// Counts layouts: boxes, and so what can cover a layer, change only with one. |
| 340 | uint64_t layouts() const { return layouts_; } |
| 341 | /// `el` can be painted on its own as a layer: a box with no effects of its own, under no |
| 342 | /// ancestor that groups its paint. `box` gets its border box. |
| 343 | bool layer_candidate(const litehtml::element::ptr& el, Rect& box) const { |
| 344 | auto ri = el->get_render_item(); |
| 345 | if (!doc_ || !ri || !ri->is_visible() || (el->is_inline() && !el->is_inline_box())) return false; |
| 346 | const auto& css = el->css(); |
| 347 | if (!css.get_filter().empty() || !css.get_backdrop_filter().empty()) return false; |
| 348 | for (auto p = ri->parent(); p; p = p->parent()) |
| 349 | if (p->src_el()->css().is_paint_group()) return false; |
| 350 | box = border_box_of(el); |
| 351 | return box.w > 0 && box.h > 0 && box.w * box.h < 2'000'000; |
| 352 | } |
| 353 | /// The ancestor that clips `el`, if one does: its padding box and inner radii. False when two |
| 354 | /// do; a layer carries one clip. |
| 355 | bool clip_of(const litehtml::element::ptr& el, bool& has, Rect& rect, Radii& radii) const |
| 356 | has = false; |
| 357 | auto ri = el->get_render_item(); |
| 358 | if (!ri) return false; |
| 359 | for (auto p = ri->parent(); p; p = p->parent()) { |
| 360 | if (!p->src_el()->css().clips_contents()) continue; |
| 361 | if (has) return false; |
| 362 | has = true; |
| 363 | Rect border = border_box_of(p->src_el()); |
| 364 | const auto& b = p->get_borders(); |
| 365 | rect = Rect{border.x + float(b.left), border.y + float(b.top), border.w - float(b.left) - float(b.right), border.h - float(b.top) - float(b.bottom)}; |
| 366 | auto r = p->src_el()->css().get_borders().radius.calc_percents(litehtml::pixel_t(border.w), litehtml::pixel_t(border.h)); |
| 367 | radii = Radii{std::max(0.0f, float(r.top_left_x) - float(b.left)), std::max(0.0f, float(r.top_left_y) - float(b.top)), |
| 368 | std::max(0.0f, float(r.top_right_x) - float(b.right)), std::max(0.0f, float(r.top_right_y) - float(b.top)), |
| 369 | std::max(0.0f, float(r.bottom_right_x) - float(b.right)), std::max(0.0f, float(r.bottom_right_y) - float(b.bottom)), |
| 370 | std::max(0.0f, float(r.bottom_left_x) - float(b.left)), std::max(0.0f, float(r.bottom_left_y) - float(b.bottom))}; |
| 371 | } |
| 372 | return true; |
| 373 | } |
| 374 | /// Render items in the order a full paint draws them. |
| 375 | std::vector<const litehtml::render_item*> paint_order() { |
| 376 | std::vector<const litehtml::render_item*> trace; |
| 377 | if (!doc_) return trace; |
| 378 | litehtml::g_paint_trace = &trace; |
| 379 | draw(); |
| 380 | litehtml::g_paint_trace = nullptr; |
| 381 | return trace; |
| 382 | } |
| 383 | /// Something painted after `el` meets `area`, other than `el`'s descendants and what `ignore` |
| 384 | /// holds (other layers, ordered among themselves by paint order). |
| 385 | bool covered(const litehtml::element::ptr& el, const Rect& area, const std::vector<const |
| 386 | const std::unordered_set<const litehtml::element*>& ignore) const { |
| 387 | auto ri = el->get_render_item(); |
| 388 | auto self = std::find(trace.begin(), trace.end(), ri.get()); |
| 389 | if (self == trace.end()) return true; |
| 390 | for (auto it = std::next(self); it != trace.end(); ++it) { |
| 391 | const litehtml::render_item* item = *it; |
| 392 | if (item->src_el()->is_space()) continue; |
| 393 | bool skip = false; |
| 394 | for (const litehtml::render_item* walk = item; walk && !skip; walk = walk->parent().get()) |
| 395 | skip = walk == ri.get() || ignore.count(walk->src_el().get()); |
| 396 | if (skip) continue; |
| 397 | Rect box = border_box_of(item->src_el()); |
| 398 | if (box.w <= 0 || box.h <= 0) continue; |
| 399 | if (box.x < area.x + area.w && area.x < box.x + box.w && box.y < area.y + area.h && area.y < box.y + box.h) return true; |
| 400 | } |
| 401 | return false; |
| 402 | } |
| 403 | /// Paints the document without the elements in `skip`. |
| 404 | DisplayList draw(const std::vector<litehtml::element::ptr>& skip) { |
| 405 | if (!doc_) return {}; |
| 406 | for (const auto& el : skip) doc_->skip_paint.insert(el.get()); |
| 407 | DisplayList list = draw(); |
| 408 | doc_->skip_paint.clear(); |
| 409 | return list; |
| 410 | } |
| 411 | /// `el` and its descendants alone, without `el`'s own transform, opacity and stacking group |
| 412 | /// (the layer applies them) and without the other layers in `skip`. `bounds` gets the area the |
| 413 | /// paint can reach. |
| 414 | DisplayList draw_layer(const litehtml::element::ptr& el, const std::vector<litehtml::element::ptr>& skip |
| 415 | list_.clear(); |
| 416 | groups_.clear(); |
| 417 | auto ri = el->get_render_item(); |
| 418 | if (!doc_ || !ri) return {}; |
| 419 | for (const auto& other : skip) |
| 420 | if (other != el) doc_->skip_paint.insert(other.get()); |
| 421 | litehtml::position placement = ri->get_placement(); |
| 422 | litehtml::pixel_t x = placement.x - ri->pos().x, y = placement.y - ri->pos().y; |
| 423 | el->draw(0, x, y, nullptr, ri); |
| 424 | if (ri->is_visible()) draw_stacking_context(ri, x, y); |
| 425 | doc_->skip_paint.clear(); |
| 426 | Rect box = border_box_of(el); |
| 427 | litehtml::position redraw(litehtml::pixel_t(box.x), litehtml::pixel_t(box.y), litehtml::pixel_t(box.w), litehtml::pixel_t(box.h)); |
| 428 | ri->get_redraw_box(redraw, x, y); |
| 429 | // The redraw box leaves out shadows and anti-aliasing: a margin keeps them. |
| 430 | float x0 = std::min(box.x, float(redraw.x)) - LAYER_MARGIN, y0 = std::min(box.y, float(redraw.y)) - LAYER_MARGIN; |
| 431 | float x1 = std::max(box.x + box.w, float(redraw.x) + float(redraw.width)) + LAYER_MARGIN; |
| 432 | float y1 = std::max(box.y + box.h, float(redraw.y) + float(redraw.height)) + LAYER_MARGIN; |
| 433 | bounds = Rect{std::floor(x0), std::floor(y0), std::ceil(x1) - std::floor(x0), std::ceil(y1) - std::floor(y0)}; |
| 434 | return std::move(list_); |
| 435 | } |
| 436 | #endif |
| 437 | /// The pointer left the view: :hover ends. True when something must repaint. |
| 438 | bool leave() { |
| 439 | if (!doc_) return false; |
| 440 | bool redraw = false; |
| 441 | doc_->on_mouse_leave([&](const litehtml::position&) { redraw = true; }); |
| 442 | return redraw; |
| 443 | } |
| 444 | /// A decoded image for the canvas's drawImage: loads `url` like an <img> would. |
| 445 | bool image_of(const std::string& url, int& id, float& w, float& h) { |
| 446 | load_image(url.c_str(), nullptr, false); |
| 447 | auto it = images_.find(url); |
| 448 | if (it == images_.end() || !it->second.id) return false; |
| 449 | id = it->second.id; |
| 450 | w = it->second.w; |
| 451 | h = it->second.h; |
| 452 | return true; |
| 453 | } |
| 454 | /// An asynchronously decoded image got its size; true when a known image changed. |
| 455 | bool image_ready(int id, float w, float h) { |
| 456 | for (auto& [url, img] : images_) { |
| 457 | if (img.id == id) { |
| 458 | if (img.w == w && img.h == h) return false; |
| 459 | img.w = w; |
| 460 | img.h = h; |
| 461 | return true; |
| 462 | } |
| 463 | } |
| 464 | return false; |
| 465 | } |
| 466 | litehtml::document* doc() const { return doc_.get(); } |
| 467 | litehtml::element::ptr element(int64_t id) const { |
| 468 | auto it = elements_.find(id); |
| 469 | return it == elements_.end() ? nullptr : it->second; |
| 470 | } |
| 471 | /// The widget id of a litehtml element or of its nearest ancestor with one (0 when none). |
| 472 | int64_t widget_id(litehtml::element::ptr el, Rect* placement) const { |
| 473 | while (el) { |
| 474 | if (const char* a = el->get_attr("data-twid")) { |
| 475 | if (placement) *placement = border_box_of(el); |
| 476 | return std::strtoll(a, nullptr, 10); |
| 477 | } |
| 478 | el = el->parent(); |
| 479 | } |
| 480 | return 0; |
| 481 | } |
| 482 | litehtml::element::ptr element_at(double x, double y) const { |
| 483 | if (!doc_ || !doc_->root_render()) return nullptr; |
| 484 | auto px = litehtml::pixel_t(float(x)), py = litehtml::pixel_t(float(y)); |
| 485 | return doc_->root_render()->get_element_by_point(px, py, px, py, nullptr); |
| 486 | } |
| 487 | /// Pointer state for :hover / :active; true when something must repaint. A lifted finger leaves |
| 488 | /// :hover; a mouse released over the view keeps it. |
| 489 | bool mouse(int action, double x, double y, bool hovers = false) { |
| 490 | if (!doc_) return false; |
| 491 | bool redraw = false; |
| 492 | auto box = [&](const litehtml::position&) { redraw = true; }; |
| 493 | auto px = litehtml::pixel_t(float(x)), py = litehtml::pixel_t(float(y)); |
| 494 | switch (action) { |
| 495 | case 0: doc_->on_mouse_over(px, py, px, py, box); doc_->on_lbutton_down(px, py, px, py, box); break; |
| 496 | case 1: doc_->on_mouse_over(px, py, px, py, box); break; |
| 497 | case 2: |
| 498 | doc_->on_lbutton_up(px, py, px, py, box); |
| 499 | if (!hovers) doc_->on_mouse_leave(box); |
| 500 | break; |
| 501 | default: doc_->on_button_cancel(box); doc_->on_mouse_leave(box); break; |
| 502 | } |
| 503 | return redraw; |
| 504 | } |
| 505 | DisplayList draw() { |
| 506 | list_.clear(); |
| 507 | #ifdef TW_LITEHTML_TWIDGET |
| 508 | groups_.clear(); |
| 509 | #endif |
| 510 | if (doc_) { |
| 511 | litehtml::position clip(0, 0, litehtml::pixel_t(float(r_.width_)), litehtml::pixel_t(float(vp_height_))); |
| 512 | doc_->draw(0, 0, 0, &clip); |
| 513 | } |
| 514 | return std::move(list_); |
| 515 | } |
| 516 | /// A font for `measureText` (CSS font shorthand parsed loosely). |
| 517 | Json measure_text(const std::string& font, const std::string& text) { |
| 518 | float size = 10; |
| 519 | bool italic = false; |
| 520 | int weight = 400; |
| 521 | std::string family = "sans-serif"; |
| 522 | std::vector<std::string> tokens; |
| 523 | { |
| 524 | std::string cur; |
| 525 | bool quoted = false; |
| 526 | for (char c : font) { |
| 527 | if (c == '"' || c == '\'') quoted = !quoted; |
| 528 | if (c == ' ' && !quoted) { |
| 529 | if (!cur.empty()) tokens.push_back(cur); |
| 530 | cur.clear(); |
| 531 | } else cur.push_back(c); |
| 532 | } |
| 533 | if (!cur.empty()) tokens.push_back(cur); |
| 534 | } |
| 535 | size_t i = 0; |
| 536 | for (; i < tokens.size(); i++) { |
| 537 | const std::string t = lower(tokens[i]); |
| 538 | if (t == "italic" || t == "oblique") italic = true; |
| 539 | else if (t == "bold" || t == "bolder") weight = 700; |
| 540 | else if (t == "normal" || t == "lighter" || t == "small-caps") {} |
| 541 | else if (std::isdigit((unsigned char)t[0]) && t.find("px") == std::string::npos && t.find( |
| 542 | else if (std::isdigit((unsigned char)t[0]) || t[0] == '.') { |
| 543 | size = float(std::atof(t.c_str())); |
| 544 | if (t.find("pt") != std::string::npos) size *= 96.0f / 72.0f; |
| 545 | else if (t.find("em") != std::string::npos) size *= 16.0f; |
| 546 | i++; |
| 547 | break; |
| 548 | } else break; |
| 549 | } |
| 550 | if (i < tokens.size()) { |
| 551 | family.clear(); |
| 552 | for (; i < tokens.size(); i++) { |
| 553 | if (!family.empty()) family += ' '; |
| 554 | family += tokens[i]; |
| 555 | } |
| 556 | } |
| 557 | FontMetrics fm; |
| 558 | int handle = backend_.create_font(family, size, weight, italic, fm); |
| 559 | Json o = Json::object(); |
| 560 | float width = handle ? backend_.text_width(handle, text) : 0.0f; |
| 561 | if (handle) backend_.delete_font(handle); |
| 562 | o.set("width", width); |
| 563 | o.set("actualBoundingBoxLeft", 0).set("actualBoundingBoxRight", width); |
| 564 | o.set("actualBoundingBoxAscent", fm.ascent * 0.8f).set("actualBoundingBoxDescent", fm.descent * 0.6f); |
| 565 | o.set("fontBoundingBoxAscent", fm.ascent).set("fontBoundingBoxDescent", fm.descent); |
| 566 | o.set("emHeightAscent", fm.ascent).set("emHeightDescent", fm.descent); |
| 567 | o.set("hangingBaseline", fm.ascent * 0.8f).set("alphabeticBaseline", 0).set("ideographicBaseline", -fm.descent); |
| 568 | return o; |
| 569 | } |
| 570 | |
| 571 | // ── document_container: fonts and text ── |
| 572 | litehtml::uint_ptr create_font(const litehtml::font_description& descr, const litehtml::document*, litehtml::font_metrics* fm) |
| 573 | FontMetrics m; |
| 574 | int handle = backend_.create_font(descr.family, float(descr.size), descr.weight, descr.style == litehtml::font_style_italic, m); |
| 575 | if (!handle) return 0; |
| 576 | Font f; |
| 577 | f.handle = handle; |
| 578 | f.metrics = m; |
| 579 | f.size = float(descr.size); |
| 580 | f.decoration = descr.decoration_line; |
| 581 | f.decoration_color = descr.decoration_color; |
| 582 | if (fm) { |
| 583 | fm->font_size = descr.size; |
| 584 | fm->ascent = litehtml::pixel_t(m.ascent); |
| 585 | fm->descent = litehtml::pixel_t(m.descent); |
| 586 | fm->height = litehtml::pixel_t(std::max(m.height, m.ascent + m.descent)); |
| 587 | fm->x_height = litehtml::pixel_t(m.x_height > 0 ? m.x_height : m.ascent * 0.5f); |
| 588 | fm->ch_width = litehtml::pixel_t(m.zero_width); |
| 589 | fm->draw_spaces = descr.decoration_line != litehtml::text_decoration_line_none; |
| 590 | fm->sub_shift = litehtml::pixel_t(f.size / 5); |
| 591 | fm->super_shift = litehtml::pixel_t(f.size / 3); |
| 592 | } |
| 593 | litehtml::uint_ptr id = ++next_font_; |
| 594 | fonts_[id] = f; |
| 595 | return id; |
| 596 | } |
| 597 | void delete_font(litehtml::uint_ptr h) override { |
| 598 | auto it = fonts_.find(h); |
| 599 | if (it == fonts_.end()) return; |
| 600 | backend_.delete_font(it->second.handle); |
| 601 | fonts_.erase(it); |
| 602 | } |
| 603 | litehtml::pixel_t text_width(const char* text, litehtml::uint_ptr h) override { |
| 604 | auto it = fonts_.find(h); |
| 605 | if (it == fonts_.end() || !text) return 0; |
| 606 | std::string key = std::to_string(it->second.handle); |
| 607 | key.push_back('\0'); |
| 608 | key += text; |
| 609 | auto c = widths_.find(key); |
| 610 | if (c != widths_.end()) return litehtml::pixel_t(c->second); |
| 611 | float w = backend_.text_width(it->second.handle, text); |
| 612 | if (widths_.size() > 20000) widths_.clear(); |
| 613 | widths_[key] = w; |
| 614 | return litehtml::pixel_t(w); |
| 615 | } |
| 616 | void draw_text(litehtml::uint_ptr, const char* text, litehtml::uint_ptr h, litehtml::web_color color, const litehtml:: |
| 617 | auto it = fonts_.find(h); |
| 618 | if (it == fonts_.end() || !text || !*text) return; |
| 619 | const Font& f = it->second; |
| 620 | Command c; |
| 621 | c.kind = Cmd::Text; |
| 622 | c.font = f.handle; |
| 623 | c.text = text; |
| 624 | c.color = color_of(color); |
| 625 | c.x = float(pos.x); |
| 626 | // litehtml hands the line box; the baseline sits `descent` above its bottom (as the cairo container does). |
| 627 | c.y = float(pos.y) + float(pos.height) - f.metrics.descent; |
| 628 | list_.push_back(std::move(c)); |
| 629 | if (f.decoration != litehtml::text_decoration_line_none) { |
| 630 | float w = float(pos.width); |
| 631 | if (w <= 0) w = backend_.text_width(f.handle, text); |
| 632 | float thickness = std::max(1.0f, f.size / 14.0f); |
| 633 | Color dc = f.decoration_color.is_current_color ? color_of(color) : color_of(f.decoration_color); |
| 634 | float baseline = float(pos.y) + float(pos.height) - f.metrics.descent; |
| 635 | auto line = [&](float y) { |
| 636 | Command l; |
| 637 | l.kind = Cmd::FillRect; |
| 638 | l.rect = Rect{float(pos.x), y, w, thickness}; |
| 639 | l.color = dc; |
| 640 | list_.push_back(std::move(l)); |
| 641 | }; |
| 642 | if (f.decoration & litehtml::text_decoration_line_underline) line(baseline + std::max(1.0f, f.metrics.descent * 0.35f)); |
| 643 | if (f.decoration & litehtml::text_decoration_line_line_through) line(baseline - f.metrics.ascent * 0.3f - thickness / 2); |
| 644 | if (f.decoration & litehtml::text_decoration_line_overline) line(float(pos.y)); |
| 645 | } |
| 646 | } |
| 647 | litehtml::pixel_t pt_to_px(float pt) const override { return litehtml::pixel_t(pt * 96.0f / 72.0f); } |
| 648 | litehtml::pixel_t get_default_font_size() const override { return 16; } |
| 649 | const char* get_default_font_name() const override { return "-apple-system, system-ui, sans-serif"; } |
| 650 | void draw_list_marker(litehtml::uint_ptr, const litehtml::list_marker& marker) override { |
| 651 | Command c; |
| 652 | c.rect = rect_of(marker.pos); |
| 653 | c.color = color_of(marker.color); |
| 654 | switch (marker.marker_type) { |
| 655 | case litehtml::list_style_type_none: return; |
| 656 | case litehtml::list_style_type_disc: c.kind = Cmd::FillEllipse; break; |
| 657 | case litehtml::list_style_type_circle: c.kind = Cmd::StrokeEllipse; c.width = 1; break; |
| 658 | case litehtml::list_style_type_square: c.kind = Cmd::FillRect; break; |
| 659 | default: { |
| 660 | auto it = fonts_.find(marker.font); |
| 661 | if (it == fonts_.end()) return; |
| 662 | c.kind = Cmd::Text; |
| 663 | c.font = it->second.handle; |
| 664 | c.text = marker_text(marker.marker_type, marker.index); |
| 665 | c.x = float(marker.pos.x); |
| 666 | c.y = float(marker.pos.y) + float(marker.pos.height) - it->second.metrics.descent; |
| 667 | } |
| 668 | } |
| 669 | list_.push_back(std::move(c)); |
| 670 | } |
| 671 | |
| 672 | // ── images: data: only, decoded by the backend, referenced by id ── |
| 673 | void load_image(const char* src, const char*, bool) override { |
| 674 | if (!src) return; |
| 675 | std::string url = src; |
| 676 | if (images_.count(url)) return; |
| 677 | Image img; |
| 678 | if (url.rfind("tw-canvas:", 0) == 0) { |
| 679 | // The renderer's own source for a <canvas>: tw-canvas:<node id>/<w>x<h>, drawn from the backend's bitmap. |
| 680 | int id = 0, w = 0, h = 0; |
| 681 | if (std::sscanf(url.c_str() + 10, "%d/%dx%d", &id, &w, &h) == 3) { |
| 682 | img.canvas = id; |
| 683 | img.w = float(w); |
| 684 | img.h = float(h); |
| 685 | } |
| 686 | } else if (url.rfind("data:", 0) == 0) { |
| 687 | // The backend may answer the size later (`image_ready`): the id stays, the size is 0 until then. |
| 688 | img.id = ++next_image_; |
| 689 | if (!backend_.load_image(img.id, url, img.w, img.h)) img.id = 0; |
| 690 | } else { |
| 691 | r_.pending_violations_.push_back("image refused: " + url.substr(0, 80)); |
| 692 | } |
| 693 | images_[url] = img; |
| 694 | } |
| 695 | void get_image_size(const char* src, const char*, litehtml::size& sz) override { |
| 696 | auto it = src ? images_.find(src) : images_.end(); |
| 697 | if (it == images_.end()) { sz.width = 0; sz.height = 0; return; } |
| 698 | sz.width = litehtml::pixel_t(it->second.w); |
| 699 | sz.height = litehtml::pixel_t(it->second.h); |
| 700 | } |
| 701 | void draw_image(litehtml::uint_ptr, const litehtml::background_layer& layer, const std::string& url, const std:: |
| 702 | auto it = images_.find(url); |
| 703 | if (it == images_.end() || (!it->second.id && !it->second.canvas)) return; |
| 704 | Command c; |
| 705 | c.kind = Cmd::Image; |
| 706 | c.image = it->second.id; |
| 707 | c.canvas = it->second.canvas; |
| 708 | c.rect = rect_of(layer.origin_box); |
| 709 | c.radii = radii_of(layer.border_radius); |
| 710 | c.clip = rect_of(layer.clip_box); |
| 711 | c.has_clip = true; |
| 712 | // the border box bounds the drawing too |
| 713 | Rect b = rect_of(layer.border_box); |
| 714 | clip_intersect(c.clip, b); |
| 715 | list_.push_back(std::move(c)); |
| 716 | } |
| 717 | |
| 718 | // ── backgrounds ── |
| 719 | void draw_solid_fill(litehtml::uint_ptr, const litehtml::background_layer& layer, const litehtml::web_color& color) override { |
| 720 | if (color.alpha == 0) return; |
| 721 | Command c; |
| 722 | c.kind = Cmd::FillRect; |
| 723 | c.color = color_of(color); |
| 724 | if (layer.is_root) { |
| 725 | // the root background covers the whole canvas, like a browser's |
| 726 | c.rect = Rect{0, 0, float(r_.width_), float(vp_height_)}; |
| 727 | } else { |
| 728 | c.rect = rect_of(layer.border_box); |
| 729 | c.radii = radii_of(layer.border_radius); |
| 730 | c.clip = rect_of(layer.clip_box); |
| 731 | c.has_clip = true; |
| 732 | } |
| 733 | list_.push_back(std::move(c)); |
| 734 | } |
| 735 | void gradient_common(Command& c, const litehtml::background_layer& layer, const litehtml::background_layer::gradient_base& g) { |
| 736 | c.rect = rect_of(layer.border_box); |
| 737 | c.radii = radii_of(layer.border_radius); |
| 738 | c.clip = rect_of(layer.clip_box); |
| 739 | c.has_clip = true; |
| 740 | for (const auto& p : g.color_points) c.stops.push_back(Stop{p.offset, color_of(p.color)}); |
| 741 | } |
| 742 | void draw_linear_gradient(litehtml::uint_ptr, const litehtml::background_layer& layer, const litehtml::background_layer::linear_gradient& g) override |
| 743 | Command c; |
| 744 | c.kind = Cmd::Linear; |
| 745 | gradient_common(c, layer, g); |
| 746 | c.ax = g.start.x; c.ay = g.start.y; c.bx = g.end.x; c.by = g.end.y; |
| 747 | list_.push_back(std::move(c)); |
| 748 | } |
| 749 | void draw_radial_gradient(litehtml::uint_ptr, const litehtml::background_layer& layer, const litehtml::background_layer::radial_gradient& g) override |
| 750 | Command c; |
| 751 | c.kind = Cmd::Radial; |
| 752 | gradient_common(c, layer, g); |
| 753 | c.ax = g.position.x; c.ay = g.position.y; c.bx = g.radius.x; c.by = g.radius.y; |
| 754 | list_.push_back(std::move(c)); |
| 755 | } |
| 756 | void draw_conic_gradient(litehtml::uint_ptr, const litehtml::background_layer& layer, const litehtml::background_layer::conic_gradient& g) override |
| 757 | Command c; |
| 758 | c.kind = Cmd::Conic; |
| 759 | gradient_common(c, layer, g); |
| 760 | c.ax = g.position.x; c.ay = g.position.y; c.bx = g.angle; c.by = g.radius; |
| 761 | list_.push_back(std::move(c)); |
| 762 | } |
| 763 | |
| 764 | // ── borders: one stroke when uniform, otherwise a strip per side (dashed/dotted drawn solid) ── |
| 765 | void draw_borders(litehtml::uint_ptr, const litehtml::borders& b, const litehtml::position& draw_pos, bool) override { |
| 766 | auto visible = [](const litehtml::border& s) { return float(s.width) > 0 && s.style != litehtml::border_style_none && s.style |
| 767 | bool l = visible(b.left), t = visible(b.top), rr = visible(b.right), bt = visible(b.bottom); |
| 768 | if (!l && !t && !rr && !bt) return; |
| 769 | auto same = [](const litehtml::border& a, const litehtml::border& c) { return a.width == c.width && a.color == c.color; }; |
| 770 | if (l && t && rr && bt && same(b.left, b.top) && same(b.left, b.right) && same(b.left, b.bottom)) { |
| 771 | float w = float(b.left.width); |
| 772 | Command c; |
| 773 | c.kind = Cmd::StrokeRect; |
| 774 | c.width = w; |
| 775 | c.color = color_of(b.left.color); |
| 776 | c.rect = Rect{float(draw_pos.x) + w / 2, float(draw_pos.y) + w / 2, float(draw_pos.width) - w, float(draw_pos.height) - w}; |
| 777 | Radii r = radii_of(b.radius); |
| 778 | auto shrink = [&](float& v) { v = std::max(0.0f, v - w / 2); }; |
| 779 | shrink(r.tlx); shrink(r.tly); shrink(r.trx); shrink(r.try_); shrink(r.brx); shrink(r.bry); shrink(r.blx); shrink(r.bly); |
| 780 | c.radii = r; |
| 781 | list_.push_back(std::move(c)); |
| 782 | return; |
| 783 | } |
| 784 | Rect p = rect_of(draw_pos); |
| 785 | auto strip = [&](const litehtml::border& s, Rect rect) { |
| 786 | Command c; |
| 787 | c.kind = Cmd::FillRect; |
| 788 | c.color = color_of(s.color); |
| 789 | c.rect = rect; |
| 790 | list_.push_back(std::move(c)); |
| 791 | }; |
| 792 | if (t) strip(b.top, Rect{p.x, p.y, p.w, float(b.top.width)}); |
| 793 | if (bt) strip(b.bottom, Rect{p.x, p.y + p.h - float(b.bottom.width), p.w, float(b.bottom.width)}); |
| 794 | if (l) strip(b.left, Rect{p.x, p.y, float(b.left.width), p.h}); |
| 795 | if (rr) strip(b.right, Rect{p.x + p.w - float(b.right.width), p.y, float(b.right.width), p.h}); |
| 796 | } |
| 797 | |
| 798 | // ── chrome the renderer has none of ── |
| 799 | void set_caption(const char*) override {} |
| 800 | void set_base_url(const char*) override {} |
| 801 | void link(const std::shared_ptr<litehtml::document>&, const litehtml::element::ptr&) override {} |
| 802 | void on_anchor_click(const char*, const litehtml::element::ptr&) override {} // navigation is the sandbox's business (openLink) |
| 803 | void on_mouse_event(const litehtml::element::ptr&, litehtml::mouse_event) override {} |
| 804 | void set_cursor(const char*) override {} |
| 805 | void transform_text(std::string& text, litehtml::text_transform tt) override { |
| 806 | // ASCII only; the platforms' Unicode case mapping would need a backend call. |
| 807 | switch (tt) { |
| 808 | case litehtml::text_transform_uppercase: for (auto& c : text) c = char(std::toupper((unsigned char)c)); break; |
| 809 | case litehtml::text_transform_lowercase: for (auto& c : text) c = char(std::tolower((unsigned char)c)); break; |
| 810 | case litehtml::text_transform_capitalize: { |
| 811 | bool start = true; |
| 812 | for (auto& c : text) { |
| 813 | if (start) c = char(std::toupper((unsigned char)c)); |
| 814 | start = c == ' '; |
| 815 | } |
| 816 | break; |
| 817 | } |
| 818 | default: break; |
| 819 | } |
| 820 | } |
| 821 | void import_css(std::string& text, const std::string&, std::string&) override { text.clear(); } // @import is dropped by the validator anyway |
| 822 | void set_clip(const litehtml::position& pos, const litehtml::border_radiuses& r) override { |
| 823 | Command c; |
| 824 | c.kind = Cmd::ClipPush; |
| 825 | c.rect = rect_of(pos); |
| 826 | c.radii = radii_of(r); |
| 827 | list_.push_back(std::move(c)); |
| 828 | } |
| 829 | void del_clip() override { |
| 830 | Command c; |
| 831 | c.kind = Cmd::ClipPop; |
| 832 | list_.push_back(std::move(c)); |
| 833 | } |
| 834 | #ifdef TW_LITEHTML_TWIDGET |
| 835 | void draw_box_shadow(litehtml::uint_ptr, const litehtml::position& box, const litehtml::border_radiuses& radius, const litehtml |
| 836 | if (shadow.color.alpha == 0) return; |
| 837 | Command c; |
| 838 | c.kind = Cmd::Shadow; |
| 839 | c.rect = rect_of(box); |
| 840 | c.radii = radii_of(radius); |
| 841 | c.color = color_of(shadow.color); |
| 842 | c.ax = float(shadow.x); |
| 843 | c.ay = float(shadow.y); |
| 844 | c.bx = float(shadow.blur); |
| 845 | c.by = float(shadow.spread); |
| 846 | c.inset = shadow.inset; |
| 847 | list_.push_back(std::move(c)); |
| 848 | } |
| 849 | void begin_group(litehtml::uint_ptr, const litehtml::paint_group& group) override { |
| 850 | // Backface visibility needs the accumulated matrix: a flip undone by an outer flip is a front face. |
| 851 | litehtml::transform_matrix total = groups_.empty() ? group.matrix : group.matrix.then(groups_.back()); |
| 852 | groups_.push_back(total); |
| 853 | Command c; |
| 854 | c.kind = Cmd::GroupPush; |
| 855 | const auto& m = group.matrix; |
| 856 | float values[6] = {m.a, m.b, m.c, m.d, m.tx, m.ty}; |
| 857 | std::copy(std::begin(values), std::end(values), c.matrix); |
| 858 | c.opacity = group.opacity; |
| 859 | c.hidden = group.backface_hidden && total.a * total.d - total.b * total.c < 0; |
| 860 | c.rect = rect_of(group.bounds); |
| 861 | list_.push_back(std::move(c)); |
| 862 | } |
| 863 | void end_group(litehtml::uint_ptr) override { |
| 864 | if (!groups_.empty()) groups_.pop_back(); |
| 865 | Command c; |
| 866 | c.kind = Cmd::GroupPop; |
| 867 | list_.push_back(std::move(c)); |
| 868 | } |
| 869 | void draw_path(litehtml::uint_ptr, const litehtml::vector_path& path) override { |
| 870 | if (!path.fill && !path.stroke) return; |
| 871 | auto p = std::make_shared<Path>(); |
| 872 | p->ops.reserve(path.ops.size()); |
| 873 | for (auto op : path.ops) p->ops.push_back(Path::Op(op)); |
| 874 | p->points = path.points; |
| 875 | p->fill = path.fill; |
| 876 | p->evenodd = path.evenodd; |
| 877 | p->fill_color = color_of(path.fill_color); |
| 878 | const auto& g = path.fill_gradient; |
| 879 | p->gradient = g.type; |
| 880 | p->x1 = g.x1; p->y1 = g.y1; p->x2 = g.x2; p->y2 = g.y2; p->r = g.r; p->fx = g.fx; p->fy = g.fy; |
| 881 | for (const auto& [offset, color] : g.stops) p->stops.push_back(Stop{offset, color_of(color)}); |
| 882 | p->stroke = path.stroke; |
| 883 | p->stroke_color = color_of(path.stroke_color); |
| 884 | p->stroke_width = path.stroke_width; |
| 885 | p->line_cap = path.line_cap; |
| 886 | p->line_join = path.line_join; |
| 887 | p->miter_limit = path.miter_limit; |
| 888 | p->dashes = path.dashes; |
| 889 | p->dash_offset = path.dash_offset; |
| 890 | Command c; |
| 891 | c.kind = Cmd::Path; |
| 892 | c.path = std::move(p); |
| 893 | list_.push_back(std::move(c)); |
| 894 | } |
| 895 | #endif |
| 896 | void get_viewport(litehtml::position& v) const override { |
| 897 | v.x = 0; v.y = 0; |
| 898 | v.width = litehtml::pixel_t(float(r_.width_)); |
| 899 | v.height = litehtml::pixel_t(float(vp_height_)); |
| 900 | } |
| 901 | litehtml::element::ptr create_element(const char*, const litehtml::string_map&, const std::shared_ptr<litehtml::document> |
| 902 | void get_media_features(litehtml::media_features& m) const override { |
| 903 | m.type = litehtml::media_type_screen; |
| 904 | m.width = litehtml::pixel_t(float(r_.width_)); |
| 905 | m.height = litehtml::pixel_t(float(vp_height_)); |
| 906 | m.device_width = m.width; |
| 907 | m.device_height = m.height; |
| 908 | m.color = 8; |
| 909 | m.color_index = 256; |
| 910 | m.monochrome = 0; |
| 911 | m.resolution = litehtml::pixel_t(float(96.0 * r_.dpr_)); |
| 912 | } |
| 913 | void get_language(std::string& language, std::string& culture) const override { |
| 914 | language = "en"; |
| 915 | culture.clear(); |
| 916 | } |
| 917 | |
| 918 | private: |
| 919 | struct Font { |
| 920 | int handle = 0; |
| 921 | FontMetrics metrics; |
| 922 | float size = 16; |
| 923 | int decoration = 0; |
| 924 | litehtml::web_color decoration_color; |
| 925 | }; |
| 926 | struct Image { |
| 927 | int id = 0; |
| 928 | int canvas = 0; |
| 929 | float w = 0, h = 0; |
| 930 | }; |
| 931 | |
| 932 | #ifdef TW_LITEHTML_TWIDGET |
| 933 | static void positioned_z(const std::shared_ptr<litehtml::render_item>& item, std::set<int>& z) { |
| 934 | for (const auto& child : item->children()) { |
| 935 | if (child->src_el()->is_positioned()) z.insert(child->src_el()->css().get_z_index()); |
| 936 | else if (!child->src_el()->css().is_paint_group()) positioned_z(child, z); |
| 937 | } |
| 938 | } |
| 939 | /// An element's children in stacking order, as if it formed a stacking context: what litehtml's |
| 940 | /// own group paint does after the element's background, without the group. |
| 941 | static void draw_stacking_context(const std::shared_ptr<litehtml::render_item>& ri, litehtml::pixel_t x, litehtml::pixel_t |
| 942 | std::set<int> z; |
| 943 | positioned_z(ri, z); |
| 944 | for (int index : z) |
| 945 | if (index < 0) ri->draw_children(0, x, y, nullptr, litehtml::draw_positioned, index); |
| 946 | ri->draw_children(0, x, y, nullptr, litehtml::draw_block, 0); |
| 947 | ri->draw_children(0, x, y, nullptr, litehtml::draw_floats, 0); |
| 948 | ri->draw_children(0, x, y, nullptr, litehtml::draw_inlines, 0); |
| 949 | for (int index : z) |
| 950 | if (index >= 0) ri->draw_children(0, x, y, nullptr, litehtml::draw_positioned, index); |
| 951 | } |
| 952 | #endif |
| 953 | |
| 954 | static void clip_intersect(Rect& a, const Rect& b) { |
| 955 | float x0 = std::max(a.x, b.x), y0 = std::max(a.y, b.y); |
| 956 | float x1 = std::min(a.x + a.w, b.x + b.w), y1 = std::min(a.y + a.h, b.y + b.h); |
| 957 | a = Rect{x0, y0, std::max(0.0f, x1 - x0), std::max(0.0f, y1 - y0)}; |
| 958 | } |
| 959 | |
| 960 | static std::string marker_text(litehtml::list_style_type t, int index) { |
| 961 | auto alpha = [](int n, char base) { |
| 962 | std::string s; |
| 963 | n = std::max(n, 1); |
| 964 | while (n > 0) { n--; s.insert(s.begin(), char(base + n % 26)); n /= 26; } |
| 965 | return s; |
| 966 | }; |
| 967 | auto roman = [](int n, bool upper) { |
| 968 | static const char* U[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", |
| 969 | static const char* L[] = {"m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", |
| 970 | static const int V[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, |
| 971 | std::string s; |
| 972 | n = std::max(n, 1); |
| 973 | for (int i = 0; i < 13; i++) while (n >= V[i]) { s += upper ? U[i] : L[i]; n -= V[i]; } |
| 974 | return s; |
| 975 | }; |
| 976 | switch (t) { |
| 977 | case litehtml::list_style_type_decimal_leading_zero: return (index < 10 ? "0" : "") + std::to_string(index) + "."; |
| 978 | case litehtml::list_style_type_lower_alpha: |
| 979 | case litehtml::list_style_type_lower_latin: return alpha(index, 'a') + "."; |
| 980 | case litehtml::list_style_type_upper_alpha: |
| 981 | case litehtml::list_style_type_upper_latin: return alpha(index, 'A') + "."; |
| 982 | case litehtml::list_style_type_lower_roman: return roman(index, false) + "."; |
| 983 | case litehtml::list_style_type_upper_roman: return roman(index, true) + "."; |
| 984 | default: return std::to_string(index) + "."; |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | Renderer& r_; |
| 989 | Backend& backend_; |
| 990 | litehtml::document::ptr doc_; |
| 991 | #ifdef TW_LITEHTML_TWIDGET |
| 992 | std::vector<litehtml::transform_matrix> groups_; // accumulated, during draw() |
| 993 | #endif |
| 994 | int vp_height_ = int(MIN_HEIGHT); |
| 995 | std::string master_css_; |
| 996 | float rendered_width_ = 0; |
| 997 | uint64_t layouts_ = 0; |
| 998 | bool patched_ = false; |
| 999 | std::unordered_map<int64_t, litehtml::element::ptr> elements_; |
| 1000 | std::unordered_map<litehtml::uint_ptr, Font> fonts_; |
| 1001 | litehtml::uint_ptr next_font_ = 0; |
| 1002 | std::unordered_map<std::string, float> widths_; |
| 1003 | std::unordered_map<std::string, Image> images_; |
| 1004 | int next_image_ = 0; |
| 1005 | DisplayList list_; |
| 1006 | }; |
| 1007 | |
| 1008 | // ───────────────────────── Renderer ───────────────────────── |
| 1009 | |
| 1010 | Renderer::Renderer(double width, double dpr, bool dark, Backend& backend) |
| 1011 | : container_(std::make_unique<Container>(*this, backend)), backend_(backend), width_(width), dpr_(dpr), dark_(dark), vp_height_(int(MIN_HEIGHT)) { |
| 1012 | auto make = [](const char* tag) { |
| 1013 | auto n = std::make_unique<Node>(); |
| 1014 | n->tag = tag; |
| 1015 | return n; |
| 1016 | }; |
| 1017 | html_node_ = make("html"); |
| 1018 | head_node_ = make("head"); |
| 1019 | body_node_ = make("body"); |
| 1020 | head_node_->parent = html_node_.get(); |
| 1021 | body_node_->parent = html_node_.get(); |
| 1022 | html_node_->children = {head_node_.get(), body_node_.get()}; |
| 1023 | // The scheme's defaults until the host's theme message (its first one) replaces them. |
| 1024 | apply_theme(Json::object().set("colorScheme", dark_ ? "dark" : "light")); |
| 1025 | rebuild(); |
| 1026 | } |
| 1027 | |
| 1028 | void Renderer::apply_theme(const Json& theme) { |
| 1029 | theme_ = theme; |
| 1030 | theme_vars_ = theme::variables(theme); |
| 1031 | // The client's chrome over the widget (docs/sdk-v1.md §2.17): always set, 0px until the host's safeArea message. |
| 1032 | if (safe_area_vars_.empty()) safe_area_vars_ = theme::safe_area_variables(Json()); |
| 1033 | theme_vars_.insert(theme_vars_.end(), safe_area_vars_.begin(), safe_area_vars_.end()); |
| 1034 | // The UA layer with the theme's values in place of its var() (litehtml substitutes a var() in a shorthand after the |
| 1035 | // cascade, so `padding: var(…)` from the master CSS would beat the widget's own `padding: 0`) and without :where() |
| 1036 | // (theme.h, unwrap_where). |
| 1037 | container_->set_master(std::string(litehtml::master_css) + UA_EXTRA + theme::unwrap_where(theme::substitute(TW_UA_STYLESHEET, theme_vars_))); |
| 1038 | } |
| 1039 | |
| 1040 | Renderer::~Renderer() { |
| 1041 | for (const auto& [id, canvas] : canvases_) backend_.canvas_release(canvas->id()); |
| 1042 | for (const auto& [css, font] : canvas_fonts_) backend_.delete_font(font.first); |
| 1043 | } |
| 1044 | |
| 1045 | double Renderer::now_s() { return now_ms() / 1000; } |
| 1046 | |
| 1047 | uint32_t Renderer::px_width() const { return uint32_t(std::ceil(width_ * dpr_)); } |
| 1048 | uint32_t Renderer::px_height() const { return uint32_t(std::ceil(vp_height_ * dpr_)); } |
| 1049 | |
| 1050 | std::vector<Json> Renderer::receive(const Json& msg) { |
| 1051 | std::vector<Json> out; |
| 1052 | const std::string& type = msg["type"].asString(); |
| 1053 | if (type == "ops") { |
| 1054 | for (const Json& op : msg["ops"].arr()) apply_op(op, out); |
| 1055 | rebuild(); |
| 1056 | report_size(out); |
| 1057 | } else if (type == "query") { |
| 1058 | Json res = Json::object(); |
| 1059 | binary_.clear(); |
| 1060 | res.set("type", "result").set("qid", msg["qid"]); |
| 1061 | res.set("result", msg.find("query") ? answer(msg["query"]) : Json::object().set("error", "no query")); |
| 1062 | if (!binary_.empty()) res.set("binaryBase64", std::move(binary_)); |
| 1063 | binary_.clear(); |
| 1064 | out.push_back(std::move(res)); |
| 1065 | } else if (type == "anim") { |
| 1066 | if (!frozen_) { |
| 1067 | // `now` is the sandbox clock when the batch was sent: it maps the records' start times onto ours. |
| 1068 | double now = now_ms(); |
| 1069 | animator_.apply_web(msg, now - msg["now"].asNumber(now)); |
| 1070 | animate(); |
| 1071 | report_size(out); |
| 1072 | } |
| 1073 | } else if (type == "listen") { |
| 1074 | interest_.clear(); |
| 1075 | for (const Json& t : msg["types"].arr()) if (t.isString()) interest_.insert(t.asString()); |
| 1076 | } else if (type == "preventDefault") { |
| 1077 | prevent_.clear(); |
| 1078 | for (const Json& k : msg["keys"].arr()) if (k.isString()) prevent_.insert(k.asString()); |
| 1079 | } else if (type == "frozen") { |
| 1080 | freeze(msg["reason"].asString(), msg["fatal"].asBool()); |
| 1081 | rebuild(); |
| 1082 | } else if (type == "theme") { |
| 1083 | apply_theme(msg["theme"]); |
| 1084 | rebuild(); |
| 1085 | report_size(out); |
| 1086 | } else if (type == "safeArea") { |
| 1087 | safe_area_vars_ = theme::safe_area_variables(msg["inset"]); |
| 1088 | apply_theme(Json(theme_)); |
| 1089 | rebuild(); |
| 1090 | report_size(out); |
| 1091 | } |
| 1092 | flush_pending(out); |
| 1093 | return out; |
| 1094 | } |
| 1095 | |
| 1096 | void Renderer::flush_pending(std::vector<Json>& out) { |
| 1097 | for (auto& ev : pending_events_) out.push_back(std::move(ev)); |
| 1098 | pending_events_.clear(); |
| 1099 | for (auto& v : pending_violations_) out.push_back(Json::object().set("type", "violation").set("detail", v)); |
| 1100 | pending_violations_.clear(); |
| 1101 | } |
| 1102 | |
| 1103 | void Renderer::set_width(double width, std::vector<Json>& out) { |
| 1104 | if (std::fabs(width - width_) < 0.01) return; |
| 1105 | width_ = width; |
| 1106 | rebuild(); |
| 1107 | report_size(out); |
| 1108 | } |
| 1109 | |
| 1110 | void Renderer::set_theme(bool dark, std::vector<Json>& out) { |
| 1111 | if (dark == dark_) return; |
| 1112 | dark_ = dark; |
| 1113 | rebuild(); |
| 1114 | report_size(out); |
| 1115 | } |
| 1116 | |
| 1117 | // ───────────────────────── ops ───────────────────────── |
| 1118 | |
| 1119 | Renderer::Node* Renderer::node(int64_t id) const { |
| 1120 | auto it = nodes_.find(id); |
| 1121 | if (it != nodes_.end()) return it->second.get(); |
| 1122 | auto a = aliases_.find(id); |
| 1123 | return a == aliases_.end() ? nullptr : a->second; |
| 1124 | } |
| 1125 | |
| 1126 | void Renderer::apply_op(const Json& op, std::vector<Json>& out) { |
| 1127 | const std::string& kind = op["op"].asString(); |
| 1128 | int64_t id = int64_t(op["id"].asNumber()); |
| 1129 | auto str = [&](const char* k) -> const std::string& { return op[k].asString(); }; |
| 1130 | if (kind == "el") { |
| 1131 | const std::string& adopt_name = str("adopt"); |
| 1132 | if (!adopt_name.empty()) { |
| 1133 | Node* n = adopt_name == "html" ? html_node_.get() : adopt_name == "head" ? head_node_.get() : adopt_name == "body" ? |
| 1134 | if (!n) return; |
| 1135 | adopt(id, n, op["attrs"]); |
| 1136 | return; |
| 1137 | } |
| 1138 | if (nodes_.count(id)) return; // the validator never reuses a live id; keep the first |
| 1139 | auto n = std::make_unique<Node>(); |
| 1140 | n->kind = Node::Element; |
| 1141 | if (!css::is_tag_name(str("tag"))) { |
| 1142 | out.push_back(Json::object().set("type", "violation").set("detail", "element name")); |
| 1143 | return; |
| 1144 | } |
| 1145 | n->id = id; |
| 1146 | n->tag = lower(str("tag")); |
| 1147 | n->svg = op["ns"].asString() == "svg"; |
| 1148 | for (const Json& pair : op["attrs"].arr()) { |
| 1149 | if (!pair[0].isString() || !pair[1].isString()) continue; |
| 1150 | if (starts_with_on(pair[0].asString())) continue; |
| 1151 | if (pair[0].asString() == "style") set_inline_style(n->styles, pair[1].asString()); |
| 1152 | else n->attrs.emplace_back(pair[0].asString(), pair[1].asString()); |
| 1153 | } |
| 1154 | nodes_[id] = std::move(n); |
| 1155 | return; |
| 1156 | } |
| 1157 | if (kind == "text" || kind == "comment") { |
| 1158 | if (nodes_.count(id)) return; |
| 1159 | auto n = std::make_unique<Node>(); |
| 1160 | n->kind = kind == "text" ? Node::Text : Node::Comment; |
| 1161 | n->id = id; |
| 1162 | n->data = str("data"); |
| 1163 | nodes_[id] = std::move(n); |
| 1164 | return; |
| 1165 | } |
| 1166 | Node* n = node(id); |
| 1167 | if (!n) return; |
| 1168 | bool is_root = n == html_node_.get() || n == head_node_.get() || n == body_node_.get(); |
| 1169 | if (kind == "attr") { |
| 1170 | const std::string& name = str("name"); |
| 1171 | if (starts_with_on(name) || !css::is_attribute_name(name)) { |
| 1172 | out.push_back(Json::object().set("type", "violation").set("detail", "attribute " + name.substr(0, 64))); |
| 1173 | return; |
| 1174 | } |
| 1175 | if (name == "style") { |
| 1176 | set_inline_style(n->styles, str("value")); |
| 1177 | return; |
| 1178 | } |
| 1179 | bool found = false; |
| 1180 | for (auto& a : n->attrs) if (a.first == name) { a.second = str("value"); found = true; } |
| 1181 | if (!found) n->attrs.emplace_back(name, str("value")); |
| 1182 | // Setting a canvas's width or height clears its bitmap, as in a browser. |
| 1183 | if (n->tag == "canvas" && (name == "width" || name == "height")) { |
| 1184 | if (auto it = canvases_.find(n->id); it != canvases_.end()) { |
| 1185 | int w = it->second->width(), h = it->second->height(); |
| 1186 | (name == "width" ? w : h) = std::max(0, std::atoi(str("value").c_str())); |
| 1187 | std::vector<CanvasOp> ops; |
| 1188 | it->second->resize(w, h, ops); |
| 1189 | backend_.canvas_run(it->second->id(), it->second->width(), it->second->height(), ops); |
| 1190 | } |
| 1191 | } |
| 1192 | } else if (kind == "rattr") { |
| 1193 | const std::string& name = str("name"); |
| 1194 | if (name == "style") n->styles.clear(); |
| 1195 | n->attrs.erase(std::remove_if(n->attrs.begin(), n->attrs.end(), [&](auto& a) { return a.first == name; }), n->attrs.end()); |
| 1196 | } else if (kind == "data") { |
| 1197 | if (n->kind != Node::Element) n->data = str("data"); |
| 1198 | } else if (kind == "ins") { |
| 1199 | if (is_root) return; |
| 1200 | int64_t parent = int64_t(op["parent"].asNumber()); |
| 1201 | detach(n); |
| 1202 | if (parent == 0) return; |
| 1203 | Node* p = node(parent); |
| 1204 | if (!p || p->kind != Node::Element) return; |
| 1205 | // no cycles: the validator forbids them, but a hostile batch must not hang the renderer |
| 1206 | for (Node* a = p; a; a = a->parent) if (a == n) return; |
| 1207 | n->parent = p; |
| 1208 | const Json* before = op.find("before"); |
| 1209 | if (before && before->isNumber()) { |
| 1210 | Node* b = node(int64_t(before->asNumber())); |
| 1211 | if (b && b->parent == p) { |
| 1212 | auto it = std::find(p->children.begin(), p->children.end(), b); |
| 1213 | p->children.insert(it, n); |
| 1214 | return; |
| 1215 | } |
| 1216 | } |
| 1217 | p->children.push_back(n); |
| 1218 | } else if (kind == "rm") { |
| 1219 | if (is_root) return; |
| 1220 | detach(n); |
| 1221 | forget(n); |
| 1222 | } else if (kind == "style") { |
| 1223 | std::string name = css::starts_with(str("name"), "--") ? str("name") : lower(str("name")); |
| 1224 | // The host's theme variables on the root are not the widget's to change (it can shadow them on its own elements). |
| 1225 | if (n == html_node_.get() && theme::is_variable(name)) return; |
| 1226 | if (!css::is_property_name(name)) { |
| 1227 | out.push_back(Json::object().set("type", "violation").set("detail", "property name")); |
| 1228 | return; |
| 1229 | } |
| 1230 | std::string value = str("value"); |
| 1231 | if (op["important"].asBool() && !value.empty()) value += " !important"; |
| 1232 | auto it = std::find_if(n->styles.begin(), n->styles.end(), [&](auto& s) { return s.first == name; }); |
| 1233 | if (value.empty()) { |
| 1234 | if (it != n->styles.end()) n->styles.erase(it); |
| 1235 | } else if (it != n->styles.end()) it->second = value; |
| 1236 | else n->styles.emplace_back(name, value); |
| 1237 | } else if (kind == "css") { |
| 1238 | if (n->tag == "style") n->data = str("text"); |
| 1239 | } else if (kind == "prop") { |
| 1240 | const std::string& name = str("name"); |
| 1241 | const Json& value = op["value"]; |
| 1242 | auto set_attr = [&](const std::string& a, const std::string& v) { |
| 1243 | for (auto& p : n->attrs) if (p.first == a) { p.second = v; return; } |
| 1244 | n->attrs.emplace_back(a, v); |
| 1245 | }; |
| 1246 | auto remove_attr = [&](const std::string& a) { |
| 1247 | n->attrs.erase(std::remove_if(n->attrs.begin(), n->attrs.end(), [&](auto& p) { return p.first == a; }), n->attrs.end()); |
| 1248 | }; |
| 1249 | if (name == "value") { |
| 1250 | std::string v = value.isString() ? value.asString() : value.isNull() ? std::string() : value.dump(); |
| 1251 | if (n->tag == "textarea") n->data = v, n->children.clear(); |
| 1252 | else set_attr("value", v); |
| 1253 | } else if (name == "checked" || name == "selected" || name == "indeterminate") { |
| 1254 | if (value.asBool()) set_attr(name, ""); else remove_attr(name); |
| 1255 | } else if (name == "selectedIndex") { |
| 1256 | int idx = value.asInt(-1), i = 0; |
| 1257 | for (Node* c : n->children) { |
| 1258 | if (c->tag != "option") continue; |
| 1259 | c->attrs.erase(std::remove_if(c->attrs.begin(), c->attrs.end(), [](auto& p) { return p.first == "selected"; }), c->attrs.end()); |
| 1260 | if (i++ == idx) c->attrs.emplace_back("selected", ""); |
| 1261 | } |
| 1262 | } |
| 1263 | // scrollTop/scrollLeft: litehtml has no scrolling boxes to move |
| 1264 | } else if (kind == "call") { |
| 1265 | const std::string& method = str("method"); |
| 1266 | if (method == "showModal" || method == "show" || method == "showPopover") { |
| 1267 | for (auto& p : n->attrs) if (p.first == "open") return; |
| 1268 | n->attrs.emplace_back("open", ""); |
| 1269 | } else if (method == "close" || method == "hidePopover") { |
| 1270 | n->attrs.erase(std::remove_if(n->attrs.begin(), n->attrs.end(), [](auto& p) { return p.first == "open"; }), n->attrs.end()); |
| 1271 | } |
| 1272 | // focus/blur/scroll*/select*: nothing to do without a focus model or scrolling |
| 1273 | } else if (kind == "canvas") { |
| 1274 | if (n->tag == "canvas" && !n->svg) { |
| 1275 | if (Canvas* canvas = canvas_for(n)) run_canvas(*canvas, op["cmds"]); |
| 1276 | } |
| 1277 | } |
| 1278 | } |
| 1279 | |
| 1280 | void Renderer::adopt(int64_t id, Node* n, const Json& attrs) { |
| 1281 | if (n->id != 0 && n->id != id) aliases_.erase(n->id); |
| 1282 | n->id = id; |
| 1283 | // a non-owning alias: the fixed nodes live in html_node_/head_node_/body_node_ |
| 1284 | nodes_.erase(id); |
| 1285 | aliases_[id] = n; |
| 1286 | for (const Json& pair : attrs.arr()) { |
| 1287 | if (!pair[0].isString() || !pair[1].isString() || starts_with_on(pair[0].asString())) continue; |
| 1288 | if (pair[0].asString() == "style") { |
| 1289 | set_inline_style(n->styles, pair[1].asString()); |
| 1290 | continue; |
| 1291 | } |
| 1292 | bool found = false; |
| 1293 | for (auto& a : n->attrs) if (a.first == pair[0].asString()) { a.second = pair[1].asString(); found = true; } |
| 1294 | if (!found) n->attrs.emplace_back(pair[0].asString(), pair[1].asString()); |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | void Renderer::detach(Node* n) { |
| 1299 | if (!n->parent) return; |
| 1300 | auto& ch = n->parent->children; |
| 1301 | ch.erase(std::remove(ch.begin(), ch.end(), n), ch.end()); |
| 1302 | n->parent = nullptr; |
| 1303 | } |
| 1304 | |
| 1305 | void Renderer::forget(Node* n) { |
| 1306 | forget_canvas(n->id); |
| 1307 | for (Node* c : n->children) { |
| 1308 | c->parent = nullptr; |
| 1309 | forget(c); |
| 1310 | } |
| 1311 | n->children.clear(); |
| 1312 | nodes_.erase(n->id); // deletes n |
| 1313 | } |
| 1314 | |
| 1315 | // ───────────────────────── serialisation ───────────────────────── |
| 1316 | |
| 1317 | void Renderer::serialize_node(const Node* n, std::string& out) const { |
| 1318 | switch (n->kind) { |
| 1319 | case Node::Comment: return; |
| 1320 | case Node::Text: escape_text(n->data, out); return; |
| 1321 | case Node::Element: break; |
| 1322 | } |
| 1323 | if (n->tag == "script" || n->tag == "template") return; // never forwarded by the validator; belt and braces |
| 1324 | if (!css::is_tag_name(n->tag)) return; |
| 1325 | out.push_back('<'); |
| 1326 | out += n->tag; |
| 1327 | if (n->id) { |
| 1328 | out += " data-twid=\""; |
| 1329 | out += std::to_string(n->id); |
| 1330 | out.push_back('"'); |
| 1331 | } |
| 1332 | // The fork lays a <canvas> out as an image: its source is the backend's bitmap. |
| 1333 | const Canvas* canvas = nullptr; |
| 1334 | if (n->tag == "canvas" && !n->svg) { |
| 1335 | if (auto it = canvases_.find(n->id); it != canvases_.end()) canvas = it->second.get(); |
| 1336 | } |
| 1337 | if (canvas) out += " src=\"tw-canvas:" + std::to_string(canvas->id()) + "/" + std::to_string(canvas->width()) + |
| 1338 | bool styled = !n->styles.empty() || overrides_.count(n->id); |
| 1339 | for (const auto& [name, value] : n->attrs) { |
| 1340 | if (name == "style") { styled = true; continue; } |
| 1341 | if ((canvas && name == "src") || !css::is_attribute_name(name)) continue; |
| 1342 | out.push_back(' '); |
| 1343 | out += name; |
| 1344 | out += "=\""; |
| 1345 | escape_attr(value, out); |
| 1346 | out.push_back('"'); |
| 1347 | } |
| 1348 | if (styled) { |
| 1349 | out += " style=\""; |
| 1350 | write_style(n, out); |
| 1351 | out.push_back('"'); |
| 1352 | } |
| 1353 | out.push_back('>'); |
| 1354 | if (!n->svg && is_void(n->tag)) return; |
| 1355 | if (n->tag == "style") { |
| 1356 | std::string css = css::resolve_light_dark(rewrite_color_scheme(n->data, dark_), dark_); |
| 1357 | size_t p = 0; |
| 1358 | while ((p = css.find("</", p)) != std::string::npos) { css.replace(p, 2, "<\\/"); p += 3; } |
| 1359 | out += css; |
| 1360 | } else if (n->tag == "textarea") { |
| 1361 | escape_text(n->data, out); |
| 1362 | for (const Node* c : n->children) serialize_node(c, out); |
| 1363 | } else { |
| 1364 | for (const Node* c : n->children) serialize_node(c, out); |
| 1365 | } |
| 1366 | out += "</"; |
| 1367 | out += n->tag; |
| 1368 | out.push_back('>'); |
| 1369 | } |
| 1370 | |
| 1371 | void Renderer::write_style(const Node* n, std::string& out) const { |
| 1372 | // Built plain, escaped once: the same text is also handed to the fork's style holes, which must |
| 1373 | // match what this writes into the HTML byte for byte. |
| 1374 | std::string plain; |
| 1375 | auto declare = [&](const std::string& name, const std::string& value) { |
| 1376 | if (!plain.empty() && plain.back() != ';') plain.push_back(';'); |
| 1377 | plain += name; |
| 1378 | plain.push_back(':'); |
| 1379 | plain += css::resolve_light_dark(value, dark_); |
| 1380 | }; |
| 1381 | if (n == html_node_.get()) |
| 1382 | for (const auto& [name, value] : theme_vars_) declare(name, value + " !important"); |
| 1383 | for (const auto& [name, value] : n->styles) |
| 1384 | if (css::is_property_name(name)) declare(name, value); |
| 1385 | if (auto it = overrides_.find(n->id); n->id && it != overrides_.end()) { |
| 1386 | // The fork records nothing after this marker as declared, so animated values never feed back |
| 1387 | // into the next scan as the element's own. |
| 1388 | declare("-lh-anim", "1"); |
| 1389 | for (const auto& [name, value] : it->second) |
| 1390 | if (css::is_property_name(name)) declare(name, value); |
| 1391 | } |
| 1392 | escape_attr(plain, out); |
| 1393 | } |
| 1394 | |
| 1395 | std::string Renderer::serialize() const { |
| 1396 | std::string out; |
| 1397 | out.reserve(4096); |
| 1398 | out += "<!DOCTYPE html>"; |
| 1399 | // the frozen chrome: html attribute, badge style in head, badge in body (renderer elements, never in the widget's table) |
| 1400 | const Node* html = html_node_.get(); |
| 1401 | out += "<html"; |
| 1402 | if (html->id) out += " data-twid=\"" + std::to_string(html->id) + "\""; |
| 1403 | if (frozen_) out += frozen_fatal_ ? " data-tw-frozen=\"fatal\"" : " data-tw-frozen=\"paused\""; |
| 1404 | bool styled = !html->styles.empty() || overrides_.count(html->id) || !theme_vars_.empty(); |
| 1405 | for (const auto& [name, value] : html->attrs) { |
| 1406 | if (name == "style") { styled = true; continue; } |
| 1407 | if (!css::is_attribute_name(name)) continue; |
| 1408 | out += " " + name + "=\""; |
| 1409 | escape_attr(value, out); |
| 1410 | out.push_back('"'); |
| 1411 | } |
| 1412 | if (styled) { |
| 1413 | out += " style=\""; |
| 1414 | write_style(html, out); |
| 1415 | out.push_back('"'); |
| 1416 | } |
| 1417 | out.push_back('>'); |
| 1418 | for (const Node* c : html->children) { |
| 1419 | if (c == body_node_.get() && frozen_) { |
| 1420 | // badge before the body's own children would shift them; append it inside instead |
| 1421 | std::string body; |
| 1422 | serialize_node(c, body); |
| 1423 | size_t close = body.rfind("</body>"); |
| 1424 | if (close != std::string::npos) { |
| 1425 | std::string badge = "<div data-tw-badge=\"" + std::string(frozen_fatal_ ? "fatal" : "paused") + "\">"; |
| 1426 | escape_text(frozen_reason_, badge); |
| 1427 | badge += "</div>"; |
| 1428 | body.insert(close, badge); |
| 1429 | } |
| 1430 | out += body; |
| 1431 | } else if (c == head_node_.get() && frozen_) { |
| 1432 | std::string head; |
| 1433 | serialize_node(c, head); |
| 1434 | size_t close = head.rfind("</head>"); |
| 1435 | const char* css = "<style>[data-tw-frozen=fatal] body{opacity:.85}[data-tw-badge]{position:fixed;right:6px;bottom:6px;z-index:2147483647;font:11px/1.3 -apple-system,system-ui,sans-serif;color:#fff;background:rgba(60,60,60,.75);padding:2px 7px;border-radius:9px}</style>"; |
| 1436 | if (close != std::string::npos) head.insert(close, css); |
| 1437 | out += head; |
| 1438 | } else { |
| 1439 | serialize_node(c, out); |
| 1440 | } |
| 1441 | } |
| 1442 | out += "</html>"; |
| 1443 | return out; |
| 1444 | } |
| 1445 | |
| 1446 | void Renderer::rebuild() { |
| 1447 | build_document(); |
| 1448 | animate(); |
| 1449 | } |
| 1450 | |
| 1451 | void Renderer::build_document() { |
| 1452 | double t0 = now_ms(); |
| 1453 | html_ = serialize(); |
| 1454 | double t1 = now_ms(); |
| 1455 | stats_.serialize_ms = t1 - t0; |
| 1456 | stats_.html_bytes = html_.size(); |
| 1457 | stats_.parse_ms = 0; |
| 1458 | stats_.passes = 0; |
| 1459 | // Like the web iframe: the viewport follows the document height (100vh must not explode), converging in a few passes. |
| 1460 | for (int pass = 0; pass < MAX_PASSES; pass++) { |
| 1461 | double a = now_ms(); |
| 1462 | container_->build(html_, vp_height_); |
| 1463 | double b = now_ms(); |
| 1464 | stats_.parse_ms += b - a; // litehtml lays out inside createFromString+render; not separable |
| 1465 | stats_.passes++; |
| 1466 | if (pass == 0 && container_->patched()) stats_.patched++; |
| 1467 | int h = int(std::ceil(std::clamp(container_->height(), MIN_HEIGHT, MAX_HEIGHT))); |
| 1468 | if (h == vp_height_) break; |
| 1469 | vp_height_ = h; |
| 1470 | } |
| 1471 | doc_height_ = std::ceil(container_->height()); |
| 1472 | stats_.builds++; |
| 1473 | dirty_ = true; |
| 1474 | } |
| 1475 | |
| 1476 | // ───────────────────────── animations ───────────────────────── |
| 1477 | |
| 1478 | void Renderer::animate() { |
| 1479 | #ifdef TW_LITEHTML_TWIDGET |
| 1480 | if (animating_ || frozen_) return; |
| 1481 | animating_ = true; |
| 1482 | double now = now_s(); |
| 1483 | std::vector<std::string> sheets; |
| 1484 | std::string key; |
| 1485 | std::function<void(const Node*)> visit = [&](const Node* n) { |
| 1486 | if (n->kind != Node::Element) return; |
| 1487 | if (n->tag == "style") { |
| 1488 | sheets.push_back(css::resolve_light_dark(rewrite_color_scheme(n->data, dark_), dark_)); |
| 1489 | key += sheets.back(); |
| 1490 | key.push_back('\x01'); |
| 1491 | return; |
| 1492 | } |
| 1493 | for (const Node* c : n->children) visit(c); |
| 1494 | }; |
| 1495 | visit(html_node_.get()); |
| 1496 | if (key != sheets_key_) { |
| 1497 | sheets_key_ = std::move(key); |
| 1498 | animator_.set_style_sheets(sheets); |
| 1499 | } |
| 1500 | animator_.prune([this](int64_t id) { return node(id) != nullptr; }); |
| 1501 | auto declarations = container_->declarations(Animator::watched(), Animator::entry_properties(), {}); |
| 1502 | animator_.underlying.clear(); |
| 1503 | auto targets = animator_.web_targets(); |
| 1504 | if (!targets.empty()) { |
| 1505 | // Web Animations targets are read whatever they declare: their keyframes compose onto these values. |
| 1506 | std::vector<std::string> names = Animator::watched(); |
| 1507 | for (int64_t id : targets) |
| 1508 | for (const std::string& p : animator_.web_properties(id)) |
| 1509 | if (std::find(names.begin(), names.end(), p) == names.end()) names.push_back(p); |
| 1510 | for (auto& [id, values] : container_->declarations(names, {}, targets)) { |
| 1511 | auto& declared = declarations[id]; |
| 1512 | for (const auto& [k, v] : values) |
| 1513 | if (!css::starts_with(k, "animation") && !css::starts_with(k, "transition")) declared.emplace(k, v); |
| 1514 | animator_.underlying[id] = std::move(values); |
| 1515 | } |
| 1516 | } |
| 1517 | animator_.update(declarations, now); |
| 1518 | update_composition(now); |
| 1519 | auto sampled = animator_.sample(now); |
| 1520 | strip_layers(sampled); |
| 1521 | queue_animation_events(); |
| 1522 | if (sampled != overrides_) { |
| 1523 | overrides_ = std::move(sampled); |
| 1524 | build_document(); |
| 1525 | } |
| 1526 | animating_ = false; |
| 1527 | #endif |
| 1528 | } |
| 1529 | |
| 1530 | void Renderer::apply_overrides(StyleOverrides sampled) { |
| 1531 | if (sampled == overrides_) return; |
| 1532 | std::vector<int64_t> changed; |
| 1533 | for (const auto& [id, values] : sampled) { |
| 1534 | auto it = overrides_.find(id); |
| 1535 | if (it == overrides_.end() || it->second != values) changed.push_back(id); |
| 1536 | } |
| 1537 | for (const auto& [id, values] : overrides_) |
| 1538 | if (!sampled.count(id)) changed.push_back(id); |
| 1539 | overrides_ = std::move(sampled); |
| 1540 | #ifdef TW_LITEHTML_TWIDGET |
| 1541 | // An animation frame changes style attributes only: patch them in place instead of serialising |
| 1542 | // the whole tree. Falls back to a build when an element has no style attribute yet, or the |
| 1543 | // document height moved. |
| 1544 | std::vector<std::pair<litehtml::element::ptr, std::string>> patches; |
| 1545 | bool ok = true; |
| 1546 | for (int64_t id : changed) { |
| 1547 | const Node* n = node(id); |
| 1548 | auto el = container_->element(id); |
| 1549 | if (!n || !el) { |
| 1550 | ok = false; |
| 1551 | break; |
| 1552 | } |
| 1553 | std::string style; |
| 1554 | write_style(n, style); |
| 1555 | patches.emplace_back(std::move(el), std::move(style)); |
| 1556 | } |
| 1557 | double t0 = now_ms(); |
| 1558 | if (ok && container_->restyle(patches)) { |
| 1559 | int h = int(std::ceil(std::clamp(container_->height(), MIN_HEIGHT, MAX_HEIGHT))); |
| 1560 | if (h == vp_height_) { |
| 1561 | doc_height_ = std::ceil(container_->height()); |
| 1562 | stats_.parse_ms = now_ms() - t0; |
| 1563 | stats_.serialize_ms = 0; |
| 1564 | stats_.passes = 1; |
| 1565 | stats_.builds++; |
| 1566 | stats_.patched++; |
| 1567 | dirty_ = true; |
| 1568 | return; |
| 1569 | } |
| 1570 | } |
| 1571 | #endif |
| 1572 | build_document(); |
| 1573 | } |
| 1574 | |
| 1575 | void Renderer::queue_animation_events() { |
| 1576 | for (const AnimationEvent& e : animator_.take_events()) { |
| 1577 | if (frozen_ || !interest_.count(e.type)) continue; |
| 1578 | Json ev = Json::object(); |
| 1579 | ev.set("type", e.type).set("targetId", double(e.target)); |
| 1580 | ev.set(e.type == "transitionend" ? "propertyName" : "animationName", e.name); |
| 1581 | ev.set("elapsedTime", e.elapsed); |
| 1582 | pending_events_.push_back(Json::object().set("type", "event").set("ev", std::move(ev))); |
| 1583 | } |
| 1584 | } |
| 1585 | |
| 1586 | std::vector<Json> Renderer::tick() { |
| 1587 | std::vector<Json> out; |
| 1588 | flush_moves(out); |
| 1589 | double now = now_s(); |
| 1590 | if (!frozen_ && (animator_.active(now) || now >= wake_at_)) { |
| 1591 | update_composition(now); |
| 1592 | auto sampled = animator_.sample(now); |
| 1593 | strip_layers(sampled); |
| 1594 | queue_animation_events(); |
| 1595 | apply_overrides(std::move(sampled)); |
| 1596 | report_size(out); |
| 1597 | } |
| 1598 | flush_pending(out); |
| 1599 | return out; |
| 1600 | } |
| 1601 | |
| 1602 | bool Renderer::wants_tick() const { |
| 1603 | return !frozen_ && (!pending_moves_.empty() || animator_.active(now_s(), layer_ids_)); |
| 1604 | } |
| 1605 | |
| 1606 | double Renderer::next_tick_in() const { |
| 1607 | if (frozen_) return std::numeric_limits<double>::infinity(); |
| 1608 | return std::max(0.0, wake_at_ - now_s()); |
| 1609 | } |
| 1610 | |
| 1611 | // ───────────────────────── compositor layers ───────────────────────── |
| 1612 | |
| 1613 | void Renderer::set_compositing(bool enabled) { |
| 1614 | if (enabled == compositing_) return; |
| 1615 | compositing_ = enabled; |
| 1616 | composition_key_ = 0; |
| 1617 | rebuild(); |
| 1618 | } |
| 1619 | |
| 1620 | void Renderer::strip_layers(StyleOverrides& sampled) const { |
| 1621 | for (int64_t id : layer_ids_) { |
| 1622 | auto it = sampled.find(id); |
| 1623 | if (it == sampled.end()) continue; |
| 1624 | auto& values = it->second; |
| 1625 | values.erase(std::remove_if(values.begin(), values.end(), [](const auto& v) { return is_layer_property(v.first); }), values.end()); |
| 1626 | if (values.empty()) sampled.erase(it); |
| 1627 | } |
| 1628 | } |
| 1629 | |
| 1630 | void Renderer::update_composition(double now) { |
| 1631 | wake_at_ = std::numeric_limits<double>::infinity(); |
| 1632 | auto drop_all = [&] { |
| 1633 | if (promoted_.empty()) return; |
| 1634 | promoted_.clear(); |
| 1635 | layer_ids_.clear(); |
| 1636 | composition_key_ = 0; |
| 1637 | dirty_ = true; |
| 1638 | }; |
| 1639 | #ifdef TW_LITEHTML_TWIDGET |
| 1640 | if (!compositing_ || frozen_) return drop_all(); |
| 1641 | struct Want { |
| 1642 | litehtml::element::ptr el; |
| 1643 | Animator::Plan plan; |
| 1644 | Rect box; |
| 1645 | uint64_t signature; |
| 1646 | }; |
| 1647 | std::vector<std::pair<int64_t, Want>> wanted; |
| 1648 | bool iterations = interest_.count("animationiteration") > 0; |
| 1649 | auto ids = animator_.animated_ids(now); |
| 1650 | uint64_t key = container_->layouts() * 0x9E3779B97F4A7C15ull ^ std::hash<double>()(width_); |
| 1651 | for (int64_t id : ids) { |
| 1652 | auto plan = animator_.plan(id, now, iterations); |
| 1653 | if (!plan) continue; |
| 1654 | wake_at_ = std::min(wake_at_, plan->wake); |
| 1655 | if (!plan->ready || (!plan->repeat && plan->duration < MIN_LAYER_SPAN)) continue; |
| 1656 | auto properties = animator_.animated_properties(id); |
| 1657 | if (!std::all_of(properties.begin(), properties.end(), [](const std::string& p) { return is_layer_property(p); })) continue; |
| 1658 | const Node* n = node(id); |
| 1659 | auto el = container_->element(id); |
| 1660 | Rect box; |
| 1661 | if (!n || n->svg || n->tag == "svg" || !el || !container_->layer_candidate(el, box)) continue; |
| 1662 | // A layer holds a still picture: nothing inside or around it may animate. |
| 1663 | if (std::any_of(ids.begin(), ids.end(), [&](int64_t other) { return other != id && (is_ancestor(other, id) || is_ancestor(id, other)); })) continue |
| 1664 | uint64_t signature = animator_.signature(id); |
| 1665 | key = (key * 1099511628211ull) ^ uint64_t(id) ^ (signature << 1) ^ uint64_t(plan->repeat); |
| 1666 | wanted.emplace_back(id, Want{std::move(el), *plan, box, signature}); |
| 1667 | } |
| 1668 | if (wanted.empty()) return drop_all(); |
| 1669 | if (key == composition_key_) return; |
| 1670 | composition_key_ = key; |
| 1671 | |
| 1672 | std::map<int64_t, Promotion> next; |
| 1673 | std::unordered_map<int64_t, litehtml::element::ptr> elements; |
| 1674 | for (auto& [id, want] : wanted) { |
| 1675 | Promotion p; |
| 1676 | p.box = want.box; |
| 1677 | p.signature = want.signature; |
| 1678 | if (!container_->clip_of(want.el, p.has_clip, p.clip, p.clip_radii)) continue; |
| 1679 | // A running track stays when nothing about it changed, and while it still covers what the |
| 1680 | // animations will do: the end of a one-shot track, or the same loop. |
| 1681 | auto old = promoted_.find(id); |
| 1682 | bool same_span = old != promoted_.end() && |
| 1683 | (want.plan.repeat ? old->second.track.repeat && std::fabs(old->second.track.duration - want.plan.duration) < 1e-6 |
| 1684 | : !old->second.track.repeat && std::fabs(old->second.track.start + old->second.track.duration - (want.plan.start + want.plan.duration)) < 1e-3); |
| 1685 | if (same_span && old->second.signature == want.signature && std::memcmp(&old->second.box, &want.box, sizeof(Rect)) == 0) { |
| 1686 | p.track = old->second.track; |
| 1687 | p.track_version = old->second.track_version; |
| 1688 | } else { |
| 1689 | const Rect& box = want.box; |
| 1690 | auto origin = css::parse_origin(animator_.base_value(id, "transform-origin"), box.w, box.h); |
| 1691 | if (!origin) continue; |
| 1692 | Affine to = Affine::translate(box.x + origin->first, box.y + origin->second); |
| 1693 | Affine from = Affine::translate(-(box.x + origin->first), -(box.y + origin->second)); |
| 1694 | const Animator::Plan& plan = want.plan; |
| 1695 | int64_t target = id; |
| 1696 | auto sample = [&](double t, LayerKey& out) { |
| 1697 | StyleValues values = animator_.peek(target, plan.start + t * plan.duration); |
| 1698 | auto value = [&](const char* property) { |
| 1699 | for (auto it = values.rbegin(); it != values.rend(); ++it) |
| 1700 | if (it->first == property) return it->second; |
| 1701 | return animator_.base_value(target, property); |
| 1702 | }; |
| 1703 | auto translate = css::parse_translate(value("translate"), box.w, box.h); |
| 1704 | auto rotate = css::parse_rotate(value("rotate")); |
| 1705 | auto scale = css::parse_scale(value("scale")); |
| 1706 | auto transform = css::parse_transform(value("transform"), box.w, box.h); |
| 1707 | auto opacity = css::parse_opacity(value("opacity")); |
| 1708 | if (!translate || !rotate || !scale || !transform || !opacity) return false; |
| 1709 | out.matrix = to * *translate * *rotate * *scale * *transform * from; |
| 1710 | out.opacity = *opacity; |
| 1711 | return true; |
| 1712 | }; |
| 1713 | p.track.start = plan.start; |
| 1714 | p.track.duration = plan.duration; |
| 1715 | p.track.repeat = plan.repeat; |
| 1716 | if (!bake_track(sample, box, p.track.keys)) continue; |
| 1717 | p.track_version = next_version_++; |
| 1718 | } |
| 1719 | // What the layer can cover, and how fine to rasterise it. |
| 1720 | float x0 = 1e30f, y0 = 1e30f, x1 = -1e30f, y1 = -1e30 |
| 1721 | for (const LayerKey& k : p.track.keys) { |
| 1722 | const float corners[4][2] = {{p.box.x, p.box.y}, {p.box.x + p.box.w, p.box.y}, {p.box.x, p.box.y + p.box.h}, {p.box.x + p.box.w, p.box.y + p.box.h}}; |
| 1723 | for (const auto& c : corners) { |
| 1724 | float x = k.matrix.apply_x(c[0], c[1]), y = k.matrix.apply_y(c[0], c[1]); |
| 1725 | x0 = std::min(x0, x); y0 = std::min(y0, y); x1 = std::max(x1, x); y1 = std::max(y1, y); |
| 1726 | } |
| 1727 | scale = std::max(scale, std::sqrt(std::fabs(k.matrix.a * k.matrix.d - k.matrix.b * k.matrix.c))); |
| 1728 | } |
| 1729 | p.raster_scale = std::min(scale, 3.0f); |
| 1730 | p.reach = Rect{x0, y0, x1 - x0, y1 - y0}; |
| 1731 | if (p.has_clip) { |
| 1732 | float cx0 = std::max(p.reach.x, p.clip.x), cy0 = std::max(p.reach.y, p.clip.y); |
| 1733 | float cx1 = std::min(p.reach.x + p.reach.w, p.clip.x + p.clip.w), cy1 = std::min(p.reach.y + p.reach.h, p.clip.y + p.clip.h); |
| 1734 | p.reach = Rect{cx0, cy0, std::max(0.0f, cx1 - cx0), std::max(0.0f, cy1 - cy0)}; |
| 1735 | } |
| 1736 | elements[id] = want.el; |
| 1737 | next.emplace(id, std::move(p)); |
| 1738 | } |
| 1739 | |
| 1740 | // Only a layer nothing paints over can go above the document. Dropping one can uncover |
| 1741 | // another's neighbour, so this settles over a few rounds. |
| 1742 | auto trace = container_->paint_order(); |
| 1743 | for (int round = 0; round < 4 && !next.empty(); round++) { |
| 1744 | std::unordered_set<const litehtml::element*> ignore; |
| 1745 | for (const auto& [id, p] : next) ignore.insert(elements[id].get()); |
| 1746 | std::vector<std::pair<int64_t, double>> uncovered; |
| 1747 | for (const auto& [id, p] : next) { |
| 1748 | if (p.reach.empty() || container_->covered(elements[id], p.reach, trace, ignore)) continue; |
| 1749 | double s = dpr_ * p.raster_scale; |
| 1750 | uncovered.emplace_back(id, double(p.box.w + 2 * LAYER_MARGIN) * (p.box.h + 2 * LAYER_MARGIN) * s * s); |
| 1751 | } |
| 1752 | std::sort(uncovered.begin(), uncovered.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); |
| 1753 | std::map<int64_t, Promotion> admitted; |
| 1754 | double pixels = 0; |
| 1755 | for (const auto& [id, cost] : uncovered) { |
| 1756 | if (admitted.size() >= MAX_LAYERS || pixels + cost > MAX_LAYER_PIXELS) continue; |
| 1757 | pixels += cost; |
| 1758 | admitted.emplace(id, std::move(next[id])); |
| 1759 | } |
| 1760 | bool stable = admitted.size() == next.size(); |
| 1761 | next = std::move(admitted); |
| 1762 | if (stable) break; |
| 1763 | } |
| 1764 | for (auto& [id, p] : next) { |
| 1765 | auto ri = elements[id]->get_render_item(); |
| 1766 | p.order = size_t(std::find(trace.begin(), trace.end(), ri.get()) - trace.begin()); |
| 1767 | } |
| 1768 | |
| 1769 | bool changed = next.size() != promoted_.size(); |
| 1770 | for (const auto& [id, p] : next) { |
| 1771 | auto old = promoted_.find(id); |
| 1772 | changed = changed || old == promoted_.end() || old->second.track_version != p.track_version || old->second.order != p.order || |
| 1773 | std::memcmp(&old->second.box, &p.box, sizeof(Rect)) != 0; |
| 1774 | } |
| 1775 | promoted_ = std::move(next); |
| 1776 | layer_ids_.clear(); |
| 1777 | for (const auto& [id, p] : promoted_) layer_ids_.insert(id); |
| 1778 | if (changed) dirty_ = true; |
| 1779 | #else |
| 1780 | (void)now; |
| 1781 | drop_all(); |
| 1782 | #endif |
| 1783 | } |
| 1784 | |
| 1785 | // ───────────────────────── canvas ───────────────────────── |
| 1786 | |
| 1787 | Canvas* Renderer::canvas_for(Node* n) { |
| 1788 | if (auto it = canvases_.find(n->id); it != canvases_.end()) return it->second.get(); |
| 1789 | if (canvases_.size() >= MAX_CANVASES) return nullptr; |
| 1790 | auto size = [&](const char* name, int fallback) { |
| 1791 | for (const auto& [k, v] : n->attrs) { |
| 1792 | std::string t = css::trim(v); |
| 1793 | if (k == name && !t.empty() && std::isdigit((unsigned char)t[0])) return std::atoi(t.c_str()); |
| 1794 | } |
| 1795 | return fallback; |
| 1796 | }; |
| 1797 | auto canvas = std::make_unique<Canvas>(int(n->id), size("width", 300), size("height", 150), static_cast<CanvasHost&>(* |
| 1798 | Canvas* raw = canvas.get(); |
| 1799 | canvases_[n->id] = std::move(canvas); |
| 1800 | CanvasOp reset; |
| 1801 | reset.kind = CanvasOp::Reset; |
| 1802 | backend_.canvas_run(raw->id(), raw->width(), raw->height(), {reset}); |
| 1803 | return raw; |
| 1804 | } |
| 1805 | |
| 1806 | void Renderer::run_canvas(Canvas& canvas, const Json& cmds) { |
| 1807 | // Fonts are held across one batch at most, so a widget cycling through font strings cannot grow this. |
| 1808 | if (canvas_fonts_.size() > 64) { |
| 1809 | for (const auto& [font_css, font] : canvas_fonts_) backend_.delete_font(font.first); |
| 1810 | canvas_fonts_.clear(); |
| 1811 | } |
| 1812 | std::vector<CanvasOp> ops; |
| 1813 | canvas.run(cmds, ops); |
| 1814 | if (ops.empty()) return; |
| 1815 | backend_.canvas_run(canvas.id(), canvas.width(), canvas.height(), ops); |
| 1816 | dirty_ = true; |
| 1817 | } |
| 1818 | |
| 1819 | void Renderer::forget_canvas(int64_t id) { |
| 1820 | auto it = canvases_.find(id); |
| 1821 | if (it == canvases_.end()) return; |
| 1822 | backend_.canvas_release(it->second->id()); |
| 1823 | canvases_.erase(it); |
| 1824 | } |
| 1825 | |
| 1826 | int Renderer::canvas_font(const std::string& font, FontMetrics& metrics) { |
| 1827 | if (auto it = canvas_fonts_.find(font); it != canvas_fonts_.end()) { |
| 1828 | metrics = it->second.second; |
| 1829 | return it->second.first; |
| 1830 | } |
| 1831 | css::Font f = css::parse_font(font); |
| 1832 | int handle = backend_.create_font(f.family, f.size, f.weight, f.italic, metrics); |
| 1833 | if (handle) canvas_fonts_.emplace(font, std::make_pair(handle, metrics)); |
| 1834 | return handle; |
| 1835 | } |
| 1836 | |
| 1837 | float Renderer::canvas_text_width(int font, const std::string& text) { return backend_.text_width(font, text); } |
| 1838 | |
| 1839 | bool Renderer::canvas_source(int64_t id, int& image, int& canvas, float& w, float& h) { |
| 1840 | if (auto it = canvases_.find(id); it != canvases_.end()) { |
| 1841 | canvas = it->second->id(); |
| 1842 | w = float(it->second->width()); |
| 1843 | h = float(it->second->height()); |
| 1844 | return true; |
| 1845 | } |
| 1846 | const Node* n = node(id); |
| 1847 | if (!n || n->tag != "img") return false; |
| 1848 | for (const auto& [k, v] : n->attrs) |
| 1849 | if (k == "src" && v.rfind("data:", 0) == 0) return container_->image_of(v, image, w, h); |
| 1850 | return false; |
| 1851 | } |
| 1852 | |
| 1853 | int64_t Renderer::canvas_allowance(int id) { |
| 1854 | int64_t used = 0; |
| 1855 | for (const auto& [node_id, canvas] : canvases_) |
| 1856 | if (canvas->id() != id) used += canvas->pixels(); |
| 1857 | return Canvas::MAX_PIXELS - used; |
| 1858 | } |
| 1859 | |
| 1860 | void Renderer::report_size(std::vector<Json>& out) { |
| 1861 | Json msg = Json::object(); |
| 1862 | msg.set("type", "size").set("width", width_).set("height", doc_height_); |
| 1863 | msg.set("innerWidth", width_).set("innerHeight", vp_height_).set("dpr", dpr_); |
| 1864 | std::string key = msg.dump(); |
| 1865 | if (key != last_size_) { |
| 1866 | last_size_ = key; |
| 1867 | out.push_back(std::move(msg)); |
| 1868 | } |
| 1869 | } |
| 1870 | |
| 1871 | DisplayList Renderer::paint() { |
| 1872 | dirty_ = false; |
| 1873 | #ifdef TW_LITEHTML_TWIDGET |
| 1874 | if (!promoted_.empty() || !composition_.layers.empty()) { |
| 1875 | std::vector<std::pair<size_t, int64_t>> order; |
| 1876 | std::vector<litehtml::element::ptr> skip; |
| 1877 | for (const auto& [id, p] : promoted_) { |
| 1878 | if (auto el = container_->element(id)) { |
| 1879 | order.emplace_back(p.order, id); |
| 1880 | skip.push_back(std::move(el)); |
| 1881 | } |
| 1882 | } |
| 1883 | DisplayList list = container_->draw(skip); |
| 1884 | std::sort(order.begin(), order.end()); |
| 1885 | Composition next; |
| 1886 | bool changed = order.size() != composition_.layers.size(); |
| 1887 | for (const auto& [index, id] : order) { |
| 1888 | const Promotion& p = promoted_.at(id); |
| 1889 | Layer layer; |
| 1890 | layer.id = id; |
| 1891 | layer.content = container_->draw_layer(container_->element(id), skip, layer.bounds); |
| 1892 | // A canvas repaints without its command changing: such a layer is always new. |
| 1893 | bool canvas = std::any_of(layer.content.begin(), layer.content.end(), [](const Command& c) { return c.canvas != 0; }); |
| 1894 | layer.content_version = canvas ? next_version_++ : paint_digest(layer.content); |
| 1895 | layer.raster_scale = p.raster_scale; |
| 1896 | layer.has_clip = p.has_clip; |
| 1897 | layer.clip = p.clip; |
| 1898 | layer.clip_radii = p.clip_radii; |
| 1899 | layer.track_version = p.track_version; |
| 1900 | layer.track = p.track; |
| 1901 | size_t i = next.layers.size(); |
| 1902 | if (!changed) { |
| 1903 | const Layer& old = composition_.layers[i]; |
| 1904 | changed = old.id != id || old.content_version != layer.content_version || old.track_version != layer.track_version || |
| 1905 | std::memcmp(&old.bounds, &layer.bounds, sizeof(Rect)) != 0 || old.has_clip != layer.has_clip || |
| 1906 | std::memcmp(&old.clip, &layer.clip, sizeof(Rect)) != 0 || std::memcmp(&old.clip_radii, &layer.clip_radii, sizeof(Radii)) != 0 |
| 1907 | } |
| 1908 | next.layers.push_back(std::move(layer)); |
| 1909 | } |
| 1910 | next.version = changed ? next_version_++ : composition_.version; |
| 1911 | composition_ = std::move(next); |
| 1912 | return list; |
| 1913 | } |
| 1914 | #endif |
| 1915 | return container_->draw(); |
| 1916 | } |
| 1917 | |
| 1918 | // ───────────────────────── queries ───────────────────────── |
| 1919 | |
| 1920 | Json Renderer::answer(const Json& q) { |
| 1921 | const std::string& kind = q["q"].asString(); |
| 1922 | litehtml::element::ptr el; |
| 1923 | const Node* shadow = nullptr; |
| 1924 | if (q.find("id")) { |
| 1925 | int64_t id = int64_t(q["id"].asNumber()); |
| 1926 | shadow = node(id); |
| 1927 | el = container_->element(id); |
| 1928 | if (!shadow || shadow->kind != Node::Element) return Json::object().set("error", "no such element"); |
| 1929 | } |
| 1930 | auto placement = [&]() -> Rect { return el ? border_box_of(el) : Rect{}; }; |
| 1931 | if (kind == "rect") return rect_json(placement()); |
| 1932 | if (kind == "rects") return el ? Json::array().push(rect_json(placement())) : Json::array(); |
| 1933 | if (kind == "box") { |
| 1934 | Rect r = placement(); |
| 1935 | float bl = 0, bt = 0, br = 0, bb = 0; |
| 1936 | if (auto ri = el ? el->get_render_item() : nullptr) { |
| 1937 | const auto& bd = ri->get_borders(); |
| 1938 | bl = float(bd.left); bt = float(bd.top); br = float(bd.right); bb = float(bd.bottom); |
| 1939 | } |
| 1940 | int64_t parent = shadow && shadow->parent ? shadow->parent->id : 0; |
| 1941 | Json o = Json::object(); |
| 1942 | o.set("offsetWidth", r.w).set("offsetHeight", r.h).set("offsetTop", r.y).set("offsetLeft", r.x).set("offsetParent", double(parent)); |
| 1943 | o.set("clientWidth", std::max(0.0f, r.w - bl - br)).set("clientHeight", std::max(0.0f, r.h - bt - bb)). |
| 1944 | o.set("scrollWidth", std::max(0.0f, r.w - bl - br)).set("scrollHeight", std::max(0.0f, r.h - bt - bb)). |
| 1945 | return o; |
| 1946 | } |
| 1947 | if (kind == "cs") { |
| 1948 | // litehtml keeps resolved values as typed fields; the handful widgets read most are answered, the rest is "". |
| 1949 | Json o = Json::object(); |
| 1950 | if (el) { |
| 1951 | const auto& css = el->css(); |
| 1952 | const char* display = "block"; |
| 1953 | switch (css.get_display()) { |
| 1954 | case litehtml::display_none: display = "none"; break; |
| 1955 | case litehtml::display_inline: display = "inline"; break; |
| 1956 | case litehtml::display_inline_block: display = "inline-block"; break; |
| 1957 | case litehtml::display_flex: display = "flex"; break; |
| 1958 | case litehtml::display_inline_flex: display = "inline-flex"; break; |
| 1959 | case litehtml::display_table: display = "table"; break; |
| 1960 | case litehtml::display_list_item: display = "list-item"; break; |
| 1961 | default: break; |
| 1962 | } |
| 1963 | auto color = [](const litehtml::web_color& c) { |
| 1964 | char buf[48]; |
| 1965 | std::snprintf(buf, sizeof buf, "rgba(%d, %d, %d, %g)", c.red, c.green, c.blue, c.alpha / 255.0); |
| 1966 | return std::string(buf); |
| 1967 | }; |
| 1968 | Rect r = placement(); |
| 1969 | o.set("display", display); |
| 1970 | o.set("visibility", css.get_visibility() == litehtml::visibility_hidden ? "hidden" : "visible"); |
| 1971 | o.set("color", color(css.get_color())); |
| 1972 | o.set("background-color", color(css.get_bg().m_color)); |
| 1973 | o.set("font-size", std::to_string(int(css.get_font_size())) + "px"); |
| 1974 | o.set("width", std::to_string(r.w) + "px").set("height", std::to_string(r.h) + "px"); |
| 1975 | } |
| 1976 | if (q.find("prop")) { |
| 1977 | const Json* v = o.find(q["prop"].asString()); |
| 1978 | return v ? *v : Json(""); |
| 1979 | } |
| 1980 | return o; |
| 1981 | } |
| 1982 | if (kind == "elementFromPoint") return double(widget_id_at(q["x"].asNumber(), q["y"].asNumber(), nullptr)); |
| 1983 | if (kind == "measureText") return container_->measure_text(q["font"].isString() ? q["font"].asString() : "10px sans-serif", q["text"].asString()); |
| 1984 | if (kind == "validity") return Json::object().set("valid", true).set("message", ""); |
| 1985 | if (kind == "matchMedia") return Json::object().set("matches", match_media(q["query"].asString())); |
| 1986 | if (kind == "viewport") return Json::object().set("innerWidth", width_).set("innerHeight", double(vp_height_)).set("dpr", dpr_); |
| 1987 | if (kind == "anims") { |
| 1988 | std::vector<int64_t> ids; |
| 1989 | if (shadow) { |
| 1990 | std::function<void(const Node*)> visit = [&](const Node* n) { |
| 1991 | if (n->id && ids.size() < 100000) ids.push_back(n->id); |
| 1992 | if (q["subtree"].asBool()) |
| 1993 | for (const Node* c : n->children) visit(c); |
| 1994 | }; |
| 1995 | visit(shadow); |
| 1996 | } |
| 1997 | return Json::object().set("list", animator_.css_animations(ids, now_s())); |
| 1998 | } |
| 1999 | if (kind == "imageData") { |
| 2000 | int w = std::clamp(q["w"].asInt(), 0, Canvas::MAX_SIDE), h = std::clamp(q["h"].asInt(), 0, Canvas::MAX_SIDE); |
| 2001 | if (int64_t(w) * h > Canvas::MAX_PIXELS) return Json::object().set("error", "too large"); |
| 2002 | std::vector<uint8_t> rgba; |
| 2003 | auto it = shadow ? canvases_.find(shadow->id) : canvases_.end(); |
| 2004 | if (it == canvases_.end() || !backend_.canvas_read(it->second->id(), q["x"].asInt(), q["y"].asInt(), w, h, rgba) || rgba.size() != size_t |
| 2005 | rgba.assign(size_t(w) * h * 4, 0); |
| 2006 | binary_ = base64_encode(rgba); |
| 2007 | return Json::object().set("width", w).set("height", h); |
| 2008 | } |
| 2009 | if (kind == "canvasCall") { |
| 2010 | auto it = shadow ? canvases_.find(shadow->id) : canvases_.end(); |
| 2011 | const std::string& method = q["method"].asString(); |
| 2012 | if (it == canvases_.end()) { |
| 2013 | if (method == "getTransform") return Json::array().push(1).push(0).push(0).push(1).push( |
| 2014 | if (method == "getLineDash") return Json::array(); |
| 2015 | if (method == "isPointInPath" || method == "isPointInStroke") return false; |
| 2016 | return Json::object().set("error", "no canvas"); |
| 2017 | } |
| 2018 | if (method == "toDataURL") return Json::object().set("error", "toDataURL unsupported by the litehtml renderer"); |
| 2019 | return it->second->call(method, q["args"]); |
| 2020 | } |
| 2021 | if (kind == "svg") return Json::object().set("error", kind + " unsupported by the litehtml renderer"); |
| 2022 | return Json::object().set("error", "unknown query"); |
| 2023 | } |
| 2024 | |
| 2025 | bool Renderer::match_media(const std::string& query) const { |
| 2026 | std::string q = lower(query); |
| 2027 | if (q.find("prefers-color-scheme") != std::string::npos) return (q.find("dark") != std::string::npos) == dark_; |
| 2028 | auto px = [&](const char* key) -> double { |
| 2029 | size_t i = q.find(key); |
| 2030 | if (i == std::string::npos) return NAN; |
| 2031 | size_t j = i + std::strlen(key); |
| 2032 | while (j < q.size() && (q[j] == ' ' || q[j] == ':')) j++; |
| 2033 | return std::atof(q.c_str() + j); |
| 2034 | }; |
| 2035 | double v; |
| 2036 | if (!std::isnan(v = px("max-width"))) return width_ <= v; |
| 2037 | if (!std::isnan(v = px("min-width"))) return width_ >= v; |
| 2038 | if (q.find("hover") != std::string::npos) return q.find("none") != std::string::npos; |
| 2039 | if (q.find("pointer") != std::string::npos) return q.find("coarse") != std::string::npos; |
| 2040 | return false; |
| 2041 | } |
| 2042 | |
| 2043 | int64_t Renderer::widget_id_at(double x, double y, Rect* placement) const { |
| 2044 | return container_->widget_id(container_->element_at(x, y), placement); |
| 2045 | } |
| 2046 | |
| 2047 | // ───────────────────────── events ───────────────────────── |
| 2048 | |
| 2049 | bool Renderer::wants_gesture(int64_t target) const { |
| 2050 | const Node* n = node(target); |
| 2051 | while (n) { |
| 2052 | if (n->id && (prevent_.count(std::to_string(n->id) + ":pointerdown") || prevent_.count(std::to_string(n->id) + ":touchstart"))) return true |
| 2053 | if (n->tag == "input") { |
| 2054 | for (const auto& a : n->attrs) if (a.first == "type" && lower(a.second) == "range") return true; |
| 2055 | } |
| 2056 | for (const auto& s : n->styles) { |
| 2057 | if (s.first == "touch-action") { |
| 2058 | std::string v = lower(s.second); |
| 2059 | if (v == "none" || (v.find("pan-y") == std::string::npos && v != "auto" && v != "manipulation")) |
| 2060 | } |
| 2061 | } |
| 2062 | n = n->parent; |
| 2063 | } |
| 2064 | return false; |
| 2065 | } |
| 2066 | |
| 2067 | Json Renderer::event_json(const char* type, int64_t target, const Rect& target_rect, const Input& in) const |
| 2068 | Json ev = Json::object(); |
| 2069 | ev.set("type", type).set("targetId", double(target)); |
| 2070 | ev.set("clientX", in.x).set("clientY", in.y).set("pageX", in.x).set("pageY", in.y); |
| 2071 | ev.set("offsetX", in.x - target_rect.x).set("offsetY", in.y - target_rect.y); |
| 2072 | ev.set("button", 0).set("buttons", in.buttons).set("detail", in.detail).set("modifiers", in.modifiers); |
| 2073 | if (in.related) ev.set("relatedId", double(in.related)); |
| 2074 | std::string name = type; |
| 2075 | if (name.rfind("pointer", 0) == 0 || name == "click" || name == "dblclick") { |
| 2076 | ev.set("pointerId", double(in.mouse ? 1 : in.pointer + 2)).set("pointerType", in.mouse ? "mouse" : "touch").set |
| 2077 | } |
| 2078 | // Form control state travels with every event (the sandbox mirror relies on it). |
| 2079 | const Node* n = node(target); |
| 2080 | if (n && (n->tag == "input" || n->tag == "textarea" || n->tag == "select" || n->tag == "button")) { |
| 2081 | bool checkbox = false; |
| 2082 | for (const auto& a : n->attrs) if (a.first == "type") checkbox = lower(a.second) == "checkbox" || lower(a.second) == "radio"; |
| 2083 | if (checkbox) { |
| 2084 | bool checked = false; |
| 2085 | for (const auto& a : n->attrs) if (a.first == "checked") checked = true; |
| 2086 | ev.set("checked", checked); |
| 2087 | } |
| 2088 | if (n->tag == "textarea") ev.set("value", n->data); |
| 2089 | else for (const auto& a : n->attrs) if (a.first == "value") ev.set("value", a.second); |
| 2090 | } |
| 2091 | return ev; |
| 2092 | } |
| 2093 | |
| 2094 | void Renderer::dispatch(Json ev, std::vector<Json>& out) { |
| 2095 | if (frozen_) return; |
| 2096 | const std::string& type = ev["type"].asString(); |
| 2097 | bool always = false; |
| 2098 | for (const char* a : ALWAYS_FORWARD) if (type == a) always = true; |
| 2099 | if (!always && !interest_.count(type)) return; |
| 2100 | if (coalesced(type)) { |
| 2101 | std::string key = type + ":" + std::to_string(int64_t(ev["pointerId"].asNumber())); |
| 2102 | for (auto& [k, pending] : pending_moves_) { |
| 2103 | if (k != key) continue; |
| 2104 | // Wheel deltas add up over the frame; a move only keeps its latest position. |
| 2105 | if (type == "wheel") { |
| 2106 | ev.set("deltaX", ev["deltaX"].asNumber() + pending["deltaX"].asNumber()); |
| 2107 | ev.set("deltaY", ev["deltaY"].asNumber() + pending["deltaY"].asNumber()); |
| 2108 | } |
| 2109 | pending = std::move(ev); |
| 2110 | return; |
| 2111 | } |
| 2112 | pending_moves_.emplace_back(std::move(key), std::move(ev)); |
| 2113 | return; |
| 2114 | } |
| 2115 | // Anything else keeps its order relative to the moves before it. Every event here comes from real |
| 2116 | // input (no script runs in this document): trusted, like the WebView renderer's isTrusted, which the |
| 2117 | // hosts require before they count a user gesture. |
| 2118 | flush_moves(out); |
| 2119 | out.push_back(Json::object().set("type", "event").set("ev", std::move(ev)).set("trusted", true)); |
| 2120 | } |
| 2121 | |
| 2122 | void Renderer::flush_moves(std::vector<Json>& out) { |
| 2123 | for (auto& [key, ev] : pending_moves_) out.push_back(Json::object().set("type", "event").set("ev", std::move(ev))); |
| 2124 | pending_moves_.clear(); |
| 2125 | } |
| 2126 | |
| 2127 | void Renderer::emit_event(const char* type, int64_t target, const Rect& target_rect, const Touch& t, int |
| 2128 | if (t.mouse && std::strncmp(type, "touch", 5) == 0) return; |
| 2129 | Input in; |
| 2130 | in.x = t.x; |
| 2131 | in.y = t.y; |
| 2132 | in.pointer = t.pointer; |
| 2133 | in.primary = t.primary; |
| 2134 | in.mouse = t.mouse; |
| 2135 | in.modifiers = t.modifiers; |
| 2136 | in.buttons = action == 0 || action == 1 ? 1 : 0; |
| 2137 | in.detail = std::strcmp(type, "click") == 0 || std::strcmp(type, "dblclick") == 0 ? click_count_ : 0; |
| 2138 | dispatch(event_json(type, target, target_rect, in), out); |
| 2139 | } |
| 2140 | |
| 2141 | bool Renderer::is_ancestor(int64_t ancestor, int64_t id) const { |
| 2142 | if (!ancestor) return false; |
| 2143 | const Node* n = node(id); |
| 2144 | for (const Node* p = n ? n->parent : nullptr; p; p = p->parent) |
| 2145 | if (p->id == ancestor) return true; |
| 2146 | return false; |
| 2147 | } |
| 2148 | |
| 2149 | std::vector<int64_t> Renderer::chain(int64_t id) const { |
| 2150 | std::vector<int64_t> out; |
| 2151 | for (const Node* n = node(id); n; n = n->parent) |
| 2152 | if (n->id) out.push_back(n->id); |
| 2153 | return out; |
| 2154 | } |
| 2155 | |
| 2156 | std::vector<Json> Renderer::touch(int action, double x, double y, int pointer, bool primary, bool |
| 2157 | std::vector<Json> out; |
| 2158 | if (frozen_) return out; |
| 2159 | if (action == 0) { |
| 2160 | Touch t{x, y, x, y, 0, Rect{}, false, primary, pointer, mouse, modifiers}; |
| 2161 | t.target = widget_id_at(x, y, &t.target_rect); |
| 2162 | touches_[pointer] = t; |
| 2163 | if (primary) out.push_back(Json::object().set("type", "gesture").set("wants", wants_gesture(t.target))); |
| 2164 | if (container_->mouse(0, x, y)) dirty_ = true; |
| 2165 | if (t.target) { |
| 2166 | emit_event("pointerdown", t.target, t.target_rect, t, 0, out); |
| 2167 | emit_event("mousedown", t.target, t.target_rect, t, 0, out); |
| 2168 | emit_event("touchstart", t.target, t.target_rect, t, 0, out); |
| 2169 | } |
| 2170 | flush_pending(out); |
| 2171 | return out; |
| 2172 | } |
| 2173 | auto it = touches_.find(pointer); |
| 2174 | if (it == touches_.end()) return out; |
| 2175 | Touch& t = it->second; |
| 2176 | t.x = x; |
| 2177 | t.y = y; |
| 2178 | t.modifiers = modifiers; |
| 2179 | if (action == 1) { |
| 2180 | if (!t.moved) { |
| 2181 | if (std::fabs(x - t.x0) < TAP_SLOP && std::fabs(y - t.y0) < TAP_SLOP) return out; |
| 2182 | t.moved = true; |
| 2183 | } |
| 2184 | if (container_->mouse(1, x, y)) dirty_ = true; |
| 2185 | if (t.target) { |
| 2186 | emit_event("pointermove", t.target, t.target_rect, t, 1, out); |
| 2187 | emit_event("mousemove", t.target, t.target_rect, t, 1, out); |
| 2188 | emit_event("touchmove", t.target, t.target_rect, t, 1, out); |
| 2189 | } |
| 2190 | return out; |
| 2191 | } |
| 2192 | Touch done = t; |
| 2193 | touches_.erase(it); |
| 2194 | if (container_->mouse(action, x, y, done.mouse && action == 2)) dirty_ = true; |
| 2195 | if (action == 2) { |
| 2196 | Rect up_rect; |
| 2197 | int64_t up_target = widget_id_at(x, y, &up_rect); |
| 2198 | if (done.target) { |
| 2199 | emit_event("pointerup", done.target, done.target_rect, done, 2, out); |
| 2200 | emit_event("mouseup", done.target, done.target_rect, done, 2, out); |
| 2201 | emit_event("touchend", done.target, done.target_rect, done, 2, out); |
| 2202 | } |
| 2203 | // A click: the press and the release land on the same element, or one inside the other |
| 2204 | // (the click goes to the outer one). A finger must also have stayed inside the slop. |
| 2205 | int64_t click = 0; |
| 2206 | if (done.target && (done.mouse || !done.moved)) { |
| 2207 | if (up_target == done.target || is_ancestor(done.target, up_target)) click = done.target; |
| 2208 | else if (is_ancestor(up_target, done.target)) click = up_target; |
| 2209 | } |
| 2210 | if (done.primary && click) { |
| 2211 | double now = now_ms(); |
| 2212 | if (now - last_click_ms_ < DOUBLE_CLICK_MS && std::hypot(x - last_click_x_, y - last_click_y_) < (done.mouse ? 5 : TAP_SLOP * 2)) click_count_++ |
| 2213 | else click_count_ = 1; |
| 2214 | last_click_ms_ = now; |
| 2215 | last_click_x_ = x; |
| 2216 | last_click_y_ = y; |
| 2217 | Rect rect = click == done.target ? done.target_rect : up_rect; |
| 2218 | emit_event("click", click, rect, done, 2, out); |
| 2219 | if (click_count_ == 2) emit_event("dblclick", click, rect, done, 2, out); |
| 2220 | } |
| 2221 | } else if (done.target) { |
| 2222 | emit_event("pointercancel", done.target, done.target_rect, done, 3, out); |
| 2223 | emit_event("touchcancel", done.target, done.target_rect, done, 3, out); |
| 2224 | } |
| 2225 | flush_pending(out); |
| 2226 | return out; |
| 2227 | } |
| 2228 | |
| 2229 | std::vector<Json> Renderer::hover(int action, double x, double y, int modifiers) { |
| 2230 | std::vector<Json> out; |
| 2231 | if (frozen_) return out; |
| 2232 | auto box = [this](int64_t id) { |
| 2233 | auto el = container_->element(id); |
| 2234 | return el ? border_box_of(el) : Rect{}; |
| 2235 | }; |
| 2236 | Input in; |
| 2237 | in.mouse = true; |
| 2238 | in.pointer = 1; |
| 2239 | in.modifiers = modifiers; |
| 2240 | int64_t previous = hover_; |
| 2241 | int64_t target = 0; |
| 2242 | if (action == 0) { |
| 2243 | in.x = hover_x_ = x; |
| 2244 | in.y = hover_y_ = y; |
| 2245 | if (container_->mouse(1, x, y)) dirty_ = true; |
| 2246 | target = widget_id_at(x, y, nullptr); |
| 2247 | } else { |
| 2248 | in.x = hover_x_; |
| 2249 | in.y = hover_y_; |
| 2250 | if (container_->leave()) dirty_ = true; |
| 2251 | } |
| 2252 | if (target != previous) { |
| 2253 | hover_ = target; |
| 2254 | // out/over bubble and name the other element; leave/enter go to each ancestor the pointer |
| 2255 | // actually left or entered, innermost first for leave and outermost first for enter. |
| 2256 | auto before = chain(previous), after = chain(target); |
| 2257 | auto in_chain = [](const std::vector<int64_t>& c, int64_t id) { return std::find(c.begin(), c.end(), id) |
| 2258 | if (previous) { |
| 2259 | in.related = target; |
| 2260 | dispatch(event_json("pointerout", previous, box(previous), in), out); |
| 2261 | dispatch(event_json("mouseout", previous, box(previous), in), out); |
| 2262 | for (int64_t id : before) { |
| 2263 | if (in_chain(after, id)) continue; |
| 2264 | dispatch(event_json("pointerleave", id, box(id), in), out); |
| 2265 | dispatch(event_json("mouseleave", id, box(id), in), out); |
| 2266 | } |
| 2267 | } |
| 2268 | if (target) { |
| 2269 | in.related = previous; |
| 2270 | dispatch(event_json("pointerover", target, box(target), in), out); |
| 2271 | dispatch(event_json("mouseover", target, box(target), in), out); |
| 2272 | for (auto it = after.rbegin(); it != after.rend(); ++it) { |
| 2273 | if (in_chain(before, *it)) continue; |
| 2274 | dispatch(event_json("pointerenter", *it, box(*it), in), out); |
| 2275 | dispatch(event_json("mouseenter", *it, box(*it), in), out); |
| 2276 | } |
| 2277 | } |
| 2278 | in.related = 0; |
| 2279 | } |
| 2280 | if (target) { |
| 2281 | dispatch(event_json("pointermove", target, box(target), in), out); |
| 2282 | dispatch(event_json("mousemove", target, box(target), in), out); |
| 2283 | } |
| 2284 | flush_pending(out); |
| 2285 | return out; |
| 2286 | } |
| 2287 | |
| 2288 | std::vector<Json> Renderer::wheel(double x, double y, double dx, double dy, int mode, int |
| 2289 | std::vector<Json> out; |
| 2290 | if (frozen_) return out; |
| 2291 | Rect rect; |
| 2292 | int64_t target = widget_id_at(x, y, &rect); |
| 2293 | if (!target) return out; |
| 2294 | Input in; |
| 2295 | in.x = x; |
| 2296 | in.y = y; |
| 2297 | in.mouse = true; |
| 2298 | in.pointer = 1; |
| 2299 | in.modifiers = modifiers; |
| 2300 | Json ev = event_json("wheel", target, rect, in); |
| 2301 | ev.set("deltaX", dx).set("deltaY", dy).set("deltaMode", mode); |
| 2302 | dispatch(std::move(ev), out); |
| 2303 | return out; |
| 2304 | } |
| 2305 | |
| 2306 | std::vector<Json> Renderer::key(const std::string& type, const std::string& key, const std |
| 2307 | std::vector<Json> out; |
| 2308 | if (frozen_ || (type != "keydown" && type != "keyup")) return out; |
| 2309 | int64_t target = body_node_->id ? body_node_->id : html_node_->id; |
| 2310 | if (!target) return out; |
| 2311 | Json ev = Json::object(); |
| 2312 | ev.set("type", type).set("targetId", double(target)).set("key", key).set("code", code).set("repeat", repeat).set("modifiers", modifiers); |
| 2313 | dispatch(std::move(ev), out); |
| 2314 | flush_pending(out); |
| 2315 | return out; |
| 2316 | } |
| 2317 | |
| 2318 | std::vector<Json> Renderer::image_ready(int id, float w, float h) { |
| 2319 | std::vector<Json> out; |
| 2320 | if (!container_->image_ready(id, w, h)) return out; |
| 2321 | rebuild(); |
| 2322 | report_size(out); |
| 2323 | return out; |
| 2324 | } |
| 2325 | |
| 2326 | // ───────────────────────── frozen ───────────────────────── |
| 2327 | |
| 2328 | void Renderer::freeze(const std::string& reason, bool fatal) { |
| 2329 | if (frozen_) return; |
| 2330 | frozen_ = true; |
| 2331 | frozen_reason_ = reason; |
| 2332 | frozen_fatal_ = fatal; |
| 2333 | touches_.clear(); |
| 2334 | pending_moves_.clear(); |
| 2335 | hover_ = 0; |
| 2336 | } |
| 2337 | |
| 2338 | // ───────────────────────── display list JSON ───────────────────────── |
| 2339 | |
| 2340 | std::string to_json(const DisplayList& list) { |
| 2341 | std::string out; |
| 2342 | out.reserve(list.size() * 64 + 2); |
| 2343 | auto num = [&](float v) { out += twidget::Json::number(std::round(double(v) * 100) / |
| 2344 | auto rect = [&](const char* key, const Rect& r) { |
| 2345 | out += ",\""; |
| 2346 | out += key; |
| 2347 | out += "\":["; |
| 2348 | num(r.x); out.push_back(','); num(r.y); out.push_back(','); num(r.w); out.push_back(','); num(r.h); |
| 2349 | out.push_back(']'); |
| 2350 | }; |
| 2351 | auto color = [&](const Color& c) { |
| 2352 | out += ",\"c\":"; |
| 2353 | out += std::to_string((uint32_t(c.a) << 24) | (uint32_t(c.r) << 16) | (uint32_t(c.g) << 8) | c.b); |
| 2354 | }; |
| 2355 | out.push_back('['); |
| 2356 | bool first = true; |
| 2357 | for (const Command& c : list) { |
| 2358 | if (!first) out.push_back(','); |
| 2359 | first = false; |
| 2360 | out += "{\"k\":"; |
| 2361 | out += std::to_string(int(c.kind)); |
| 2362 | if (c.kind != Cmd::ClipPop && c.kind != Cmd::Text) rect("r", c.rect); |
| 2363 | if (c.radii.any()) { |
| 2364 | out += ",\"q\":["; |
| 2365 | const float v[] = {c.radii.tlx, c.radii.tly, c.radii.trx, c.radii.try_, c.radii.brx, c.radii.bry, c.radii.blx, c.radii.bly}; |
| 2366 | for (int i = 0; i < 8; i++) { if (i) out.push_back(','); num(v[i]); } |
| 2367 | out.push_back(']'); |
| 2368 | } |
| 2369 | if (c.has_clip) rect("l", c.clip); |
| 2370 | switch (c.kind) { |
| 2371 | case Cmd::FillRect: case Cmd::FillEllipse: color(c.color); break; |
| 2372 | case Cmd::StrokeRect: case Cmd::StrokeEllipse: color(c.color); out += ",\"w\":"; num(c.width); break; |
| 2373 | case Cmd::Text: |
| 2374 | color(c.color); |
| 2375 | out += ",\"f\":" + std::to_string(c.font) + ",\"x\":"; num(c.x); |
| 2376 | out += ",\"y\":"; num(c.y); |
| 2377 | out += ",\"t\":" + twidget::Json::quote(c.text); |
| 2378 | break; |
| 2379 | case Cmd::Image: out += ",\"i\":" + std::to_string(c.image); break; |
| 2380 | case Cmd::Linear: case Cmd::Radial: case Cmd::Conic: |
| 2381 | out += ",\"a\":["; num(c.ax); out.push_back(','); num(c.ay); out.push_back(','); num(c.bx); out.push_back(','); num(c.by); out.push_back |
| 2382 | out += ",\"s\":["; |
| 2383 | for (size_t i = 0; i < c.stops.size(); i++) { |
| 2384 | if (i) out.push_back(','); |
| 2385 | num(c.stops[i].offset); |
| 2386 | out.push_back(','); |
| 2387 | const Color& s = c.stops[i].color; |
| 2388 | out += std::to_string((uint32_t(s.a) << 24) | (uint32_t(s.r) << 16) | (uint32_t(s.g) << 8) | s.b); |
| 2389 | } |
| 2390 | out.push_back(']'); |
| 2391 | break; |
| 2392 | case Cmd::ClipPush: case Cmd::ClipPop: break; |
| 2393 | } |
| 2394 | out.push_back('}'); |
| 2395 | } |
| 2396 | out.push_back(']'); |
| 2397 | return out; |
| 2398 | } |
| 2399 | |
| 2400 | } // namespace twlite |
| 2401 | |