| 1 | //! The renderer trust domain of docs/protocol.md on Blitz: validated |
| 2 | //! `RenderOp`s in, layout answers and `WidgetEvent`s out, pixels on request. |
| 3 | //! Mirrors src/renderer/renderer.ts; nothing here parses HTML or runs script. |
| 4 | |
| 5 | use crate::net::DataOnlyNet; |
| 6 | use crate::Backend; |
| 7 | use anyrender::render_to_buffer; |
| 8 | use anyrender_vello_cpu::VelloCpuImageRenderer; |
| 9 | use blitz_dom::{ |
| 10 | local_name, ns, Attribute, BaseDocument, Document, DocumentConfig, EventDriver, EventHandler, |
| 11 | FontContext, LocalName, NodeData, NodeId, PlainDocument, QualName, |
| 12 | }; |
| 13 | use blitz_paint::paint_scene; |
| 14 | use blitz_traits::events::{ |
| 15 | BlitzPointerEvent, BlitzPointerId, DomEvent, DomEventData, EventState, MouseEventButton, |
| 16 | MouseEventButtons, PointerCoords, PointerDetails, UiEvent, |
| 17 | }; |
| 18 | use blitz_traits::shell::{ColorScheme, Viewport}; |
| 19 | use serde_json::{json, Map, Value}; |
| 20 | use std::collections::{HashMap, HashSet}; |
| 21 | use std::sync::Arc; |
| 22 | |
| 23 | const MIN_HEIGHT: f64 = 24.0; |
| 24 | const MAX_HEIGHT: f64 = 900.0; |
| 25 | const ALWAYS_FORWARD: &[&str] = &["click", "input", "change", "submit", "reset", "load", "error", "toggle"]; |
| 26 | /// A finger jitters a few px during a tap; Blitz turns any move beyond 2 px into a document pan |
| 27 | /// and then drops the click. Moves stay inside the renderer until the finger leaves this radius |
| 28 | /// (CSS px), like the platforms' own tap slop. |
| 29 | const TAP_SLOP: f64 = 8.0; |
| 30 | |
| 31 | pub struct Renderer { |
| 32 | doc: PlainDocument, |
| 33 | fonts: FontContext, |
| 34 | net: Arc<DataOnlyNet>, |
| 35 | /// widget node id → Blitz node id, and back |
| 36 | nodes: HashMap<i64, NodeId>, |
| 37 | ids: HashMap<NodeId, i64>, |
| 38 | html: NodeId, |
| 39 | head: NodeId, |
| 40 | body: NodeId, |
| 41 | width: f64, |
| 42 | dpr: f64, |
| 43 | dark: bool, |
| 44 | /// Viewport height in CSS px (the document decides it, like the iframe on the web). |
| 45 | vp_height: u32, |
| 46 | doc_height: f64, |
| 47 | interest: HashSet<String>, |
| 48 | prevent: HashSet<String>, |
| 49 | frozen: bool, |
| 50 | last_size: String, |
| 51 | pub dirty: bool, |
| 52 | /// Where each pressed pointer went down, and whether it has left the tap slop since. |
| 53 | touch_down: HashMap<i32, (f64, f64)>, |
| 54 | touch_moved: HashSet<i32>, |
| 55 | backend: Backend, |
| 56 | } |
| 57 | |
| 58 | fn qn(tag: &str, svg: bool) -> QualName { |
| 59 | QualName::new(None, if svg { ns!(svg) } else { ns!(html) }, LocalName::from(tag)) |
| 60 | } |
| 61 | |
| 62 | fn attr_name(name: &str) -> QualName { |
| 63 | QualName::new(None, ns!(), LocalName::from(name)) |
| 64 | } |
| 65 | |
| 66 | /// Milliseconds on a monotonic clock. `std::time::Instant` is unavailable on |
| 67 | /// wasm32-unknown-unknown (it panics), so there the paint time is 0 and the |
| 68 | /// JS glue measures around the call. |
| 69 | #[cfg(not(target_arch = "wasm32"))] |
| 70 | fn now() -> f64 { |
| 71 | use std::sync::OnceLock; |
| 72 | use std::time::Instant; |
| 73 | static EPOCH: OnceLock<Instant> = OnceLock::new(); |
| 74 | EPOCH.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0 |
| 75 | } |
| 76 | #[cfg(target_arch = "wasm32")] |
| 77 | fn now() -> f64 { |
| 78 | 0.0 |
| 79 | } |
| 80 | |
| 81 | fn rect_json(x: f64, y: f64, w: f64, h: f64) -> Value { |
| 82 | json!({ "x": x, "y": y, "width": w, "height": h, "top": y, "left": x, "right": x + w, "bottom": y + h }) |
| 83 | } |
| 84 | |
| 85 | impl Renderer { |
| 86 | pub fn new(width: f64, dpr: f64, dark: bool, fonts: FontContext) -> Self { |
| 87 | let net = Arc::new(DataOnlyNet::new()); |
| 88 | let vp_height = MIN_HEIGHT as u32; |
| 89 | let mut base = BaseDocument::new(DocumentConfig { |
| 90 | viewport: Some(Self::viewport(width, vp_height, dpr, dark)), |
| 91 | net_provider: Some(net.clone() as _), |
| 92 | font_ctx: Some(fonts.clone()), |
| 93 | ..Default::default() |
| 94 | }); |
| 95 | // Chromium/WebKit UA rules Blitz's stylesheet lacks and widgets rely on. |
| 96 | base.add_user_agent_stylesheet("button,input,select,textarea,meter,progress{box-sizing:border-box}"); |
| 97 | let root = base.root_node().id; |
| 98 | let (html, head, body) = { |
| 99 | let mut m = base.mutate(); |
| 100 | let html = m.create_element(qn("html", false), vec![]); |
| 101 | let head = m.create_element(qn("head", false), vec![]); |
| 102 | let body = m.create_element(qn("body", false), vec![]); |
| 103 | m.append_children(html, &[head, body]); |
| 104 | m.append_children(root, &[html]); |
| 105 | (html, head, body) |
| 106 | }; |
| 107 | Self { |
| 108 | doc: PlainDocument(base), |
| 109 | fonts, |
| 110 | net, |
| 111 | nodes: HashMap::new(), |
| 112 | ids: HashMap::new(), |
| 113 | html, |
| 114 | head, |
| 115 | body, |
| 116 | width, |
| 117 | dpr, |
| 118 | dark, |
| 119 | vp_height, |
| 120 | doc_height: 0.0, |
| 121 | interest: HashSet::new(), |
| 122 | prevent: HashSet::new(), |
| 123 | frozen: false, |
| 124 | last_size: String::new(), |
| 125 | dirty: true, |
| 126 | touch_down: HashMap::new(), |
| 127 | touch_moved: HashSet::new(), |
| 128 | backend: Backend::from_env(), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | fn viewport(width: f64, vp_height: u32, dpr: f64, dark: bool) -> Viewport { |
| 133 | Viewport::new( |
| 134 | (width * dpr).ceil() as u32, |
| 135 | ((vp_height as f64) * dpr).ceil() as u32, |
| 136 | dpr as f32, |
| 137 | if dark { ColorScheme::Dark } else { ColorScheme::Light }, |
| 138 | ) |
| 139 | } |
| 140 | |
| 141 | fn base(&self) -> &BaseDocument { |
| 142 | &self.doc.0 |
| 143 | } |
| 144 | |
| 145 | fn base_mut(&mut self) -> &mut BaseDocument { |
| 146 | &mut self.doc.0 |
| 147 | } |
| 148 | |
| 149 | /// Host → renderer message. Returns renderer → host messages. |
| 150 | pub fn receive(&mut self, msg: &Value) -> Vec<Value> { |
| 151 | let mut out = Vec::new(); |
| 152 | match msg.get("type").and_then(Value::as_str).unwrap_or("") { |
| 153 | "ops" => { |
| 154 | if let Some(ops) = msg.get("ops").and_then(Value::as_array) { |
| 155 | for op in ops { |
| 156 | self.apply_op(op, &mut out); |
| 157 | } |
| 158 | } |
| 159 | self.layout(); |
| 160 | self.dirty = true; |
| 161 | self.report_size(&mut out); |
| 162 | } |
| 163 | "query" => { |
| 164 | let qid = msg.get("qid").cloned().unwrap_or(Value::Null); |
| 165 | let result = match msg.get("query") { |
| 166 | Some(q) => self.answer(q), |
| 167 | None => json!({ "error": "no query" }), |
| 168 | }; |
| 169 | out.push(json!({ "type": "result", "qid": qid, "result": result })); |
| 170 | } |
| 171 | "listen" => { |
| 172 | self.interest = msg |
| 173 | .get("types") |
| 174 | .and_then(Value::as_array) |
| 175 | .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) |
| 176 | .unwrap_or_default(); |
| 177 | } |
| 178 | "preventDefault" => { |
| 179 | self.prevent = msg |
| 180 | .get("keys") |
| 181 | .and_then(Value::as_array) |
| 182 | .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) |
| 183 | .unwrap_or_default(); |
| 184 | } |
| 185 | "frozen" => { |
| 186 | let reason = msg.get("reason").and_then(Value::as_str).unwrap_or("").to_string(); |
| 187 | let fatal = msg.get("fatal").and_then(Value::as_bool).unwrap_or(false); |
| 188 | self.freeze(&reason, fatal); |
| 189 | self.layout(); |
| 190 | self.dirty = true; |
| 191 | } |
| 192 | _ => {} |
| 193 | } |
| 194 | self.drain_blocked(&mut out); |
| 195 | out |
| 196 | } |
| 197 | |
| 198 | pub fn set_width(&mut self, width: f64, out: &mut Vec<Value>) { |
| 199 | if (width - self.width).abs() < 0.01 { |
| 200 | return; |
| 201 | } |
| 202 | self.width = width; |
| 203 | let vp = Self::viewport(width, self.vp_height, self.dpr, self.dark); |
| 204 | self.base_mut().set_viewport(vp); |
| 205 | self.layout(); |
| 206 | self.dirty = true; |
| 207 | self.report_size(out); |
| 208 | } |
| 209 | |
| 210 | /// The chat theme changed: `prefers-color-scheme` inside the document follows. |
| 211 | pub fn set_theme(&mut self, dark: bool, out: &mut Vec<Value>) { |
| 212 | if dark == self.dark { |
| 213 | return; |
| 214 | } |
| 215 | self.dark = dark; |
| 216 | let vp = Self::viewport(self.width, self.vp_height, self.dpr, self.dark); |
| 217 | self.base_mut().set_viewport(vp); |
| 218 | self.layout(); |
| 219 | self.dirty = true; |
| 220 | self.report_size(out); |
| 221 | } |
| 222 | |
| 223 | fn drain_blocked(&mut self, out: &mut Vec<Value>) { |
| 224 | let blocked: Vec<String> = std::mem::take(&mut *self.net.blocked.lock().unwrap()); |
| 225 | for url in blocked { |
| 226 | out.push(json!({ "type": "violation", "detail": format!("fetch refused: {url}") })); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // ───────────────────────── ops ───────────────────────── |
| 231 | |
| 232 | fn apply_op(&mut self, op: &Value, out: &mut Vec<Value>) { |
| 233 | let kind = op.get("op").and_then(Value::as_str).unwrap_or(""); |
| 234 | let id = op.get("id").and_then(Value::as_i64).unwrap_or(0); |
| 235 | let s = |k: &str| op.get(k).and_then(Value::as_str).unwrap_or("").to_string(); |
| 236 | match kind { |
| 237 | "el" => { |
| 238 | let tag = s("tag").to_lowercase(); |
| 239 | let adopt = s("adopt"); |
| 240 | let svg = op.get("ns").and_then(Value::as_str) == Some("svg"); |
| 241 | let nid = match adopt.as_str() { |
| 242 | "html" => self.html, |
| 243 | "head" => self.head, |
| 244 | "body" => self.body, |
| 245 | _ => { |
| 246 | let attrs = op |
| 247 | .get("attrs") |
| 248 | .and_then(Value::as_array) |
| 249 | .map(|a| { |
| 250 | a.iter() |
| 251 | .filter_map(|pair| { |
| 252 | let p = pair.as_array()?; |
| 253 | let name = p.first()?.as_str()?; |
| 254 | let value = p.get(1)?.as_str()?; |
| 255 | if name.to_ascii_lowercase().starts_with("on") { |
| 256 | return None; |
| 257 | } |
| 258 | Some(Attribute { name: attr_name(name), value: value.to_string() }) |
| 259 | }) |
| 260 | .collect::<Vec<_>>() |
| 261 | }) |
| 262 | .unwrap_or_default(); |
| 263 | let mut m = self.doc.0.mutate(); |
| 264 | m.create_element(qn(&tag, svg), attrs) |
| 265 | } |
| 266 | }; |
| 267 | self.register(id, nid); |
| 268 | if !adopt.is_empty() { |
| 269 | // attrs on an adopted element are applied one by one |
| 270 | if let Some(a) = op.get("attrs").and_then(Value::as_array) { |
| 271 | for pair in a { |
| 272 | if let (Some(name), Some(value)) = (pair.get(0).and_then(Value::as_str), pair.get(1).and_then( |
| 273 | self.doc.0.mutate().set_attribute(nid, attr_name(name), value); |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | "text" => { |
| 280 | let nid = self.doc.0.mutate().create_text_node(&s("data")); |
| 281 | self.register(id, nid); |
| 282 | } |
| 283 | "comment" => {} |
| 284 | _ => { |
| 285 | let Some(&nid) = self.nodes.get(&id) else { return }; |
| 286 | let is_root = nid == self.html || nid == self.head || nid == self.body; |
| 287 | match kind { |
| 288 | "attr" => { |
| 289 | let name = s("name"); |
| 290 | if name.to_ascii_lowercase().starts_with("on") { |
| 291 | out.push(json!({ "type": "violation", "detail": format!("attribute {name}") })); |
| 292 | return; |
| 293 | } |
| 294 | self.doc.0.mutate().set_attribute(nid, attr_name(&name), &s("value")); |
| 295 | } |
| 296 | "rattr" => self.doc.0.mutate().clear_attribute(nid, attr_name(&s("name"))), |
| 297 | "data" => self.doc.0.mutate().set_node_text(nid, &s("data")), |
| 298 | "ins" => { |
| 299 | if is_root { |
| 300 | return; |
| 301 | } |
| 302 | let parent = op.get("parent").and_then(Value::as_i64).unwrap_or(0); |
| 303 | let mut m = self.doc.0.mutate(); |
| 304 | if parent == 0 { |
| 305 | if m.parent_id(nid).is_some() { |
| 306 | m.remove_node(nid); |
| 307 | } |
| 308 | return; |
| 309 | } |
| 310 | let Some(&pnid) = self.nodes.get(&parent) else { return }; |
| 311 | if m.parent_id(nid).is_some() { |
| 312 | m.remove_node(nid); |
| 313 | } |
| 314 | let before = op.get("before").and_then(Value::as_i64).and_then(|b| self.nodes.get(&b) |
| 315 | match before { |
| 316 | Some(bnid) if m.parent_id(bnid) == Some(pnid) => m.insert_nodes_before(bnid, &[nid]), |
| 317 | _ => m.append_children(pnid, &[nid]), |
| 318 | } |
| 319 | } |
| 320 | "rm" => { |
| 321 | if is_root { |
| 322 | return; |
| 323 | } |
| 324 | self.forget(nid); |
| 325 | self.doc.0.mutate().remove_and_drop_node(nid); |
| 326 | } |
| 327 | "style" => { |
| 328 | let name = s("name"); |
| 329 | let value = s("value"); |
| 330 | let mut m = self.doc.0.mutate(); |
| 331 | if value.is_empty() { |
| 332 | m.remove_style_property(nid, &name); |
| 333 | } else { |
| 334 | m.set_style_property(nid, &name, &value); |
| 335 | } |
| 336 | } |
| 337 | "css" => { |
| 338 | let text = s("text"); |
| 339 | let is_style = matches!(self.doc.0.get_node(nid).map(|n| &n.data), Some(NodeData::Element(el)) |
| 340 | if !is_style { |
| 341 | return; |
| 342 | } |
| 343 | { |
| 344 | let mut m = self.doc.0.mutate(); |
| 345 | let child = m.child_ids(nid).first().copied(); |
| 346 | match child { |
| 347 | Some(c) => m.set_node_text(c, &text), |
| 348 | None => { |
| 349 | let c = m.create_text_node(&text); |
| 350 | m.append_children(nid, &[c]); |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | self.doc.0.process_style_element(nid); |
| 355 | } |
| 356 | "prop" => self.apply_prop(nid, &s("name"), op.get("value").unwrap_or(&Value::Null)), |
| 357 | "call" => self.apply_call(nid, &s("method"), op.get("args").and_then(Value::as_array)), |
| 358 | "canvas" => { |
| 359 | // TODO: replay CanvasCmd on a custom paint source; the element renders empty for now. |
| 360 | } |
| 361 | _ => {} |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | fn register(&mut self, id: i64, nid: NodeId) { |
| 368 | self.nodes.insert(id, nid); |
| 369 | self.ids.insert(nid, id); |
| 370 | } |
| 371 | |
| 372 | fn forget(&mut self, nid: NodeId) { |
| 373 | let mut stack = vec![nid]; |
| 374 | while let Some(n) = stack.pop() { |
| 375 | if let Some(id) = self.ids.remove(&n) { |
| 376 | self.nodes.remove(&id); |
| 377 | } |
| 378 | if let Some(node) = self.doc.0.get_node(n) { |
| 379 | stack.extend(node.children.iter().copied()); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | fn apply_prop(&mut self, nid: NodeId, name: &str, value: &Value) { |
| 385 | match name { |
| 386 | "value" => { |
| 387 | let text = match value { |
| 388 | Value::String(s) => s.clone(), |
| 389 | Value::Null => String::new(), |
| 390 | v => v.to_string(), |
| 391 | }; |
| 392 | // `set_text` alone leaves the editor's layout dirty, and blitz-paint |
| 393 | // unwraps it on the next frame (node.rs text_input_v_centering_offset). |
| 394 | self.doc.0.with_text_input(nid, |mut drv| { |
| 395 | drv.editor.set_text(&text); |
| 396 | drv.refresh_layout(); |
| 397 | }); |
| 398 | } |
| 399 | "checked" => { |
| 400 | let v = value.as_bool().unwrap_or(false); |
| 401 | if let Some(c) = self.doc.0.get_node_mut(nid).and_then(|n| n.element_data_mut()).and_then(|el |
| 402 | *c = v; |
| 403 | } |
| 404 | } |
| 405 | "scrollTop" | "scrollLeft" => { |
| 406 | let v = value.as_f64().unwrap_or(0.0); |
| 407 | if let Some(node) = self.doc.0.get_node_mut(nid) { |
| 408 | let off = node.scroll_offset_mut(); |
| 409 | if name == "scrollTop" { off.y = v } else { off.x = v } |
| 410 | } |
| 411 | } |
| 412 | _ => {} |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | fn apply_call(&mut self, nid: NodeId, method: &str, args: Option<&Vec<Value>>) { |
| 417 | let num = |i: usize| args.and_then(|a| a.get(i)).and_then(Value::as_f64).unwrap_or( |
| 418 | match method { |
| 419 | "focus" => { |
| 420 | self.doc.0.set_focus_to(nid); |
| 421 | } |
| 422 | "blur" => self.doc.0.clear_focus(), |
| 423 | "scrollTo" => { |
| 424 | if let Some(node) = self.doc.0.get_node_mut(nid) { |
| 425 | let off = node.scroll_offset_mut(); |
| 426 | off.x = num(0); |
| 427 | off.y = num(1); |
| 428 | } |
| 429 | } |
| 430 | "scrollBy" => { |
| 431 | if let Some(node) = self.doc.0.get_node_mut(nid) { |
| 432 | let off = node.scroll_offset_mut(); |
| 433 | off.x += num(0); |
| 434 | off.y += num(1); |
| 435 | } |
| 436 | } |
| 437 | _ => {} |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | // ───────────────────────── layout & size ───────────────────────── |
| 442 | |
| 443 | fn root_height(&self) -> f64 { |
| 444 | self.doc.0.get_node(self.html).map(|n| n.final_layout().size.height as f64).unwrap_or |
| 445 | } |
| 446 | |
| 447 | fn layout(&mut self) { |
| 448 | // Like the web iframe: the viewport follows the document height (100vh must not explode), converging in a few passes. |
| 449 | for _ in 0..4 { |
| 450 | self.doc.0.resolve(0.0); |
| 451 | let h = self.root_height().max(MIN_HEIGHT).min(MAX_HEIGHT).ceil() as u32; |
| 452 | if h == self.vp_height { |
| 453 | break; |
| 454 | } |
| 455 | self.vp_height = h; |
| 456 | let vp = Self::viewport(self.width, h, self.dpr, self.dark); |
| 457 | self.doc.0.set_viewport(vp); |
| 458 | } |
| 459 | self.doc_height = self.root_height().ceil(); |
| 460 | } |
| 461 | |
| 462 | fn report_size(&mut self, out: &mut Vec<Value>) { |
| 463 | let msg = json!({ |
| 464 | "type": "size", "width": self.width, "height": self.doc_height, |
| 465 | "innerWidth": self.width, "innerHeight": self.vp_height, "dpr": self.dpr, |
| 466 | }); |
| 467 | let key = msg.to_string(); |
| 468 | if key != self.last_size { |
| 469 | self.last_size = key; |
| 470 | out.push(msg); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | pub fn viewport_px(&self) -> (u32, u32) { |
| 475 | let vp = self.base().viewport(); |
| 476 | vp.window_size |
| 477 | } |
| 478 | |
| 479 | /// Paints into a caller-owned buffer of `capacity` bytes (premultiplied RGBA8, |
| 480 | /// `viewport_px()` sized). Returns the paint time in ms, -2 when the buffer is too small. |
| 481 | pub fn render_into(&mut self, buffer: *mut u8, capacity: usize) -> f64 { |
| 482 | let t0 = now(); |
| 483 | let (w, h) = self.viewport_px(); |
| 484 | let need = (w as usize) * (h as usize) * 4; |
| 485 | if capacity < need { |
| 486 | return -2.0; |
| 487 | } |
| 488 | let pixels = self.render(); |
| 489 | unsafe { std::ptr::copy_nonoverlapping(pixels.as_ptr(), buffer, need.min(pixels.len())) }; |
| 490 | now() - t0 |
| 491 | } |
| 492 | |
| 493 | #[cfg_attr(target_os = "android", allow(dead_code))] |
| 494 | pub fn backend(&self) -> Backend { |
| 495 | self.backend |
| 496 | } |
| 497 | |
| 498 | pub fn set_backend(&mut self, backend: Backend) { |
| 499 | if self.backend != backend { |
| 500 | self.backend = backend; |
| 501 | self.dirty = true; |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | /// The frame as a display list (src/dl.rs) for a platform executor, `viewport_px()` sized. |
| 506 | #[cfg_attr(not(target_os = "android"), allow(dead_code))] |
| 507 | pub fn render_display_list(&mut self) -> Vec<u8> { |
| 508 | let (w, h) = self.viewport_px(); |
| 509 | let scale = self.dpr; |
| 510 | let doc = &mut self.doc.0; |
| 511 | doc.resolve(0.0); |
| 512 | self.dirty = false; |
| 513 | crate::dl::record(doc, scale, w, h) |
| 514 | } |
| 515 | |
| 516 | /// Premultiplied RGBA8, `viewport_px()` sized. |
| 517 | pub fn render(&mut self) -> Vec<u8> { |
| 518 | let (w, h) = self.viewport_px(); |
| 519 | let scale = self.dpr; |
| 520 | let doc = &mut self.doc.0; |
| 521 | doc.resolve(0.0); |
| 522 | self.dirty = false; |
| 523 | match self.backend { |
| 524 | #[cfg(target_vendor = "apple")] |
| 525 | Backend::CoreGraphics => render_to_buffer::<crate::cg::CgImageRenderer, _>(|scene| paint_scene(scene, doc, scale, w, h, 0, 0), w, h), |
| 526 | _ => render_to_buffer::<VelloCpuImageRenderer, _>(|scene| paint_scene(scene, doc, scale, w, h, 0, 0), w, h), |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | // ───────────────────────── queries ───────────────────────── |
| 531 | |
| 532 | fn answer(&mut self, q: &Value) -> Value { |
| 533 | let kind = q.get("q").and_then(Value::as_str).unwrap_or(""); |
| 534 | let nid = q.get("id").and_then(Value::as_i64).and_then(|id| self.nodes.get(&id) |
| 535 | if q.get("id").is_some() { |
| 536 | match nid { |
| 537 | Some(n) if matches!(self.doc.0.get_node(n).map(|x| &x.data), Some(NodeData::Element(_))) |
| 538 | _ => return json!({ "error": "no such element" }), |
| 539 | } |
| 540 | } |
| 541 | match kind { |
| 542 | "rect" => { |
| 543 | let nid = nid.unwrap(); |
| 544 | match self.doc.0.get_client_bounding_rect(nid) { |
| 545 | Some(r) => rect_json(r.x, r.y, r.width, r.height), |
| 546 | None => rect_json(0.0, 0.0, 0.0, 0.0), |
| 547 | } |
| 548 | } |
| 549 | "rects" => { |
| 550 | let nid = nid.unwrap(); |
| 551 | match self.doc.0.get_client_bounding_rect(nid) { |
| 552 | Some(r) => json!([rect_json(r.x, r.y, r.width, r.height)]), |
| 553 | None => json!([]), |
| 554 | } |
| 555 | } |
| 556 | "box" => { |
| 557 | let nid = nid.unwrap(); |
| 558 | let Some(node) = self.doc.0.get_node(nid) else { return json!({ "error": "no such element" }) }; |
| 559 | let l = node.final_layout(); |
| 560 | let rect = self.doc.0.get_client_bounding_rect(nid); |
| 561 | let (x, y) = rect.map(|r| (r.x, r.y)).unwrap_or((l.location.x as f64, l.location.y |
| 562 | let parent = node.parent.and_then(|p| self.ids.get(&p).copied()).unwrap_or(0); |
| 563 | let overflow = node.scrollable_overflow(); |
| 564 | let off = node.scroll_offset(); |
| 565 | let cw = (l.size.width - l.border.left - l.border.right).max(0.0); |
| 566 | let ch = (l.size.height - l.border.top - l.border.bottom).max(0.0); |
| 567 | json!({ |
| 568 | "offsetWidth": l.size.width, "offsetHeight": l.size.height, "offsetTop": y, "offsetLeft": x, |
| 569 | "offsetParent": parent, |
| 570 | "clientWidth": cw, "clientHeight": ch, "clientTop": l.border.top, "clientLeft": l.border.left, |
| 571 | "scrollWidth": overflow.width().max(cw as f64), "scrollHeight": overflow.height().max(ch as f64), |
| 572 | "scrollTop": off.y, "scrollLeft": off.x, |
| 573 | }) |
| 574 | } |
| 575 | "cs" => { |
| 576 | let nid = nid.unwrap(); |
| 577 | if let Some(prop) = q.get("prop").and_then(Value::as_str) { |
| 578 | return Value::String(self.doc.0.resolved_style_value(nid, prop)); |
| 579 | } |
| 580 | let mut out = Map::new(); |
| 581 | for name in blitz_dom::resolved_style_property_names() { |
| 582 | out.insert((*name).to_string(), Value::String(self.doc.0.resolved_style_value(nid, name))); |
| 583 | } |
| 584 | Value::Object(out) |
| 585 | } |
| 586 | "elementFromPoint" => { |
| 587 | let x = q.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32; |
| 588 | let y = q.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32; |
| 589 | let id = self.doc.0.element_from_point(x, y).and_then(|n| self.widget_id(n)).unwrap_or(0); |
| 590 | json!(id) |
| 591 | } |
| 592 | "measureText" => { |
| 593 | let font = q.get("font").and_then(Value::as_str).unwrap_or("10px sans-serif"); |
| 594 | let text = q.get("text").and_then(Value::as_str).unwrap_or(""); |
| 595 | crate::text::measure(&mut self.fonts, font, text) |
| 596 | } |
| 597 | "validity" => json!({ "valid": true, "message": "" }), |
| 598 | "matchMedia" => { |
| 599 | let query = q.get("query").and_then(Value::as_str).unwrap_or(""); |
| 600 | json!({ "matches": self.match_media(query) }) |
| 601 | } |
| 602 | "viewport" => json!({ "innerWidth": self.width, "innerHeight": self.vp_height, "dpr": self.dpr }), |
| 603 | "svg" | "imageData" | "canvasCall" => json!({ "error": format!("{kind} unsupported by the Blitz renderer") }), |
| 604 | _ => json!({ "error": "unknown query" }), |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | fn match_media(&self, query: &str) -> bool { |
| 609 | let q = query.to_ascii_lowercase(); |
| 610 | if q.contains("prefers-color-scheme") { |
| 611 | return q.contains("dark") == self.dark; |
| 612 | } |
| 613 | let px = |key: &str| -> Option<f64> { |
| 614 | let i = q.find(key)?; |
| 615 | let rest = &q[i + key.len()..]; |
| 616 | let rest = rest.trim_start_matches([' ', ':']); |
| 617 | let num: String = rest.chars().take_while(|c| c.is_ascii_digit() || *c == '.'). |
| 618 | num.parse().ok() |
| 619 | }; |
| 620 | if let Some(v) = px("max-width") { |
| 621 | return self.width <= v; |
| 622 | } |
| 623 | if let Some(v) = px("min-width") { |
| 624 | return self.width >= v; |
| 625 | } |
| 626 | if q.contains("hover") { |
| 627 | return q.contains("none"); |
| 628 | } |
| 629 | if q.contains("pointer") { |
| 630 | return q.contains("coarse"); |
| 631 | } |
| 632 | false |
| 633 | } |
| 634 | |
| 635 | /// Widget id of a Blitz node, or of its nearest mapped ancestor. |
| 636 | fn widget_id(&self, mut nid: NodeId) -> Option<i64> { |
| 637 | loop { |
| 638 | if let Some(&id) = self.ids.get(&nid) { |
| 639 | return Some(id); |
| 640 | } |
| 641 | nid = self.doc.0.get_node(nid)?.parent?; |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // ───────────────────────── events ───────────────────────── |
| 646 | |
| 647 | /// A touch from the host view, in CSS px. `action`: 0 down, 1 move, 2 up, 3 cancel. |
| 648 | pub fn touch(&mut self, action: i32, x: f64, y: f64, pointer: i32, primary: bool) |
| 649 | let mut out = Vec::new(); |
| 650 | if self.frozen { |
| 651 | return out; |
| 652 | } |
| 653 | match action { |
| 654 | 0 => { |
| 655 | self.touch_down.insert(pointer, (x, y)); |
| 656 | self.touch_moved.remove(&pointer); |
| 657 | } |
| 658 | 1 => { |
| 659 | if !self.touch_moved.contains(&pointer) { |
| 660 | if let Some(&(x0, y0)) = self.touch_down.get(&pointer) { |
| 661 | if (x - x0).abs() < TAP_SLOP && (y - y0).abs() < TAP_SLOP { |
| 662 | return out; |
| 663 | } |
| 664 | } |
| 665 | self.touch_moved.insert(pointer); |
| 666 | } |
| 667 | } |
| 668 | _ => { |
| 669 | self.touch_down.remove(&pointer); |
| 670 | self.touch_moved.remove(&pointer); |
| 671 | } |
| 672 | } |
| 673 | // A move counts as pressed only while that pointer is down: a mouse hovering over the |
| 674 | // document (web, macOS) must not become a drag, which Blitz turns into a document pan. |
| 675 | let pressed = action == 0 || (action == 1 && self.touch_down.contains_key(&pointer)); |
| 676 | let ev = BlitzPointerEvent { |
| 677 | id: BlitzPointerId::Finger(pointer as u64), |
| 678 | is_primary: primary, |
| 679 | coords: PointerCoords { |
| 680 | page_x: x as f32, page_y: y as f32, screen_x: x as f32, screen_y: y as f32, client_x: x as f32, client_y |
| 681 | }, |
| 682 | button: MouseEventButton::Main, |
| 683 | buttons: if pressed { MouseEventButtons::Primary } else { MouseEventButtons::None }, |
| 684 | mods: Default::default(), |
| 685 | details: PointerDetails { pressure: if pressed { 0.5 } else { 0.0 }, ..Default::default() }, |
| 686 | element: blitz_traits::events::Point { x: 0.0, y: 0.0 }, |
| 687 | active_pointers: Default::default(), |
| 688 | }; |
| 689 | let ui = match action { |
| 690 | 0 => UiEvent::PointerDown(ev), |
| 691 | 1 => UiEvent::PointerMove(ev), |
| 692 | 2 => UiEvent::PointerUp(ev), |
| 693 | _ => UiEvent::PointerCancel(ev), |
| 694 | }; |
| 695 | if action == 0 && primary { |
| 696 | let target = self.doc.0.element_from_point(x as f32, y as f32); |
| 697 | let wants = target.map(|t| self.wants_gesture(t)).unwrap_or(false); |
| 698 | out.push(json!({ "type": "gesture", "wants": wants })); |
| 699 | } |
| 700 | let mut events = Vec::new(); |
| 701 | { |
| 702 | let handler = Collector { |
| 703 | ids: &self.ids, |
| 704 | interest: &self.interest, |
| 705 | prevent: &self.prevent, |
| 706 | out: &mut events, |
| 707 | }; |
| 708 | let doc: &mut dyn Document = &mut self.doc; |
| 709 | let mut driver = EventDriver::new(doc, handler); |
| 710 | driver.handle_ui_event(ui); |
| 711 | } |
| 712 | // Real input only (the document has no script that could dispatch events): trusted, like the |
| 713 | // WebView renderer's isTrusted, which the hosts require before they count a user gesture. |
| 714 | for ev in events { |
| 715 | out.push(json!({ "type": "event", "ev": ev, "trusted": true })); |
| 716 | } |
| 717 | self.dirty = true; |
| 718 | out |
| 719 | } |
| 720 | |
| 721 | fn wants_gesture(&self, target: NodeId) -> bool { |
| 722 | let mut cur = Some(target); |
| 723 | while let Some(n) = cur { |
| 724 | if n == self.html { |
| 725 | break; |
| 726 | } |
| 727 | if let Some(id) = self.ids.get(&n) { |
| 728 | if self.prevent.contains(&format!("{id}:pointerdown")) || self.prevent.contains(&format!("{id}:touchstart")) { |
| 729 | return true; |
| 730 | } |
| 731 | } |
| 732 | let Some(node) = self.doc.0.get_node(n) else { break }; |
| 733 | if let NodeData::Element(el) = &node.data { |
| 734 | if el.name.local == local_name!("input") && el.attr(local_name!("type")) == Some("range") { |
| 735 | return true; |
| 736 | } |
| 737 | let ta = self.doc.0.resolved_style_value(n, "touch-action"); |
| 738 | if ta == "none" { |
| 739 | return true; |
| 740 | } |
| 741 | if ta != "auto" && ta != "manipulation" && !ta.contains("pan-y") && !ta.contains("pan-up") |
| 742 | return true; |
| 743 | } |
| 744 | let oy = self.doc.0.resolved_style_value(n, "overflow-y"); |
| 745 | if (oy == "auto" || oy == "scroll") && node.scrollable_overflow().height() > node.final_layout().size.height as |
| 746 | return true; |
| 747 | } |
| 748 | } |
| 749 | cur = node.parent; |
| 750 | } |
| 751 | false |
| 752 | } |
| 753 | |
| 754 | // ───────────────────────── frozen ───────────────────────── |
| 755 | |
| 756 | fn freeze(&mut self, reason: &str, fatal: bool) { |
| 757 | if self.frozen { |
| 758 | return; |
| 759 | } |
| 760 | self.frozen = true; |
| 761 | let (html, head, body) = (self.html, self.head, self.body); |
| 762 | let mut m = self.doc.0.mutate(); |
| 763 | m.set_attribute(html, attr_name("data-tw-frozen"), if fatal { "fatal" } else { "paused" }); |
| 764 | let style = m.create_element(qn("style", false), vec![]); |
| 765 | let css = m.create_text_node( |
| 766 | "[data-tw-frozen]{pointer-events:none}[data-tw-frozen=fatal]{filter:grayscale(.3)}\ |
| 767 | [data-tw-badge]{position:fixed;right:6px;bottom:6px;z-index:2147483647;font:11px/1.3 system-ui,sans-serif;color:#fff;background:rgba(60,60,60,.75);padding:2px 7px;border-radius:9px;pointer-events:none}", |
| 768 | ); |
| 769 | m.append_children(style, &[css]); |
| 770 | m.append_children(head, &[style]); |
| 771 | let badge = m.create_element(qn("div", false), vec![Attribute { name: attr_name("data-tw-badge"), value: if fatal { "fatal" } |
| 772 | let text = m.create_text_node(reason); |
| 773 | m.append_children(badge, &[text]); |
| 774 | m.append_children(body, &[badge]); |
| 775 | drop(m); |
| 776 | self.doc.0.process_style_element(style); |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | /// Sees every DOM event Blitz dispatches, before its default action; applies the |
| 781 | /// learned `preventDefault` keys and serializes what the sandbox listens for. |
| 782 | struct Collector<'a> { |
| 783 | ids: &'a HashMap<NodeId, i64>, |
| 784 | interest: &'a HashSet<String>, |
| 785 | prevent: &'a HashSet<String>, |
| 786 | out: &'a mut Vec<Value>, |
| 787 | } |
| 788 | |
| 789 | impl EventHandler for Collector<'_> { |
| 790 | fn handle_event(&mut self, chain: &[NodeId], event: &mut DomEvent, doc: &mut dyn Document, state: |
| 791 | let name = event.name(); |
| 792 | let target_id = chain.iter().find_map(|n| self.ids.get(n).copied()).unwrap_or(0); |
| 793 | if target_id == 0 { |
| 794 | return; |
| 795 | } |
| 796 | if event.cancelable && (self.prevent.contains(&format!("{target_id}:{name}"))) { |
| 797 | state.prevent_default(); |
| 798 | } |
| 799 | if !ALWAYS_FORWARD.contains(&name) && !self.interest.contains(name) { |
| 800 | return; |
| 801 | } |
| 802 | let mut ev = Map::new(); |
| 803 | ev.insert("type".into(), json!(name)); |
| 804 | ev.insert("targetId".into(), json!(target_id)); |
| 805 | match &event.data { |
| 806 | DomEventData::PointerMove(p) | DomEventData::PointerDown(p) | DomEventData::PointerUp(p) | DomEventData::PointerCancel(p) |
| 807 | | DomEventData::PointerEnter(p) | DomEventData::PointerLeave(p) | DomEventData::PointerOver(p) | DomEventData::PointerOut(p) |
| 808 | | DomEventData::MouseMove(p) | DomEventData::MouseDown(p) | DomEventData::MouseUp(p) | DomEventData::MouseEnter(p) |
| 809 | | DomEventData::MouseLeave(p) | DomEventData::MouseOver(p) | DomEventData::MouseOut(p) | DomEventData::TouchStart(p) |
| 810 | | DomEventData::TouchMove(p) | DomEventData::TouchEnd(p) | DomEventData::TouchCancel(p) | DomEventData::Click(p) |
| 811 | | DomEventData::ContextMenu(p) | DomEventData::DoubleClick(p) => { |
| 812 | ev.insert("clientX".into(), json!(p.coords.client_x)); |
| 813 | ev.insert("clientY".into(), json!(p.coords.client_y)); |
| 814 | ev.insert("pageX".into(), json!(p.coords.page_x)); |
| 815 | ev.insert("pageY".into(), json!(p.coords.page_y)); |
| 816 | ev.insert("offsetX".into(), json!(p.element.x)); |
| 817 | ev.insert("offsetY".into(), json!(p.element.y)); |
| 818 | ev.insert("button".into(), json!(p.button as u8)); |
| 819 | ev.insert("buttons".into(), json!(p.buttons.bits())); |
| 820 | ev.insert("detail".into(), json!(if name == "click" { 1 } else { 0 })); |
| 821 | ev.insert("modifiers".into(), json!(0)); |
| 822 | if name.starts_with("pointer") || name == "click" { |
| 823 | let pid = match p.id { BlitzPointerId::Finger(n) => n as i64 + 2, BlitzPointerId::Pen => 1, |
| 824 | ev.insert("pointerId".into(), json!(pid)); |
| 825 | ev.insert("pointerType".into(), json!(if p.is_mouse() { "mouse" } else if p.is_pen() { "pen" } else { "touch" })); |
| 826 | ev.insert("isPrimary".into(), json!(p.is_primary)); |
| 827 | ev.insert("pressure".into(), json!(p.details.pressure)); |
| 828 | } |
| 829 | } |
| 830 | DomEventData::Wheel(w) => { |
| 831 | let (dx, dy, mode) = match w.delta { |
| 832 | blitz_traits::events::BlitzWheelDelta::Pixels(x, y) => (x, y, 0), |
| 833 | blitz_traits::events::BlitzWheelDelta::Lines(x, y) => (x, y, 1), |
| 834 | }; |
| 835 | ev.insert("deltaX".into(), json!(dx)); |
| 836 | ev.insert("deltaY".into(), json!(dy)); |
| 837 | ev.insert("deltaMode".into(), json!(mode)); |
| 838 | } |
| 839 | DomEventData::KeyDown(k) | DomEventData::KeyUp(k) | DomEventData::KeyPress(k) => { |
| 840 | ev.insert("key".into(), json!(k.key.to_string())); |
| 841 | ev.insert("code".into(), json!(k.code.to_string())); |
| 842 | ev.insert("repeat".into(), json!(k.is_auto_repeating)); |
| 843 | } |
| 844 | DomEventData::Input(i) => { |
| 845 | ev.insert("inputType".into(), json!("insertText")); |
| 846 | ev.insert("data".into(), json!(i.value)); |
| 847 | } |
| 848 | _ => {} |
| 849 | } |
| 850 | // Form control state travels with every event (the sandbox mirror relies on it). |
| 851 | { |
| 852 | let base = doc.inner(); |
| 853 | if let Some(NodeData::Element(el)) = base.get_node(event.target).map(|n| &n.data) { |
| 854 | if el.name.local == local_name!("input") { |
| 855 | if let Some(c) = el.checkbox_input_checked() { |
| 856 | ev.insert("checked".into(), json!(c)); |
| 857 | } |
| 858 | if let Some(t) = el.text_input_data() { |
| 859 | ev.insert("value".into(), json!(t.editor.raw_text())); |
| 860 | } else if let Some(v) = el.attr(local_name!("value")) { |
| 861 | ev.insert("value".into(), json!(v)); |
| 862 | } |
| 863 | } else if el.name.local == local_name!("textarea") { |
| 864 | if let Some(t) = el.text_input_data() { |
| 865 | ev.insert("value".into(), json!(t.editor.raw_text())); |
| 866 | } |
| 867 | } |
| 868 | } |
| 869 | } |
| 870 | self.out.push(Value::Object(ev)); |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | #[cfg(test)] |
| 875 | mod tests { |
| 876 | use super::*; |
| 877 | use parley::fontique::GenericFamily; |
| 878 | |
| 879 | fn ops_for(text: &str) -> Value { |
| 880 | json!({ "type": "ops", "ops": [ |
| 881 | { "op": "el", "id": 1, "tag": "body", "adopt": "body" }, |
| 882 | { "op": "el", "id": 2, "tag": "p", "attrs": [["style", "font-size:32px;margin:0"]] }, |
| 883 | { "op": "text", "id": 3, "data": text }, |
| 884 | { "op": "ins", "id": 3, "parent": 2 }, |
| 885 | { "op": "ins", "id": 2, "parent": 1 }, |
| 886 | ]}) |
| 887 | } |
| 888 | |
| 889 | /// Non-transparent pixels in the first 48×48 px of the document. |
| 890 | fn painted(r: &mut Renderer) -> usize { |
| 891 | let (w, _h) = r.viewport_px(); |
| 892 | let px = r.render(); |
| 893 | let mut n = 0; |
| 894 | for y in 0..48 { |
| 895 | for x in 0..48 { |
| 896 | let i = ((y * w as usize) + x) * 4; |
| 897 | if i + 3 < px.len() && px[i + 3] > 0 { n += 1; } |
| 898 | } |
| 899 | } |
| 900 | n |
| 901 | } |
| 902 | |
| 903 | fn render(fonts: FontContext, text: &str) -> usize { |
| 904 | render_with(fonts, text, Backend::Vello) |
| 905 | } |
| 906 | |
| 907 | fn render_with(fonts: FontContext, text: &str, backend: Backend) -> usize { |
| 908 | let mut r = Renderer::new(200.0, 1.0, false, fonts); |
| 909 | r.set_backend(backend); |
| 910 | r.receive(&ops_for(text)); |
| 911 | painted(&mut r) |
| 912 | } |
| 913 | |
| 914 | /// The CoreGraphics backend draws the same document through CoreText: a letter, a |
| 915 | /// bold letter (variation axis on the system font) and a colour emoji all paint. |
| 916 | #[cfg(target_vendor = "apple")] |
| 917 | #[test] |
| 918 | fn coregraphics_backend_paints_text_and_emoji() { |
| 919 | let fonts = crate::fonts(); |
| 920 | let letter = render_with(fonts.clone(), "x", Backend::CoreGraphics); |
| 921 | let emoji = render_with(fonts.clone(), "🪐", Backend::CoreGraphics); |
| 922 | let mut r = Renderer::new(200.0, 1.0, false, fonts); |
| 923 | r.set_backend(Backend::CoreGraphics); |
| 924 | r.receive(&json!({ "type": "ops", "ops": [ |
| 925 | { "op": "el", "id": 1, "tag": "body", "adopt": "body" }, |
| 926 | { "op": "el", "id": 2, "tag": "p", "attrs": [["style", "font-size:32px;margin:0;font-weight:700"]] }, |
| 927 | { "op": "text", "id": 3, "data": "x" }, |
| 928 | { "op": "ins", "id": 3, "parent": 2 }, |
| 929 | { "op": "ins", "id": 2, "parent": 1 }, |
| 930 | ]})); |
| 931 | let bold = painted(&mut r); |
| 932 | println!("coregraphics: letter {letter} px, bold {bold} px, emoji {emoji} px"); |
| 933 | assert!(letter > 20, "a letter must paint ({letter} px)"); |
| 934 | assert!(bold > letter, "bold must cover more pixels than regular ({bold} vs {letter})"); |
| 935 | assert!(emoji > 100, "the emoji must paint ({emoji} px)"); |
| 936 | } |
| 937 | |
| 938 | #[test] |
| 939 | fn emoji_is_painted_with_the_host_font() { |
| 940 | let fonts = crate::fonts(); |
| 941 | let letter = render(fonts.clone(), "x"); |
| 942 | let emoji = render(fonts, "🪐"); |
| 943 | println!("host font: letter {letter} px, emoji {emoji} px"); |
| 944 | assert!(letter > 20, "a letter must paint"); |
| 945 | assert!(emoji > 100, "the emoji must paint ({emoji} px)"); |
| 946 | } |
| 947 | |
| 948 | /// Documents the iOS gap: the iOS emoji font's sbix glyphs are `emjc`, not PNG, so |
| 949 | /// nothing is painted. Run with TW_IOS_EMOJI_FONT=<path to AppleColorEmoji-160px.ttc |
| 950 | /// from a simulator runtime> to see it; it fails until glifo decodes `emjc`. |
| 951 | #[test] |
| 952 | #[ignore] |
| 953 | fn emoji_is_painted_with_the_ios_font() { |
| 954 | let path = std::env::var("TW_IOS_EMOJI_FONT").unwrap_or_default(); |
| 955 | if !std::path::Path::new(&path).exists() { |
| 956 | eprintln!("TW_IOS_EMOJI_FONT not set; skipping"); |
| 957 | return; |
| 958 | } |
| 959 | let mut fcx = crate::fonts(); |
| 960 | fcx.collection.load_fonts_from_paths([&path]); |
| 961 | let all: Vec<_> = fcx.collection.family_ids().collect(); |
| 962 | let ids: Vec<_> = all.into_iter().filter(|id| fcx.collection.family_name(*id).map(|n |
| 963 | let names: Vec<String> = ids.iter().filter_map(|id| fcx.collection.family_name(*id).map( |
| 964 | println!("emoji families after loading the iOS font: {names:?}"); |
| 965 | fcx.collection.set_generic_families(GenericFamily::Emoji, ids.into_iter().take(1)); |
| 966 | let emoji = render(fcx.clone(), "🪐"); |
| 967 | #[cfg(target_vendor = "apple")] |
| 968 | { |
| 969 | let cg = render_with(fcx.clone(), "🪐", Backend::CoreGraphics); |
| 970 | let mut r = Renderer::new(200.0, 1.0, false, fcx); |
| 971 | r.set_backend(Backend::CoreGraphics); |
| 972 | r.receive(&ops_for("🪐")); |
| 973 | let (w, _) = r.viewport_px(); |
| 974 | let px = r.render(); |
| 975 | let total = px.chunks(4).filter(|p| p[3] > 0).count(); |
| 976 | let xs: Vec<usize> = px.chunks(4).enumerate().filter(|(_, p)| p[3] > 0 |
| 977 | println!("ios font: emoji {emoji} px on vello, {cg} px on CoreGraphics (whole frame {total} px, x range {:?}..{:?})", xs.iter().min(), xs.iter().max()); |
| 978 | } |
| 979 | #[cfg(not(target_vendor = "apple"))] |
| 980 | println!("ios font: emoji {emoji} px"); |
| 981 | assert!(emoji > 100, "the emoji must paint with the iOS font ({emoji} px)"); |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | #[cfg(test)] |
| 986 | mod font_probe { |
| 987 | use skrifa::bitmap::{BitmapData, BitmapStrikes}; |
| 988 | use skrifa::instance::Size; |
| 989 | use skrifa::string::StringId; |
| 990 | use skrifa::{FontRef, MetadataProvider}; |
| 991 | |
| 992 | fn probe(path: &str) { |
| 993 | let data = std::fs::read(path).unwrap(); |
| 994 | for index in 0..4 { |
| 995 | let Ok(font) = FontRef::from_index(&data, index) else { break }; |
| 996 | let ps: Vec<String> = font.localized_strings(StringId::POSTSCRIPT_NAME).map(|s| s.to_string()).collect(); |
| 997 | let fam: Vec<String> = font.localized_strings(StringId::FAMILY_NAME).map(|s| s.to_string()).collect(); |
| 998 | let strikes = BitmapStrikes::new(&font); |
| 999 | let ppems: Vec<f32> = strikes.iter().map(|s| s.ppem()).collect(); |
| 1000 | let gid = font.charmap().map('🪐'); |
| 1001 | let glyph = gid.and_then(|g| strikes.glyph_for_size(Size::new(32.0), g)); |
| 1002 | let kind = glyph.as_ref().map(|g| match &g.data { |
| 1003 | BitmapData::Png(d) => format!("png {} bytes, magic {:02x?}", d.len(), &d[..4.min(d.len())]), |
| 1004 | BitmapData::Bgra(d) => format!("bgra {} bytes", d.len()), |
| 1005 | BitmapData::Mask(_) => "mask".to_string(), |
| 1006 | }); |
| 1007 | println!("{} #{index}: family {fam:?} ps {ps:?} format {:?} strikes {ppems:?} gid {gid:?} glyph {kind:?}", path.rsplit('/').next().unwrap(), strikes.format()); |
| 1008 | } |
| 1009 | } |
| 1010 | |
| 1011 | #[test] |
| 1012 | #[ignore] |
| 1013 | fn probe_emoji_fonts() { |
| 1014 | probe("/System/Library/Fonts/Apple Color Emoji.ttc"); |
| 1015 | if let Ok(p) = std::env::var("TW_IOS_EMOJI_FONT") { probe(&p); } |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | #[cfg(test)] |
| 1020 | mod sbix_probe { |
| 1021 | use skrifa::raw::TableProvider; |
| 1022 | use skrifa::{FontRef, MetadataProvider}; |
| 1023 | |
| 1024 | /// Prints the sbix graphic type per strike: `png ` on macOS, `emjc` in the iOS font. |
| 1025 | #[test] |
| 1026 | #[ignore] |
| 1027 | fn probe_sbix_strikes() { |
| 1028 | let Ok(p) = std::env::var("TW_IOS_EMOJI_FONT") else { return }; |
| 1029 | for path in ["/System/Library/Fonts/Apple Color Emoji.ttc", p.as_str()] { |
| 1030 | let data = std::fs::read(path).unwrap(); |
| 1031 | let font = FontRef::from_index(&data, 0).unwrap(); |
| 1032 | let gid = font.charmap().map('🪐').unwrap(); |
| 1033 | let sbix = font.sbix().unwrap(); |
| 1034 | for strike in sbix.strikes().iter() { |
| 1035 | let strike = strike.unwrap(); |
| 1036 | let g = strike.glyph_data(gid); |
| 1037 | let desc = match g { |
| 1038 | Ok(Some(g)) => format!("type {:?} {} bytes origin ({}, {})", std::str::from_utf8(&g.graphic_type().to_be_bytes()).unwrap_or("?"), g |
| 1039 | Ok(None) => "none".to_string(), |
| 1040 | Err(e) => format!("err {e}"), |
| 1041 | }; |
| 1042 | println!("{} strike {} ppem: {desc}", path.rsplit('/').next().unwrap(), strike.ppem()); |
| 1043 | } |
| 1044 | } |
| 1045 | } |
| 1046 | } |
| 1047 | |