mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-22 18:41:44 +01:00
feat(export): embedded glyph outlines for dynamic text fields in the HTML page, with the fsType licence check (M5)
This commit is contained in:
1 parent
882434838e
commit
de8688ba20
14 files changed
+791
-10
No files matched your search
+18
-2
@@ -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<actions::Action>,
|
||||
/// 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() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -861,9 +861,14 @@ fn export_html(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
"ms": started.elapsed().as_millis() as u64,
|
||||
"report": summary,
|
||||
"notes": out.report,
|
||||
"fonts": embedded.summary,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
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<Value> {
|
||||
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::<String>());
|
||||
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<Value> {
|
||||
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)
|
||||
};
|
||||
|
||||
@@ -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<EmbeddedFace>,
|
||||
/// 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<Value> = 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
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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("<image x="));
|
||||
let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions { title: "t".into(), sound: false, fit: false }).unwrap();
|
||||
let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions { title: "t".into(), sound: false, fit: false, fonts: Vec::new() }).unwrap();
|
||||
assert!(html.report.keys().any(|k| k.starts_with("warped bitmaps")), "{:?}", html.report);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,14 +56,38 @@ pub struct HtmlOptions {
|
||||
pub sound: bool,
|
||||
/// Scale the movie to fit the browser window (else it shows at its stage size).
|
||||
pub fit: bool,
|
||||
/// Glyph outlines the page carries for text fields (ADR 0107): the caller reads them from
|
||||
/// the fonts (this crate has none) for the characters fields ask to embed, where the
|
||||
/// fonts' licences allow.
|
||||
pub fonts: Vec<EmbeddedFace>,
|
||||
}
|
||||
|
||||
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<Path>)>,
|
||||
}
|
||||
|
||||
/// 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<Value> = 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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 <input> or <textarea> that canvas.js lays over
|
||||
@@ -2760,5 +2895,5 @@ var AniCraft = (function () {
|
||||
return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
||||
}
|
||||
|
||||
return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, recolours: recolours, mul: mul, meanScale: meanScale, finite: finite, htmlText: { parse: parseHtml, write: writeHtml }, restrictAllows: restrictAllows, fieldStyles: fieldStyles };
|
||||
return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, recolours: recolours, mul: mul, meanScale: meanScale, finite: finite, htmlText: { parse: parseHtml, write: writeHtml }, restrictAllows: restrictAllows, fieldStyles: fieldStyles, fieldLayout: fieldLayout, embeddedFace: embeddedFace };
|
||||
})();
|
||||
@@ -1139,6 +1139,79 @@ fn the_js_html_text_reader_and_writer_match_rust_on_any_input() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Embedded glyphs (ADR 0107): the faces handed to the export reach the page with their
|
||||
/// advances and outlines, and the page's layout measures and places text with them, falling
|
||||
/// back to the browser's fonts for a stretch with a character the face lacks.
|
||||
#[test]
|
||||
fn embedded_glyphs_reach_the_page_and_its_layout_uses_them() {
|
||||
use crate::html::EmbeddedFace;
|
||||
let doc = html_fields_doc();
|
||||
// A face for the fields' own style (Inter, bold): A and B 600 wide, a space 250, at 1000.
|
||||
let glyph = |c: char, adv: f32| (c, adv, Arc::new(if c == ' ' { Path::new() } else { Path::rect(50.0, -700.0, 500.0, 700.0) }));
|
||||
let face = EmbeddedFace { family: "Inter".into(), bold: true, italic: false, ascent: 900.0, line_height: 1200.0, glyphs: vec![glyph('A', 600.0), glyph('B', 600.0), glyph(' ', 250.0)] };
|
||||
let empty = EmbeddedFace { family: "Nothing".into(), ..EmbeddedFace::default() };
|
||||
let hostile = EmbeddedFace { family: "Bad".into(), ascent: f32::NAN, glyphs: vec![glyph('x', 1.0)], ..EmbeddedFace::default() };
|
||||
let plain = movie(&doc, &HtmlOptions::default());
|
||||
assert!(plain.json.get("fonts").is_none(), "pages without embedded glyphs are as before");
|
||||
let m = movie(&doc, &HtmlOptions { fonts: vec![face, empty, hostile], ..HtmlOptions::default() });
|
||||
let fonts = m.json["fonts"].as_array().expect("fonts");
|
||||
assert_eq!(fonts.len(), 1, "faces without glyphs or with broken metrics are left out: {fonts:?}");
|
||||
assert_eq!((fonts[0]["f"].as_str(), fonts[0]["b"].as_bool(), fonts[0]["a"].as_f64(), fonts[0]["lh"].as_f64()), (Some("Inter"), Some(true), Some(900.0), Some(1200.0)));
|
||||
let a = &fonts[0]["g"]["A"];
|
||||
assert_eq!(a[0], 600.0);
|
||||
let path = a[1].as_u64().unwrap() as usize;
|
||||
assert_eq!(fonts[0]["g"]["B"][1].as_u64(), Some(path as u64), "the same outline is stored once");
|
||||
assert_eq!(m.json["paths"].as_array().unwrap().len(), m.paths.len(), "the page's paths include the glyphs");
|
||||
assert!(m.json["paths"][path].as_str().unwrap().contains("-700"), "{}", m.json["paths"][path]);
|
||||
// The page's layout: the dynamic field (100 wide, centred, 14 px, letter spacing 0.5).
|
||||
let mut js = Js::new(&m);
|
||||
js.ctx
|
||||
.eval(Source::from_bytes(
|
||||
"function L(text, html, multiline) { var tf = Object.assign({}, FIELD); if (multiline) tf.ln = 'multiline'; \
|
||||
var styles = html === null ? AniCraft.fieldStyles({ text: text, rich: null }, tf) : (function () { var p = AniCraft.htmlText.parse(html, AniCraft.fieldStyles({ text: '', rich: null }, tf).runs[0].s, { al: tf.al }); text = p.text; return { runs: p.runs, paras: p.paras }; })(); \
|
||||
return AniCraft.fieldLayout(tf, text, styles, P.M.fonts, function (st, t) { return Array.from(t).length * st.size * 0.5; }).map(function (l) { return [l.top, l.base, l.h, l.w, l.segs.map(function (s) { return [s.text, s.x, s.w, s.face !== null, s.st.bold, s.st.size]; })]; }); }",
|
||||
))
|
||||
.unwrap();
|
||||
// The field's exported settings, found in the movie's data.
|
||||
fn find_tf(v: &Value) -> Option<&Value> {
|
||||
match v {
|
||||
Value::Object(o) => o.get("tf").filter(|t| t["k"] == "dynamic" && t["t"] == "Score").or_else(|| o.values().find_map(find_tf)),
|
||||
Value::Array(a) => a.iter().find_map(find_tf),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let tf = find_tf(&m.json).expect("the dynamic field").clone();
|
||||
js.ctx.eval(Source::from_bytes(&format!("var FIELD = {tf};"))).unwrap();
|
||||
// "AB A": glyph advances 600 × 14 / 1000 + 0.5 each, the space 250 × 14 / 1000 + 0.5.
|
||||
let lines = js.eval("L('AB A', null, false)");
|
||||
let w = 3.0 * (8.4 + 0.5) + (3.5 + 0.5);
|
||||
let near = |v: &Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-6;
|
||||
assert_eq!(lines.as_array().unwrap().len(), 1);
|
||||
assert!(near(&lines[0][3], w) && near(&lines[0][0], 2.0) && near(&lines[0][1], 2.0 + 0.9 * 14.0) && near(&lines[0][2], 1.2 * 14.0 + 2.0), "{lines}");
|
||||
assert_eq!(lines[0][4].as_array().unwrap().len(), 1, "one stretch: {lines}");
|
||||
assert!(lines[0][4][0][3] == true && near(&lines[0][4][0][1], (100.0 - w) / 2.0), "embedded and centred: {lines}");
|
||||
// A character the face lacks: that word is the browser's (measured by it), the rest embedded.
|
||||
let lines = js.eval("L('AB xy', null, false)");
|
||||
let segs = lines[0][4].as_array().unwrap();
|
||||
assert_eq!(segs.iter().map(|s| (s[0].as_str().unwrap(), s[3].as_bool().unwrap())).collect::<Vec<_>>(), vec![("AB ", true), ("xy", false)], "{lines}");
|
||||
assert!(near(&segs[1][2], 2.0 * 14.0 * 0.5));
|
||||
// Styled text wraps at spaces across runs; each line makes room for its tallest stretch,
|
||||
// and paragraphs align on their own.
|
||||
let lines = js.eval("L('', '<p align=\"right\">AB AB AB AB <font size=\"28\">AB</font> AB</p>last<br>', true)");
|
||||
let rows = lines.as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4, "two wrapped lines, a line and an empty one: {lines}");
|
||||
assert_eq!(rows[0][4].as_array().unwrap().iter().map(|s| s[0].as_str().unwrap()).collect::<String>(), "AB AB AB AB", "{lines}");
|
||||
assert!(rows[1][4].as_array().unwrap().iter().any(|s| s[5] == 28.0) && near(&rows[1][2], 1.2 * 28.0 + 2.0), "{lines}");
|
||||
let right_edge = |row: &Value| row[4].as_array().unwrap().last().map(|s| s[1].as_f64().unwrap() + s[2].as_f64().unwrap()).unwrap();
|
||||
assert!((right_edge(&rows[0]) - 98.0).abs() < 1e-6 && (right_edge(&rows[1]) - 98.0).abs() < 1e-6, "right-aligned: {lines}");
|
||||
assert_eq!(rows[2][4][0][0], "last");
|
||||
assert!(near(&rows[2][0], rows[1][0].as_f64().unwrap() + rows[1][2].as_f64().unwrap()), "lines stack: {lines}");
|
||||
assert_eq!(rows[3][4].as_array().unwrap().len(), 0);
|
||||
// Empty text is one empty line; a very long text is capped.
|
||||
assert_eq!(js.eval("L('', null, false)").as_array().unwrap().len(), 1);
|
||||
assert_eq!(js.eval("L(Array(3000).join('\\n'), null, false)").as_array().unwrap().len(), 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_fields_export_as_named_instances_and_static_text_as_before() {
|
||||
use anicraft_doc::{LineType, TextField, TextKind};
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Font embedding (ADR 0107): whether a face's licence bits allow its glyphs to travel with an
|
||||
//! export, and the glyphs of chosen characters as outlines, for exports that draw text the
|
||||
//! author didn't type (a text field a script fills in the HTML page).
|
||||
//!
|
||||
//! The permission is the OpenType `OS/2` table's `fsType` field, read as the specification
|
||||
//! describes it ("OS/2 — fsType", "Embedding licensing rights"). The three cases and their rule
|
||||
//! are the ones proposed for the shared Craft text library (craft-libs issue #82), so this
|
||||
//! function can be swapped for the shared one without a change in behaviour.
|
||||
|
||||
use crate::{Fonts, Pen};
|
||||
use anicraft_geom::Path;
|
||||
use skrifa::MetadataProvider as _;
|
||||
use skrifa::raw::TableProvider as _;
|
||||
|
||||
/// Most characters embedded from one face.
|
||||
pub const MAX_EMBED_CHARS: usize = 1024;
|
||||
|
||||
/// The em size glyph tables are drawn at (pixels): outlines and advances scale by
|
||||
/// `size / EMBED_EM`.
|
||||
pub const EMBED_EM: f32 = 1000.0;
|
||||
|
||||
/// What a face's licence bits allow an export to do with it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Embedding {
|
||||
/// Its glyphs may be embedded, and only the ones used.
|
||||
Subset,
|
||||
/// It may be embedded, but only whole ("no subsetting").
|
||||
Whole,
|
||||
/// It may not be embedded ("restricted licence"), or only as bitmaps.
|
||||
Forbidden,
|
||||
}
|
||||
|
||||
impl Embedding {
|
||||
/// The permission in an `OS/2` `fsType` value. Restricted (`0x0002`) forbids embedding
|
||||
/// unless Preview & Print (`0x0004`) or Editable (`0x0008`) is also set (older fonts set
|
||||
/// several; the least restrictive applies); bitmap embedding only (`0x0200`) forbids
|
||||
/// outlines; no subsetting (`0x0100`) allows only the whole font. A font without the bits
|
||||
/// (or without an `OS/2` table) is installable: anything goes.
|
||||
pub fn from_fs_type(fs_type: u16) -> Embedding {
|
||||
const RESTRICTED: u16 = 0x0002;
|
||||
const PREVIEW_PRINT: u16 = 0x0004;
|
||||
const EDITABLE: u16 = 0x0008;
|
||||
const NO_SUBSETTING: u16 = 0x0100;
|
||||
const BITMAP_ONLY: u16 = 0x0200;
|
||||
if (fs_type & RESTRICTED != 0 && fs_type & (PREVIEW_PRINT | EDITABLE) == 0) || fs_type & BITMAP_ONLY != 0 {
|
||||
Embedding::Forbidden
|
||||
} else if fs_type & NO_SUBSETTING != 0 {
|
||||
Embedding::Whole
|
||||
} else {
|
||||
Embedding::Subset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One character's glyph in a [`GlyphTable`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TableGlyph {
|
||||
pub ch: char,
|
||||
/// How far the pen moves past it, at [`EMBED_EM`].
|
||||
pub advance: f32,
|
||||
/// Its outline at [`EMBED_EM`], the pen position on the baseline at the origin (y down).
|
||||
pub outline: Path,
|
||||
}
|
||||
|
||||
/// The glyphs of chosen characters in one face, unshaped: one glyph per character, no kerning
|
||||
/// or ligatures.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GlyphTable {
|
||||
/// The family used (the one asked for, or the fallback).
|
||||
pub family: String,
|
||||
pub embedding: Embedding,
|
||||
/// The face's ascent and line height (ascent + descent + line gap) at [`EMBED_EM`].
|
||||
pub ascent: f32,
|
||||
pub line_height: f32,
|
||||
/// The characters the face has, in the order asked for. Empty when `embedding` doesn't
|
||||
/// allow a subset.
|
||||
pub glyphs: Vec<TableGlyph>,
|
||||
/// Characters asked for that the face has no glyph for.
|
||||
pub missing: usize,
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
/// The glyphs of `chars` (at most [`MAX_EMBED_CHARS`], duplicates and control characters
|
||||
/// skipped) in the face `family`, `bold`, `italic` resolves to, if its licence bits allow a
|
||||
/// subset of it to be embedded ([`Embedding::Subset`]); otherwise the table comes back
|
||||
/// without glyphs, saying why. `None`: no usable font.
|
||||
pub fn glyph_table(&self, family: &str, bold: bool, italic: bool, chars: &str) -> Option<GlyphTable> {
|
||||
let family = self.resolve(family)?;
|
||||
let q = fontdb::Query {
|
||||
families: &[fontdb::Family::Name(&family)],
|
||||
weight: if bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL },
|
||||
stretch: fontdb::Stretch::Normal,
|
||||
style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||
};
|
||||
let id = self.db.query(&q)?;
|
||||
self.db
|
||||
.with_face_data(id, |data, index| {
|
||||
let font = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let embedding = Embedding::from_fs_type(font.os2().map_or(0, |o| o.fs_type()));
|
||||
let size = skrifa::instance::Size::new(EMBED_EM);
|
||||
let loc = skrifa::instance::LocationRef::default();
|
||||
let m = skrifa::MetadataProvider::metrics(&font, size, loc);
|
||||
let mut table = GlyphTable { family: family.clone(), embedding, ascent: m.ascent, line_height: (m.ascent - m.descent + m.leading).max(EMBED_EM * 0.5), glyphs: Vec::new(), missing: 0 };
|
||||
if embedding != Embedding::Subset {
|
||||
return Some(table);
|
||||
}
|
||||
let charmap = font.charmap();
|
||||
let outlines = font.outline_glyphs();
|
||||
let advances = font.glyph_metrics(size, loc);
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for ch in chars.chars().filter(|c| !c.is_control()).take(MAX_EMBED_CHARS * 4) {
|
||||
if table.glyphs.len() >= MAX_EMBED_CHARS || !seen.insert(ch) {
|
||||
continue;
|
||||
}
|
||||
let Some(gid) = charmap.map(ch) else {
|
||||
table.missing += 1;
|
||||
continue;
|
||||
};
|
||||
let mut outline = Path::new();
|
||||
if let Some(g) = outlines.get(gid) {
|
||||
let mut pen = Pen { cmds: &mut outline.cmds, x: 0.0, y: 0.0 };
|
||||
let _ = g.draw(skrifa::outline::DrawSettings::unhinted(size, loc), &mut pen);
|
||||
}
|
||||
let advance = advances.advance_width(gid).filter(|a| a.is_finite()).unwrap_or(0.0);
|
||||
table.glyphs.push(TableGlyph { ch, advance, outline });
|
||||
}
|
||||
Some(table)
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fs_type_bits_read_as_the_specification_says() {
|
||||
use Embedding::*;
|
||||
// (fsType, what it allows): installable, each level alone, the modifiers, and old fonts
|
||||
// with several levels set (the least restrictive applies).
|
||||
for (bits, want) in [
|
||||
(0x0000, Subset),
|
||||
(0x0002, Forbidden),
|
||||
(0x0004, Subset),
|
||||
(0x0008, Subset),
|
||||
(0x0006, Subset),
|
||||
(0x000a, Subset),
|
||||
(0x000e, Subset),
|
||||
(0x0100, Whole),
|
||||
(0x0104, Whole),
|
||||
(0x0108, Whole),
|
||||
(0x0102, Forbidden),
|
||||
(0x0200, Forbidden),
|
||||
(0x0204, Forbidden),
|
||||
(0x0300, Forbidden),
|
||||
(0x0001, Subset),
|
||||
(0xfc00, Subset),
|
||||
(0xffff, Forbidden),
|
||||
] {
|
||||
assert_eq!(Embedding::from_fs_type(bits), want, "{bits:#06x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_glyph_table_holds_the_characters_asked_for_once_each() {
|
||||
let fonts = Fonts::get();
|
||||
if fonts.families().is_empty() {
|
||||
eprintln!("no fonts on this computer: glyph table test skipped");
|
||||
return;
|
||||
}
|
||||
assert!(Fonts::from_faces(Vec::new()).glyph_table("", false, false, "a").is_none());
|
||||
let t = fonts.glyph_table("", false, false, "Score: 0123456789 Score\u{7}\n").expect("the default face");
|
||||
assert!(!t.family.is_empty());
|
||||
if t.embedding != Embedding::Subset {
|
||||
assert!(t.glyphs.is_empty(), "a face that can't be subset gives no glyphs");
|
||||
return;
|
||||
}
|
||||
let chars: String = t.glyphs.iter().map(|g| g.ch).collect();
|
||||
assert_eq!(chars.chars().count() + t.missing, "Score: 0123456789".chars().count(), "each character once, controls skipped: {chars:?}");
|
||||
assert!(t.ascent > 500.0 && t.ascent < 1500.0 && t.line_height >= t.ascent, "{} {}", t.ascent, t.line_height);
|
||||
// Advances and outlines are the layout's own, at the table's em.
|
||||
let l = fonts.layout_glyphs("S0", &crate::Style { size: EMBED_EM, ..crate::Style::default() }).unwrap();
|
||||
for (g, ch) in l.glyphs.iter().zip(['S', '0']) {
|
||||
let e = t.glyphs.iter().find(|x| x.ch == ch).expect("in the table");
|
||||
assert_eq!(e.outline, g.outline, "{ch}");
|
||||
}
|
||||
let zero = t.glyphs.iter().find(|x| x.ch == '0').unwrap();
|
||||
let nine = t.glyphs.iter().find(|x| x.ch == '9').unwrap();
|
||||
assert!(zero.advance > 100.0 && (zero.advance - nine.advance).abs() < zero.advance, "{}", zero.advance);
|
||||
let space = t.glyphs.iter().find(|x| x.ch == ' ').unwrap();
|
||||
assert!(space.outline.cmds.is_empty() && space.advance > 0.0, "a space has an advance and no outline");
|
||||
// The cap holds whatever is asked for.
|
||||
let many: String = (0x4e00u32..0x4e00 + 5000).filter_map(char::from_u32).chain("abc".chars()).collect();
|
||||
let big = fonts.glyph_table("", false, false, &many).unwrap();
|
||||
assert!(big.glyphs.len() <= MAX_EMBED_CHARS);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,9 @@
|
||||
use anicraft_geom::{Path, PathCmd, Vec2};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
mod embed;
|
||||
mod rich;
|
||||
pub use embed::{EMBED_EM, Embedding, GlyphTable, MAX_EMBED_CHARS, TableGlyph};
|
||||
pub use rich::{MAX_FACES, MAX_RUNS, ParaStyle, RichText, Run, RunStyle, Shift, sanitize_para, sanitize_run};
|
||||
|
||||
/// Families tried, in order, when none is asked for or the one asked for isn't installed.
|
||||
|
||||
@@ -1607,6 +1607,42 @@ fn text_field_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
}
|
||||
});
|
||||
}
|
||||
// Animate's Embed: the characters whose outlines travel with the HTML export, so text a
|
||||
// script sets is drawn in this font in any browser (ADR 0107). Dynamic text only: what a
|
||||
// viewer types into an input field is drawn by the browser.
|
||||
if kind == TextKind::Dynamic {
|
||||
let mut embed = f.embed.clone();
|
||||
row_prose(ui, tr!("Embed"), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut embed).desired_width(crate::theme::fit(ui, 110.0)).hint_text(tr!("characters"))).named(tr!("Characters to embed"));
|
||||
if r.on_hover_text(tr!("The HTML export carries these characters' outlines in this field's font, so text a script sets looks the same in every browser. Left out, with a note in the export's report, when the font's licence doesn't allow embedding.")).changed() {
|
||||
live(app, tr_noop!("Embed characters"), "text.field", json!({"embed": embed}));
|
||||
}
|
||||
ui.menu_button(tr!("Add"), |ui| {
|
||||
let sets: [(&str, String); 5] = [
|
||||
(tr!("Uppercase (A–Z)"), ('A'..='Z').collect()),
|
||||
(tr!("Lowercase (a–z)"), ('a'..='z').collect()),
|
||||
(tr!("Numerals (0–9)"), ('0'..='9').collect()),
|
||||
(tr!("Punctuation and space"), " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".to_string()),
|
||||
(tr!("The characters in this text"), t.text.clone()),
|
||||
];
|
||||
for (label, chars) in sets {
|
||||
if ui.button(label).clicked() {
|
||||
app.run("text.field", json!({"embed": format!("{}{}", f.embed, chars)}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if !f.embed.is_empty() && ui.button(tr!("None")).on_hover_text(tr!("Embed nothing: the page draws changed text with the browser's fonts")).clicked() {
|
||||
app.run("text.field", json!({"embed": ""}));
|
||||
ui.close();
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr!("Add a set of characters to embed"));
|
||||
});
|
||||
if !f.embed.is_empty() {
|
||||
ui.label(text(Type::Caption, trn!("{n} character embedded in the HTML export", "{n} characters embedded in the HTML export", f.embed.chars().count())).color(T.text_faint));
|
||||
}
|
||||
}
|
||||
if !f.variable.is_empty() {
|
||||
row(ui, tr!("Variable"), |ui| {
|
||||
ui.label(text(Type::Data, f.variable.as_str())).on_hover_text(tr!("Kept from the Animate document: an ActionScript 1.0 or 2.0 variable, which doesn't run here"));
|
||||
|
||||
Reference in new issue
Block a user