From de8688ba2020bd09e5b8a5df5db79aef46cb0690 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 20 Nov 2026 14:48:15 -0700 Subject: [PATCH] feat(export): embedded glyph outlines for dynamic text fields in the HTML page, with the fsType licence check (M5) --- crates/doc/src/lib.rs | 20 ++- crates/engine/src/cmds_file.rs | 10 +- crates/engine/src/cmds_text.rs | 10 +- crates/engine/src/embed.rs | 124 +++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/tests_script.rs | 71 +++++++++++ crates/engine/src/tests_warp.rs | 2 +- crates/render/src/html.rs | 50 +++++++- crates/render/src/html/canvas.js | 65 +++++++++- crates/render/src/html/player.js | 139 ++++++++++++++++++++- crates/render/src/html_tests.rs | 73 +++++++++++ crates/text/src/embed.rs | 198 ++++++++++++++++++++++++++++++ crates/text/src/lib.rs | 2 + src/panels.rs | 36 ++++++ 14 files changed, 791 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/embed.rs create mode 100644 crates/text/src/embed.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6f240665..d951c220 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1005,6 +1005,22 @@ pub struct TextField { /// run in the timeline the field is on, as an instance's event handlers are. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub on_change: Vec, + /// The characters whose glyph outlines the HTML export carries for this field's font + /// (ADR 0107), so text a script sets is drawn in the author's font where the font's licence + /// allows; empty: the viewer's browser fonts. Each character once, at most + /// [`MAX_EMBED_CHARS`]. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub embed: String, +} + +/// Most characters a field embeds. +pub const MAX_EMBED_CHARS: usize = 1024; + +/// A list of characters to embed as a field keeps it: each once, in order, no control +/// characters, at most [`MAX_EMBED_CHARS`]. +pub fn embed_chars(chars: &str) -> String { + let mut seen = std::collections::BTreeSet::new(); + chars.chars().take(MAX_EMBED_CHARS * 64).filter(|c| !c.is_control() && seen.insert(*c)).take(MAX_EMBED_CHARS).collect() } fn black() -> Rgba { @@ -1017,7 +1033,7 @@ fn white() -> Rgba { impl TextField { /// A single-line field of `kind`. pub fn new(kind: TextKind) -> TextField { - TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new(), on_change: Vec::new() } + TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new(), on_change: Vec::new(), embed: String::new() } } /// The width text wraps at in a box `box_width` wide, if its lines wrap. @@ -1039,7 +1055,7 @@ impl TextField { pub fn sanitized(&self) -> TextField { let mut on_change = self.on_change.clone(); actions::sanitize_actions(&mut on_change); - TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), on_change, ..self.clone() } + TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), on_change, embed: embed_chars(&self.embed), ..self.clone() } } } diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 78f73cd6..34088564 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -861,9 +861,14 @@ fn export_html(s: &mut Session, p: &Value) -> Result { Some(t) if !t.trim().is_empty() => t.to_string(), _ => stem, }; - let opts = anicraft_render::html::HtmlOptions { title, sound: opt_bool(p, "sound")?.unwrap_or(true), fit: opt_bool(p, "fit")?.unwrap_or(true) }; let started = web_time::Instant::now(); - let out = anicraft_render::html::to_html(&s.doc, &opts).map_err(EngineError::Param)?; + // Glyph outlines for fields that embed characters (ADR 0107), where the fonts allow it. + let embedded = crate::embed::embedded_faces(&s.doc); + let opts = anicraft_render::html::HtmlOptions { title, sound: opt_bool(p, "sound")?.unwrap_or(true), fit: opt_bool(p, "fit")?.unwrap_or(true), fonts: embedded.faces }; + let mut out = anicraft_render::html::to_html(&s.doc, &opts).map_err(EngineError::Param)?; + for (note, n) in embedded.notes { + out.report.insert(note, n); + } crate::vfs::write(&path, out.html.as_bytes())?; let summary = if out.report.is_empty() { String::new() @@ -886,6 +891,7 @@ fn export_html(s: &mut Session, p: &Value) -> Result { "ms": started.elapsed().as_millis() as u64, "report": summary, "notes": out.report, + "fonts": embedded.summary, })) } diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index faff585c..0ee4e815 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { ), c("text.path", "Text on Path", "", None, "{offset? (px along the path), flip?: bool (along the path backwards, on its other side), release?: bool (back to lines of text where it starts)} on the selected text on a path (ADR 0070)", true, |s, p| s.each_layer(false, |s| set_path(s, p))), c("text.release_path", "Release Text from Path", "Modify/Text", None, "{} the selected text on a path goes back to lines of text (ADR 0070)", true, |s, _| s.each_layer(false, |s| set_path(s, &json!({"release": true})))), - c("text.field", "Text Type", "", None, "{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)", true, |s, p| s.each_layer(false, |s| set_field(s, p))), + c("text.field", "Text Type", "", None, "{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run), embed?: characters whose glyph outlines the HTML export carries for this field's font, so text a script sets is drawn in it where the font's licence allows (\"\": none; ADR 0107)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)", true, |s, p| s.each_layer(false, |s| set_field(s, p))), ] } @@ -576,6 +576,11 @@ fn set_field(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("'max_chars' is at most {MAX_FIELD_CHARS}"))); } let variable = opt_str(p, "variable")?.map(|v| v.trim().chars().take(MAX_FIELD_NAME).collect::()); + let embed = match opt_str(p, "embed")? { + Some(e) if e.chars().count() > anicraft_doc::MAX_EMBED_CHARS * 4 => return Err(EngineError::Param(format!("'embed' is at most {} characters", anicraft_doc::MAX_EMBED_CHARS * 4))), + Some(e) => Some(anicraft_doc::embed_chars(e)), + None => None, + }; let (selectable, border, background) = (opt_bool(p, "selectable")?, opt_bool(p, "border")?, opt_bool(p, "background")?); let (border_color, background_color) = (opt_color(p, "border_color")?, opt_color(p, "background_color")?); let mut changed = 0; @@ -630,6 +635,9 @@ fn set_field(s: &mut Session, p: &Value) -> Result { if let Some(v) = &variable { f.variable.clone_from(v); } + if let Some(e) = &embed { + f.embed.clone_from(e); + } let (b, n, _) = lay_out_block(&TextBlock { field: Some(f.sanitized()), box_width: width.unwrap_or(bw), box_height: height.unwrap_or(bh), ..(**t).clone() })?; (b, n) }; diff --git a/crates/engine/src/embed.rs b/crates/engine/src/embed.rs new file mode 100644 index 00000000..ba798ed0 --- /dev/null +++ b/crates/engine/src/embed.rs @@ -0,0 +1,124 @@ +//! Embedded glyphs for the HTML export (ADR 0107): the outlines of the characters text fields +//! ask to embed, read from this computer's fonts where their licence bits allow, so text a +//! script sets in a dynamic field is drawn in the author's font in any browser. +//! +//! The export itself (`anicraft_render::html`) has no fonts: it draws what it is handed. A +//! face whose `OS/2` `fsType` forbids embedding, or allows it only whole, is left out and +//! named, and the page draws that field with the browser's fonts as before. + +use anicraft_doc::{Document, ElementKind, TextKind, Timeline}; +use anicraft_render::html::EmbeddedFace; +use anicraft_text::{Embedding, Fonts}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// Most faces one page embeds. +pub const MAX_EMBEDDED_FACES: usize = 32; + +/// What an export embeds, and what it says about it. +#[derive(Clone, Debug, Default)] +pub struct Embedded { + pub faces: Vec, + /// Lines for the export's report, with a count each. + pub notes: Vec<(String, usize)>, + /// The same as data: every face asked for, whether it was embedded and why not. + pub summary: Value, +} + +/// `(family, bold, italic)` → the characters asked for, over every field of the document. +fn wanted(doc: &Document) -> (BTreeMap<(String, bool, bool), String>, usize) { + fn walk(tl: &Timeline, depth: usize, out: &mut BTreeMap<(String, bool, bool), String>, inputs: &mut usize) { + if depth > anicraft_doc::MAX_SYMBOL_DEPTH { + return; + } + for l in &tl.layers { + for k in &l.keyframes { + for e in &k.elements { + match &e.kind { + ElementKind::Text(t) => { + let Some(f) = t.field.as_ref().filter(|f| !f.embed.is_empty()) else { continue }; + // An input field is a native element in the page: the browser + // draws what is typed. + if f.kind == TextKind::Input { + *inputs += 1; + continue; + } + out.entry((t.font.clone(), t.bold, t.italic)).or_default().push_str(&f.embed); + } + ElementKind::Group { members } => walk(members, depth + 1, out, inputs), + _ => {} + } + } + } + } + } + let mut out = BTreeMap::new(); + let mut inputs = 0; + for s in &doc.scenes { + walk(&s.timeline, 0, &mut out, &mut inputs); + } + for s in &doc.library { + walk(&s.timeline, 0, &mut out, &mut inputs); + } + (out, inputs) +} + +/// The faces `doc`'s fields ask to embed, with this computer's fonts. +pub fn embedded_faces(doc: &Document) -> Embedded { + embedded_with(doc, Fonts::get()) +} + +/// [`embedded_faces`] with a given font library. +pub fn embedded_with(doc: &Document, fonts: &Fonts) -> Embedded { + let (wanted, inputs) = wanted(doc); + let mut out = Embedded::default(); + let mut rows: Vec = Vec::new(); + let (mut glyphs, mut refused, mut missing_faces, mut missing_chars) = (0usize, 0usize, 0usize, 0usize); + for ((family, bold, italic), chars) in wanted.into_iter().take(MAX_EMBEDDED_FACES) { + let chars = anicraft_doc::embed_chars(&chars); + let table = fonts.glyph_table(&family, bold, italic, &chars).filter(|t| t.family.eq_ignore_ascii_case(family.trim())); + let row = |state: &str, n: usize| json!({"family": family, "bold": bold, "italic": italic, "embedded": state == "embedded", "state": state, "glyphs": n}); + let Some(table) = table else { + // The font isn't on this computer (a fallback's glyphs would be the wrong face). + missing_faces += 1; + rows.push(row("not installed", 0)); + continue; + }; + match table.embedding { + Embedding::Subset => { + glyphs += table.glyphs.len(); + missing_chars += table.missing; + rows.push(row("embedded", table.glyphs.len())); + out.faces.push(EmbeddedFace { + family: family.clone(), + bold, + italic, + ascent: table.ascent, + line_height: table.line_height, + glyphs: table.glyphs.into_iter().map(|g| (g.ch, g.advance, Arc::new(g.outline))).collect(), + }); + } + Embedding::Whole => { + refused += 1; + rows.push(row("its licence allows embedding only the whole font", 0)); + } + Embedding::Forbidden => { + refused += 1; + rows.push(row("its licence doesn't allow embedding", 0)); + } + } + } + let mut note = |text: &str, n: usize| { + if n > 0 { + out.notes.push((text.to_string(), n)); + } + }; + note("glyph outlines embedded for text fields (drawn without kerning or ligatures)", glyphs); + note("fonts not embedded because their licence doesn't allow it (those fields use the browser's fonts)", refused); + note("fonts to embed that aren't installed on this computer (those fields use the browser's fonts)", missing_faces); + note("characters to embed that the font doesn't have", missing_chars); + note("input fields with characters to embed (what the viewer types is drawn by the browser)", inputs); + out.summary = Value::Array(rows); + out +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2b9a98b6..37ef49ba 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -51,6 +51,7 @@ pub mod cmds_audio_keys; pub mod cmds_data; pub mod data_import; pub mod cmds_text; +pub mod embed; mod cmds_timeline; mod cmds_view; mod cmds_width; diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index eaa22b1a..e04a7026 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -321,3 +321,74 @@ fn html_text_change_events_and_limits_run_in_test_movie() { assert!(v["output"].as_array().unwrap().iter().any(|l| l["line"] == "ab"), "{}", v["output"]); } +/// Embedded glyphs (ADR 0107) through the commands: `text.field {embed}` keeps each character +/// once, the HTML export carries the outlines where the font's licence allows and says what it +/// did, and a document without embedded characters exports exactly as before. +#[test] +fn fields_embed_glyph_outlines_in_the_html_export() { + if anicraft_text::Fonts::get().families().is_empty() { + return; + } + let mut s = Session::default(); + let ok = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + ok(&mut s, "text.create", json!({"text": "Score: 0", "type": "dynamic", "x": 20, "y": 20, "size": 20})); + ok(&mut s, "instance.set_name", json!({"name": "score_txt"})); + ok(&mut s, "script.set", json!({"frame": 0, "text": "score_txt.text = \"Score: 12\";"})); + let dir = std::env::temp_dir().join(format!("anicraft-embed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let page = |s: &mut Session, name: &str| { + let file = dir.join(name); + let v = s.execute("file.export_html", &json!({"path": file.display().to_string()})).unwrap(); + (v, std::fs::read_to_string(&file).unwrap()) + }; + let (before, html) = page(&mut s, "plain.html"); + assert!(!html.contains("\"fonts\":") && before["fonts"].as_array().is_some_and(Vec::is_empty), "{before}"); + // Characters to embed: each once, controls dropped; one undo step; saved with the field. + let steps = s.history().undo_len(); + ok(&mut s, "text.field", json!({"embed": "Score: 0123456789 Score\u{7}"})); + assert_eq!(s.history().undo_len(), steps + 1); + let field = |s: &Session| match &s.doc.timeline(0).layers[0].keyframes[0].elements[0].kind { + ElementKind::Text(t) => t.field.clone().unwrap(), + _ => panic!("text"), + }; + assert_eq!(field(&s).embed, "Score: 0123456789"); + let saved = crate::format::to_json(&s.doc).unwrap(); + assert_eq!(crate::format::from_json(&saved).unwrap(), s.doc); + assert!(s.execute("text.field", &json!({"embed": "x".repeat(anicraft_doc::MAX_EMBED_CHARS * 4 + 1)})).is_err()); + let (v, html) = page(&mut s, "embedded.html"); + let rows = v["fonts"].as_array().unwrap(); + assert_eq!(rows.len(), 1, "{v}"); + match rows[0]["state"].as_str().unwrap() { + // The usual case: the outlines are in the page, and the report counts them. + "embedded" => { + let n = rows[0]["glyphs"].as_u64().unwrap(); + assert!(n >= 10 && n <= 17, "{v}"); + assert!(html.contains("\"fonts\":[{"), "the page carries the face"); + assert!(v["notes"].as_object().unwrap().iter().any(|(k, c)| k.starts_with("glyph outlines embedded") && c.as_u64() == Some(n)), "{v}"); + assert!(html.len() > before["bytes"].as_u64().unwrap() as usize, "the glyphs add to the page"); + } + // A computer whose default face forbids embedding: nothing embedded, and it says so. + other => { + assert!(!html.contains("\"fonts\":"), "{other}"); + assert!(v["notes"].as_object().unwrap().keys().any(|k| k.contains("licence") || k.contains("installed")), "{v}"); + } + } + // An input field's embedded characters are noted, not used: the browser draws what is typed. + ok(&mut s, "text.field", json!({"type": "input"})); + let (v, _) = page(&mut s, "input.html"); + assert!(v["fonts"].as_array().unwrap().is_empty() && v["notes"].as_object().unwrap().keys().any(|k| k.starts_with("input fields with characters to embed")), "{v}"); + // A font that isn't on this computer is never swapped for another face's glyphs. + ok(&mut s, "text.field", json!({"type": "dynamic"})); + let mut doc = s.doc.clone(); + { + let l = std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut doc.scenes[0]).timeline.layers[0]); + let k = std::sync::Arc::make_mut(&mut l.keyframes[0]); + if let ElementKind::Text(t) = &mut std::sync::Arc::make_mut(&mut k.elements[0]).kind { + std::sync::Arc::make_mut(t).font = "No Such Family 12345".into(); + } + } + let e = crate::embed::embedded_faces(&doc); + assert!(e.faces.is_empty() && e.summary[0]["state"] == "not installed", "{:?}", e.summary); + std::fs::remove_dir_all(&dir).ok(); +} + diff --git a/crates/engine/src/tests_warp.rs b/crates/engine/src/tests_warp.rs index 1a3aab39..a65016da 100644 --- a/crates/engine/src/tests_warp.rs +++ b/crates/engine/src/tests_warp.rs @@ -172,7 +172,7 @@ fn a_bitmap_bends_in_every_renderer_and_export() { // SVG bakes the bent image; the HTML page reports it. let svg = crate::cmds_file::frame_svg(&s.doc, 0); assert!(svg.contains(", } impl Default for HtmlOptions { fn default() -> Self { - HtmlOptions { title: "AniCraft movie".into(), sound: true, fit: true } + HtmlOptions { title: "AniCraft movie".into(), sound: true, fit: true, fonts: Vec::new() } } } +/// The em size [`EmbeddedFace`] outlines and advances are given at. +pub const EMBED_EM: f32 = 1000.0; +/// Most glyphs the page carries over all faces. +pub const MAX_EMBEDDED_GLYPHS: usize = 16_384; + +/// One face's glyphs for the page (ADR 0107): the page draws a dynamic field's changed text +/// with them when every character of a stretch is here, else with the browser's fonts. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EmbeddedFace { + pub family: String, + pub bold: bool, + pub italic: bool, + /// The face's ascent and line height at [`EMBED_EM`]. + pub ascent: f32, + pub line_height: f32, + /// Each character's advance and outline at [`EMBED_EM`] (the pen on the baseline at the + /// origin, y down). + pub glyphs: Vec<(char, f32, Arc)>, +} + /// Counts of what the export holds. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct HtmlStats { @@ -1058,6 +1082,30 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { "images": b.images, "sounds": b.sounds, }); + let mut json = json; + // Embedded glyphs: `fonts` is a list of faces `{f: family, b, i, a: ascent, lh: line + // height, g: {character: [advance, path]}}`, sizes at 1000 px to the em. + let mut budget = MAX_EMBEDDED_GLYPHS; + let fonts: Vec = opts + .fonts + .iter() + .filter(|f| !f.glyphs.is_empty() && f.ascent.is_finite() && f.line_height.is_finite()) + .map(|f| { + let mut g = Map::new(); + for (ch, advance, outline) in f.glyphs.iter().filter(|g| g.1.is_finite()) { + if budget == 0 { + break; + } + budget -= 1; + g.insert(ch.to_string(), json!([num(*advance, 100.0), b.path(outline)])); + } + json!({"f": f.family, "b": f.bold, "i": f.italic, "a": num(f.ascent, 100.0), "lh": num(f.line_height, 100.0), "g": g}) + }) + .collect(); + if !fonts.is_empty() { + json["fonts"] = Value::Array(fonts); + json["paths"] = json!(b.path_d); + } let stats = HtmlStats { timelines: json["timelines"].as_array().map_or(0, Vec::len), frames, diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 71c3e47f..6b1bffd0 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -342,6 +342,55 @@ g.fillText(lines[i], x, y); } } + // A style's font for the canvas. + function styleFont(st) { + const family = String(st.font || "").replace(/["\\\r\n;{}]/g, ""); + return (st.italic ? "italic " : "") + (st.bold ? "bold " : "") + st.size + "px " + (family ? '"' + family + '", ' : "") + "sans-serif"; + } + // Changed text in styles of its own (`htmlText`), or in a face whose glyphs the page carries + // (ADR 0107): laid out by the player's `fieldLayout`, then each stretch drawn in its colour, + // by its embedded outlines when it has them, else with the browser's fonts; underlines under. + function fieldRich(g, f, styles) { + const tf = f.tf; + const shown = tf.k === "input" && tf.ln === "password" ? Array.from(f.text, () => "*").join("") : f.text; + g.textBaseline = "alphabetic"; + g.textAlign = "left"; + const measure = (st, t) => { + g.font = styleFont(st); + if ("letterSpacing" in g) g.letterSpacing = st.ls + "px"; + return g.measureText(t).width; + }; + const lines = AniCraft.fieldLayout(tf, shown, styles, movie.fonts, measure); + for (const line of lines) { + if (line.top > tf.h) break; + for (const s of line.segs) { + const st = s.st; + g.fillStyle = css(AniCraft.applyEffect(f.c, [st.color[0] / 255, st.color[1] / 255, st.color[2] / 255, 1])); + if (s.face) { + const k = st.size / 1000; + let x = s.x; + for (const c of Array.from(s.text)) { + const glyph = s.face.g[c]; + const p = paths[glyph[1]]; + if (p) { + g.save(); + g.translate(x, line.base); + g.scale(k, k); + g.fill(p); + g.restore(); + } + x += glyph[0] * k + st.ls; + } + } else { + g.font = styleFont(st); + if ("letterSpacing" in g) g.letterSpacing = st.ls + "px"; + g.fillText(s.text, s.x, line.base); + } + if (st.u) g.fillRect(s.x, line.base + st.size * 0.08, s.w, Math.max(st.size * 0.06, 1)); + } + } + if ("letterSpacing" in g) g.letterSpacing = "0px"; + } // One field on layer `L` (`set` places a layer's context by a stage transform); input fields // with an instance path go into `seen`, to get their elements. function drawField(L, f, set, seen) { @@ -371,7 +420,13 @@ g.fillStyle = fieldColour(f); g.fill(p); } - } else fieldText(g, f); + } else { + // Styled text and embedded faces go through the layout; plain text in a browser font + // is drawn as it always was. + const styles = AniCraft.fieldStyles({ text: f.text, rich: f.rich }, tf); + if (f.rich !== null || (movie.fonts && styles.runs.some((r) => AniCraft.embeddedFace(movie.fonts, r.s) !== null))) fieldRich(g, f, styles); + else fieldText(g, f); + } g.restore(); } if (tf.bd) { @@ -417,6 +472,8 @@ if (v === null) return; if (v !== el.value) el.value = v; el._shown = v; + // The field's change event ran (ADR 0107): its traces and sounds. + if (player.changed) report(player.changed); draw(); }; el.addEventListener("input", (e) => { @@ -458,6 +515,12 @@ el.style.caretColor = colour; el._colour = colour; } + // A script set `maxChars`. + if (el._mx !== f.mx) { + if (f.mx > 0) el.maxLength = f.mx; + else el.removeAttribute("maxlength"); + el._mx = f.mx; + } // A script set its text (setting it unchanged would move the viewer's caret). const v = f.text !== null ? f.text : f.tf.t; if (v !== el._shown && !el._composing) { diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index 6736e506..21dcc7ad 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -460,7 +460,9 @@ var AniCraft = (function () { for (const it of items) dl.items.push(it); if (!v) return; // `rich`: the styles changed text is drawn in when a script set them (`htmlText`). - if (v.field) v.field({ tf: tf, name: name, m: xf, c: color, clip: clip, group: group, key: key, text: text, rich: text !== null && fs && fs.rich !== null ? fs.rich : null, focused: focused, items: items }); + // `rich`: the styles changed text is drawn in when a script set them (`htmlText`); `mx`: + // the most characters the viewer may type now. + if (v.field) v.field({ tf: tf, name: name, m: xf, c: color, clip: clip, group: group, key: key, text: text, rich: text !== null && fs && fs.rich !== null ? fs.rich : null, mx: fieldMax(fs, tf), focused: focused, items: items }); else for (const it of items) v.item(it); } @@ -2457,6 +2459,139 @@ var AniCraft = (function () { return ok; } + // ----- laying out changed text for the page (ADR 0107) --------------------------------------- + // + // Text a script or the viewer changed has no outline: the page lays it out. This is the part + // of that with no canvas in it, so the tests can run it: `text` in `styles` ({ runs, paras }) + // broken into lines (where it breaks, and in a Multiline field wrapped at the box less its + // gutters, greedily at spaces, across runs), each line a list of stretches in one style with + // their place. A stretch whose face is embedded (`faces`, the movie's `fonts`) and has every + // character is measured by its glyphs' advances and carries the face, for the page to draw + // its outlines; any other is measured by `measure(style, text)` (the browser's fonts). + const MAX_LINES = 1000; + function embeddedFace(faces, st) { + for (const f of faces || []) if (f.f === st.font && !!f.b === st.bold && !!f.i === st.italic) return f; + return null; + } + function fieldLayout(tf, text, styles, faces, measure) { + const chars = Array.from(text); + const runs = styles.runs, paras = styles.paras; + if (runs.length === 0) return []; + const wrap = tf.ln === "multiline" ? Math.max(tf.w - 4, 1) : 0; + const lsp = (tf.font && tf.font.lsp) || 0; + // A stretch of characters in run `k`, measured. + const token = (cs, k, space) => { + const st = runs[k] ? runs[k].s : runs[runs.length - 1].s; + let face = embeddedFace(faces, st); + let w = 0; + if (face !== null) { + for (const c of cs) { + const g = face.g[c]; + if (g === undefined) { + face = null; + break; + } + w += (g[0] * st.size) / 1000 + st.ls; + } + } + const t = cs.join(""); + if (face === null) w = measure(st, t); + return { text: t, st: st, w: w, face: face, space: space }; + }; + const lines = []; + let top = 2; + let run = 0, left = runs.length > 0 ? runs[0].n : Infinity; + const runAt = () => { + while (run < runs.length - 1 && left <= 0) { + run += 1; + left = runs[run].n; + } + left -= 1; + return run; + }; + const flush = (toks, para, firstRun) => { + while (toks.length > 0 && toks[toks.length - 1].space) toks.pop(); + // Room above and below the baseline: the most any stretch needs (an empty line: the run + // its paragraph starts in). + const metric = (st, face) => (face ? [(face.a * st.size) / 1000, (face.lh * st.size) / 1000] : [st.size * 0.95, st.size * 1.2]); + let asc = 0, below = 0; + if (toks.length === 0) { + const st = runs[firstRun] ? runs[firstRun].s : runs[runs.length - 1].s; + const m = metric(st, embeddedFace(faces, st)); + asc = m[0]; + below = m[1] - m[0]; + } + let w = 0; + for (const t of toks) { + const m = metric(t.st, t.face); + asc = Math.max(asc, m[0]); + below = Math.max(below, m[1] - m[0]); + w += t.w; + } + const al = (paras[para] || paras[paras.length - 1] || { al: "left" }).al; + let x = al === "center" ? (tf.w - w) / 2 : al === "right" ? tf.w - 2 - w : 2; + const segs = []; + for (const t of toks) { + const last = segs[segs.length - 1]; + // Neighbours in one style and face draw as one stretch. + if (last && last.st === t.st && last.face === t.face) { + last.text += t.text; + last.w += t.w; + } else segs.push({ text: t.text, st: t.st, x: x, w: t.w, face: t.face }); + x += t.w; + } + const h = Math.max(asc + below + lsp, 1); + if (lines.length < MAX_LINES) lines.push({ top: top, base: top + asc, h: h, w: w, segs: segs }); + top += h; + }; + let para = 0; + let toks = [], width = 0, breakAt = -1, firstRun = 0, started = false; + let word = [], wordRun = -1, wordSpace = false; + const endWord = () => { + if (word.length === 0) return; + const t = token(word, wordRun, wordSpace); + word = []; + if (wrap && !t.space && width + t.w > wrap && toks.length > 0) { + // Wrap: at the last space if there is one, else here. + const rest = breakAt >= 0 ? toks.splice(breakAt) : []; + flush(toks, para, firstRun); + toks = rest; + width = rest.reduce((s, x) => s + x.w, 0); + breakAt = -1; + } + toks.push(t); + width += t.w; + if (t.space) breakAt = toks.length; + }; + for (const c of chars) { + const k = runAt(); + if (!started) { + firstRun = k; + started = true; + } + if (c === "\n") { + endWord(); + flush(toks, para, firstRun); + toks = []; + width = 0; + breakAt = -1; + para += 1; + started = false; + continue; + } + const space = c === " "; + if (word.length > 0 && (k !== wordRun || space !== wordSpace)) endWord(); + wordRun = k; + wordSpace = space; + word.push(c); + } + endWord(); + // An empty last line is in the style the text ends in. + if (!started) firstRun = run; + flush(toks, para, firstRun); + return lines; + } + // ----- text fields (player.rs, field.rs; ADR 0066) ------------------------------------------- // // In the browser the viewer types into a real or