feat(fla): decode static and dynamic text records

CPicText records decode into the same text blocks the XFL importer makes of
their twins' DOMStaticText / DOMDynamicText: matrix, bounds, autoExpand,
static vs dynamic single/multiline from the field flags, runs with face,
size, colour and alpha, bold/italic, alignment, letter/line spacing,
indent, superscript, target, render mode and anti-alias thickness. The
512-unit storage pieces of one run merge back as XFL shows them, texts
without characters read their one attribute block, and the header and
trailer strings go through a full MFC CArchive CString reader (with the
FF FE FF FF <u16> long form). Unknown values are approximated and counted;
a record whose structure isn't a text's is refused whole.

Corpus (env-gated): 372/372 records decode and pair with their twins,
372/372 element-level and 667/667 run-level field checks, the one known
1-twip bounds difference tolerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Rob CoenenandClaude Opus 5.5 committed 2026-11-21 15:31:19 +01:00
1 parent 4ea949dc42
commit 2db8e12d65
6 files changed
+1374 -2

No files matched your search

Generated
+2
View File
@@ -342,6 +342,8 @@ version = "0.3.0"
dependencies = [
"anicraft-doc",
"anicraft-geom",
"anicraft-text",
"anicraft-xml",
"craft-xfl",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11)",
"thiserror 2.0.21",
+4
View File
@@ -10,6 +10,8 @@ repository.workspace = true
[dependencies]
anicraft-doc.workspace = true
anicraft-geom.workspace = true
# Lays imported text out with the fonts on this computer, as the XFL importer does (ADR 0012).
anicraft-text.workspace = true
thiserror.workspace = true
[dev-dependencies]
@@ -17,6 +19,8 @@ thiserror.workspace = true
craft-xfl.workspace = true
# The twins' XML trees, for the timeline differential (keyframes, instances).
craft-xml.workspace = true
# The text corpus test reads the twins' XML text fields through the shared XFL schema view.
anicraft-xml.workspace = true
[lints]
workspace = true
+6 -2
View File
@@ -13,8 +13,9 @@
//! stream at 256 MiB, chains (FAT, mini-FAT, DIFAT, directory tree) are cycle-guarded, nothing
//! is written to disk, and hostile or damaged input is refused with a one-sentence error —
//! never a panic. [`archive`] reads an item stream's object graph (layers, keyframes, symbol
//! instances, tweens), [`shape`] the shape records' styles and straight and curved edges, and
//! [`doc`] maps them into the AniCraft model the way the XFL importer maps Animate's (ADR 0096).
//! instances, tweens), [`shape`] the shape records' styles and straight and curved edges,
//! [`text`] the `CPicText` records' static and dynamic text fields, and [`doc`] maps them into
//! the AniCraft model the way the XFL importer maps Animate's (ADR 0096).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -24,9 +25,12 @@ pub mod doc;
pub mod records;
pub mod report;
pub mod shape;
pub mod text;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod text_tests;
pub use doc::import;
pub use report::{ImportError, Report};
+687
View File
@@ -0,0 +1,687 @@
//! `CPicText` records: static and dynamic text fields (ADR 0096), decoded into the same
//! text blocks the XFL importer makes of their twins' `DOMStaticText` and `DOMDynamicText`.
//!
//! Learned differentially from the corpus's legacy files and their Animate twins (every one
//! of the corpus's 372 text records pairs with its twin element, field for field): no Flash
//! or Animate code involved. A record's head is the byte behind its class tag (the class
//! name `CPicText` or a `0x80nn` class reference) and reads, little-endian, offsets from the
//! head:
//!
//! ```text
//! +0 04 · flags (02 selected, 04 locked) · 00 00
//! +4 i32 0x80000000 ×2 (no transformation point) · 00 00
//! +14 0d (the text kind)
//! +15 matrix a b c d : i32 16.16 · tx ty : i32 twips
//! +39 bounds xmin xmax ymin ymax : i32 twips (XFL left, width = xmax − xmin, height)
//! +55 autoExpand u8 · 00
//! +57 field flags u16: & 0003 dynamic, & 0018 multiline, & 4000 no characters
//! +59 static isSelectable u8 · 00 00 00
//! +63 CString (empty in the corpus)
//! runs: { u16 n, attribute block, n UTF-16 units } … u16 0
//! (with no characters: one attribute block without its n, then u16 0)
//! trailer: CString · 8 bytes · CString · CString · 3 bytes
//! ```
//!
//! An attribute block (offsets from its first byte; `F` and `T` are the face's and the
//! target's lengths in units):
//!
//! ```text
//! +0 0c · size u16 twips · face (bare u8 length, UTF-16: the family, as `Arial`)
//! q=+5+2F RGBA · 2 bytes not yet understood · bold · italic · 00 · autoKern
//! · character position (1 superscript) · alignment (0 left, 1 right, 2 center,
//! 3 justify) · lineSpacing i16 twips · indent i16 twips · 4 bytes (margins?)
//! · letterSpacing i16 twips · 5 bytes
//! q+27 target (bare u8 length, UTF-16)
//! r 02 · rendering (0: Animate's "standard") · antiAliasThickness f32 · f32 · 00
//! ```
//!
//! A run stores at most 512 units: a longer run of one style is split into 512-unit pieces
//! with byte-identical attribute blocks, which the decode merges back, as XFL shows them.
//! Strings in the header and trailer are MFC `CArchive` strings ([`Reader::cstring`]).
use crate::report::Report;
use anicraft_doc::{BaselineShift, CharStyle, ColorEffect, Element, ElementId, ElementKind, LineType, ParagraphStyle, Rgba, TextAlign, TextBlock, TextField, TextKind, TextRun};
use anicraft_geom::{Affine, Path, Vec2};
use anicraft_text::{Align, FaceMatch, Fonts, TextError as LayoutError};
use std::collections::HashMap;
use std::sync::Arc;
/// The space between a text field's box and its text, on every side (pixels), as in the XFL
/// importer and Animate's text fields.
pub const GUTTER: f32 = 2.0;
/// The bytes from the head to the matrix.
const HEAD: usize = 15;
/// The head every corpus text record starts with: `04`, any flag byte, then fixed bytes up to
/// the `0d` kind (index 1 is not compared).
const SIGNATURE: [u8; HEAD] = [0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x0D];
/// The first byte of every run's attribute block.
const RUN_KIND: u8 = 0x0C;
/// The longest run a record stores; longer runs of one style are split into pieces this long.
pub const CHUNK: usize = 512;
/// Field flags: a dynamic field (either bit).
const DYNAMIC: u16 = 0x0003;
/// Field flags: a multiline dynamic field (both bits in the corpus).
const MULTILINE: u16 = 0x0018;
/// Field flags: a text without characters, whose one attribute block has no length.
const NO_CHARACTERS: u16 = 0x4000;
/// Every field flag seen in the corpus.
const KNOWN_FLAGS: u16 = DYNAMIC | MULTILINE | NO_CHARACTERS;
/// The most runs one record may store.
pub const MAX_STORED_RUNS: usize = 1 << 16;
/// The most UTF-16 units one record may store.
pub const MAX_UNITS: usize = 1 << 22;
/// The longest CString read, in units.
pub const MAX_STRING: usize = 1 << 20;
/// Why a text record didn't decode: the record is left out whole.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum TextError {
#[error("not a text record")]
NotText,
#[error("the record ends early")]
Truncated,
#[error("a run's attribute block of kind {0:#04x}")]
RunKind(u8),
#[error("a text without characters whose attribute block isn't closed")]
Unclosed,
#[error("a string in the record isn't one")]
String,
#[error("more runs, characters or string units than a text may hold")]
TooLarge,
}
/// How a run's characters line up in their paragraph.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Alignment {
#[default]
Left,
Right,
Center,
Justify,
}
/// One run's style, as stored (sizes and spacings in pixels).
#[derive(Clone, Debug, PartialEq)]
pub struct RunStyle {
pub size: f32,
/// The font family (bold and italic are separate).
pub face: String,
/// RGBA, as stored.
pub rgba: [u8; 4],
pub bold: bool,
pub italic: bool,
pub auto_kern: bool,
pub shift: BaselineShift,
pub align: Alignment,
pub line_spacing: f32,
pub indent: f32,
pub letter_spacing: f32,
/// The link's target window (`_blank`), stored without a link in the corpus.
pub target: String,
/// Animate's "standard" font rendering (the stored byte is 0).
pub standard_rendering: bool,
/// The anti-alias thickness, 0 when unset.
pub anti_alias_thickness: f32,
}
impl RunStyle {
/// The colour, as the XFL importer reads `fillColor` and `alpha`.
pub fn color(&self) -> Rgba {
let [r, g, b, a] = self.rgba;
Rgba::hex(u32::from_be_bytes([0, r, g, b])).with_alpha(a as f32 / 255.0)
}
}
/// A run of characters in one style (the 512-unit pieces merged back).
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
pub text: String,
pub style: RunStyle,
}
/// A decoded text record.
#[derive(Clone, Debug)]
pub struct TextRecord {
/// The head's offset in its stream.
pub head: usize,
pub selected: bool,
pub locked: bool,
pub matrix: Affine,
/// xmin, xmax, ymin, ymax in twips.
pub bounds: [i32; 4],
pub auto_expand: bool,
/// The field flags as stored.
pub field_flags: u16,
/// Static or dynamic (input text is not in the corpus, so never decoded as such).
pub kind: TextKind,
/// A dynamic field's line type (`Single` for static text).
pub lines: LineType,
/// The static-text "selectable" byte (dynamic fields store 0 and are selectable).
pub selectable: bool,
/// The runs; a text without characters has one, empty, carrying its style.
pub runs: Vec<Run>,
/// What was read the nearest way AniCraft can, or left out, as report kinds.
pub approximations: Vec<&'static str>,
/// Where the record ended (the byte after its trailer).
pub end: usize,
}
/// Bounded little-endian reads: every read past the end is [`TextError::Truncated`].
struct Reader<'a> {
data: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8], TextError> {
let end = self.at.checked_add(n).ok_or(TextError::Truncated)?;
let s = self.data.get(self.at..end).ok_or(TextError::Truncated)?;
self.at = end;
Ok(s)
}
fn bytes<const N: usize>(&mut self) -> Result<[u8; N], TextError> {
<[u8; N]>::try_from(self.take(N)?).map_err(|_| TextError::Truncated)
}
fn u8(&mut self) -> Result<u8, TextError> {
Ok(self.bytes::<1>()?[0])
}
fn u16(&mut self) -> Result<u16, TextError> {
Ok(u16::from_le_bytes(self.bytes()?))
}
fn i16(&mut self) -> Result<i16, TextError> {
Ok(i16::from_le_bytes(self.bytes()?))
}
fn u32(&mut self) -> Result<u32, TextError> {
Ok(u32::from_le_bytes(self.bytes()?))
}
fn i32(&mut self) -> Result<i32, TextError> {
Ok(i32::from_le_bytes(self.bytes()?))
}
fn f32(&mut self) -> Result<f32, TextError> {
Ok(f32::from_le_bytes(self.bytes()?))
}
/// `n` UTF-16LE units.
fn units(&mut self, n: usize) -> Result<Vec<u16>, TextError> {
let bytes = self.take(n.checked_mul(2).ok_or(TextError::TooLarge)?)?;
Ok(bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect())
}
/// A matrix: a, b, c, d in 16.16 fixed point, then tx, ty in twips.
fn matrix(&mut self) -> Result<Affine, TextError> {
let mut m = [0f32; 6];
for (i, v) in m.iter_mut().enumerate() {
let raw = self.i32()? as f32;
*v = if i < 4 { raw / 65536.0 } else { raw / 20.0 };
}
Ok(Affine { m })
}
/// A run's string: a bare u8 length, then UTF-16LE units.
fn bare_string(&mut self) -> Result<String, TextError> {
let n = self.u8()? as usize;
Ok(String::from_utf16_lossy(&self.units(n)?))
}
/// An MFC `CArchive` string: a u8 length; `FF` escapes to a u16 length, and `FFFF` to a
/// u32 one. A u16 of `FFFE` marks the string as UTF-16 and its length follows again, so
/// the corpus's strings read `FF FE FF <u8>` and, from 255 units, `FF FE FF FF <u16>`.
/// Unmarked strings are 8-bit (read as Latin-1).
fn cstring(&mut self) -> Result<String, TextError> {
let mut wide = false;
let len = loop {
let b = self.u8()?;
if b < 0xFF {
break b as usize;
}
let w = self.u16()?;
if w == 0xFFFE {
if wide {
return Err(TextError::String);
}
wide = true;
continue;
}
if w < 0xFFFF {
break w as usize;
}
break usize::try_from(self.u32()?).map_err(|_| TextError::TooLarge)?;
};
if len > MAX_STRING {
return Err(TextError::TooLarge);
}
Ok(if wide { String::from_utf16_lossy(&self.units(len)?) } else { self.take(len)?.iter().map(|&b| b as char).collect() })
}
}
/// Reads the MFC `CArchive` string at `at` (see [`decode`]'s header strings): its text and
/// the offset after it. Other records carry such strings too (a component instance's
/// metadata XML), so the object walker can skip them whole.
pub fn cstring(data: &[u8], at: usize) -> Result<(String, usize), TextError> {
let mut r = Reader { data, at };
let s = r.cstring()?;
Ok((s, r.at))
}
fn note(approximations: &mut Vec<&'static str>, what: &'static str) {
if !approximations.contains(&what) {
approximations.push(what);
}
}
fn px(twips: i16) -> f32 {
twips as f32 / 20.0
}
/// One attribute block, and its bytes (pieces of one run have byte-identical blocks).
fn block<'a>(r: &mut Reader<'a>, approximations: &mut Vec<&'static str>) -> Result<(RunStyle, &'a [u8]), TextError> {
let start = r.at;
let kind = r.u8()?;
if kind != RUN_KIND {
return Err(TextError::RunKind(kind));
}
let size = r.u16()? as f32 / 20.0;
let face = r.bare_string()?;
let rgba: [u8; 4] = r.bytes()?;
r.bytes::<2>()?; // vary between files; no XFL attribute follows them
let [bold, italic, zero, auto_kern, position, align] = r.bytes::<6>()?;
let line_spacing = px(r.i16()?);
let indent = px(r.i16()?);
let margins: [u8; 4] = r.bytes()?;
let letter_spacing = px(r.i16()?);
let rest: [u8; 5] = r.bytes()?;
let target = r.bare_string()?;
let [_aa_mode, rendering] = r.bytes::<2>()?; // the first is 02 throughout the corpus
let thickness = r.f32()?;
r.f32()?; // zero throughout the corpus (the anti-alias sharpness?)
let end_zero = r.u8()?;
if margins != [0; 4] {
note(approximations, "text margins (not decoded yet)");
}
if zero != 0 || rest != [0; 5] || end_zero != 0 {
note(approximations, "text attributes not decoded yet");
}
let shift = match position {
0 => BaselineShift::Normal,
1 => BaselineShift::Superscript,
// Not in the corpus; the next value after superscript, as in XFL's list.
2 => BaselineShift::Subscript,
_ => {
note(approximations, "character positions of an unknown kind (drawn normal)");
BaselineShift::Normal
}
};
let align = match align {
0 => Alignment::Left,
1 => Alignment::Right,
2 => Alignment::Center,
3 => Alignment::Justify,
_ => {
note(approximations, "text alignments of an unknown kind (drawn left-aligned)");
Alignment::Left
}
};
let style = RunStyle {
size,
face,
rgba,
bold: bold != 0,
italic: italic != 0,
auto_kern: auto_kern != 0,
shift,
align,
line_spacing,
indent,
letter_spacing,
target,
standard_rendering: rendering == 0,
anti_alias_thickness: if thickness.is_finite() { thickness } else { 0.0 },
};
Ok((style, r.data.get(start..r.at).unwrap_or_default()))
}
/// Decodes the text record whose head (the `04` byte behind its class tag) is at `at`.
pub fn decode(data: &[u8], at: usize) -> Result<TextRecord, TextError> {
let mut r = Reader { data, at };
let head: [u8; HEAD] = r.bytes()?;
if head[0] != 0x04 || head[2..4] != [0, 0] || head[12..14] != [0, 0] || head[14] != 0x0D {
return Err(TextError::NotText);
}
let mut approximations = Vec::new();
let matrix = r.matrix()?;
let bounds = [r.i32()?, r.i32()?, r.i32()?, r.i32()?];
let [auto_expand, _] = r.bytes::<2>()?;
let field_flags = r.u16()?;
let [selectable, _, _, _] = r.bytes::<4>()?;
if field_flags & !KNOWN_FLAGS != 0 {
note(&mut approximations, "text field settings of an unknown kind (left out)");
}
let kind = if field_flags & DYNAMIC != 0 { TextKind::Dynamic } else { TextKind::Static };
let lines = match field_flags & MULTILINE {
0 => LineType::Single,
MULTILINE => LineType::Multiline,
_ => {
note(&mut approximations, "text line types of an unknown kind (drawn multiline)");
LineType::Multiline
}
};
if !r.cstring()?.is_empty() {
note(&mut approximations, "text field strings (not decoded yet)");
}
// The stored runs, the 512-unit pieces of one run merged back as they come.
let mut merged: Vec<(Vec<u16>, RunStyle, &[u8])> = Vec::new();
if field_flags & NO_CHARACTERS != 0 {
let (style, raw) = block(&mut r, &mut approximations)?;
if r.u16()? != 0 {
return Err(TextError::Unclosed);
}
merged.push((Vec::new(), style, raw));
} else {
let (mut stored, mut total) = (0usize, 0usize);
loop {
let n = r.u16()? as usize;
if n == 0 {
break;
}
stored += 1;
total += n;
if stored > MAX_STORED_RUNS || total > MAX_UNITS {
return Err(TextError::TooLarge);
}
let (style, raw) = block(&mut r, &mut approximations)?;
let units = r.units(n)?;
match merged.last_mut() {
Some(last) if !last.0.is_empty() && last.0.len() % CHUNK == 0 && last.2 == raw => last.0.extend(units),
_ => merged.push((units, style, raw)),
}
}
}
// The trailer: three CStrings around fixed bytes, empty or zero in the corpus.
let named = !r.cstring()?.is_empty();
let fixed: [u8; 8] = r.bytes()?;
let named = named | !r.cstring()?.is_empty() | !r.cstring()?.is_empty();
let tail: [u8; 3] = r.bytes()?;
if named {
note(&mut approximations, "text field strings (not decoded yet)");
}
if fixed != [0; 8] || tail != [0; 3] {
note(&mut approximations, "text field settings of an unknown kind (left out)");
}
let runs = merged.into_iter().map(|(units, style, _)| Run { text: String::from_utf16_lossy(&units), style }).collect();
Ok(TextRecord {
head: at,
selected: head[1] & 0x02 != 0,
locked: head[1] & 0x04 != 0,
matrix,
bounds,
auto_expand: auto_expand != 0,
field_flags,
kind,
lines,
selectable: selectable != 0,
runs,
approximations,
end: r.at,
})
}
/// The offsets of every byte run in a stream that has a text record's head (the 15-byte
/// signature, any flag byte): candidates for [`decode`].
pub fn heads(data: &[u8]) -> Vec<usize> {
data.windows(HEAD).enumerate().filter(|(_, w)| w[0] == SIGNATURE[0] && w[2..] == SIGNATURE[2..]).map(|(i, _)| i).collect()
}
/// Every text record in a stream that decodes whole, found by its head and checked by a
/// full decode. For inspection and differential tests: the record-level pass that places
/// them on frames calls [`decode`] at each text object's head.
pub fn find_all(data: &[u8]) -> Vec<TextRecord> {
let mut out: Vec<TextRecord> = Vec::new();
for at in heads(data) {
if out.last().is_some_and(|last| at < last.end) {
continue;
}
if let Ok(record) = decode(data, at) {
out.push(record);
}
}
out
}
/// The faces looked up so far, by name (one lookup per face per import).
pub type Faces = HashMap<String, FaceMatch>;
/// A record's text with its runs (faces resolved to installed families) and one style per
/// paragraph, as the XFL importer reads a field's runs.
struct Styled {
text: String,
runs: Vec<TextRun>,
paragraphs: Vec<ParagraphStyle>,
missing: Vec<String>,
justified: bool,
}
impl TextRecord {
/// Whether the record holds no characters.
pub fn is_empty(&self) -> bool {
self.runs.iter().all(|r| r.text.is_empty())
}
/// XFL's `left`, `top`, `width` and `height`, in pixels.
pub fn left(&self) -> f32 {
self.bounds[0] as f32 / 20.0
}
pub fn top(&self) -> f32 {
self.bounds[2] as f32 / 20.0
}
pub fn width(&self) -> f32 {
(self.bounds[1] as f64 - self.bounds[0] as f64) as f32 / 20.0
}
pub fn height(&self) -> f32 {
(self.bounds[3] as f64 - self.bounds[2] as f64) as f32 / 20.0
}
/// XFL's `fontRenderingMode="standard"` (stored per run; XFL keeps the first run's).
pub fn standard_rendering(&self) -> bool {
self.runs.first().is_some_and(|r| r.style.standard_rendering)
}
/// XFL's `antiAliasThickness`, when set (stored per run; XFL keeps the first run's).
pub fn anti_alias_thickness(&self) -> Option<f32> {
self.runs.first().map(|r| r.style.anti_alias_thickness).filter(|t| *t != 0.0)
}
fn styled(&self, fonts: &Fonts, faces: &mut Faces, report: &mut Report) -> Styled {
let mut text = String::new();
let mut runs: Vec<TextRun> = Vec::new();
let mut para_of_run: Vec<ParagraphStyle> = Vec::new();
let (mut chars, mut missing, mut justified) = (0usize, Vec::new(), false);
let mut cut = self.runs.len() > anicraft_doc::MAX_TEXT_RUNS;
for run in self.runs.iter().take(anicraft_doc::MAX_TEXT_RUNS) {
let s = &run.style;
let align = match s.align {
Alignment::Left => TextAlign::Left,
Alignment::Right => TextAlign::Right,
Alignment::Center => TextAlign::Center,
Alignment::Justify => {
justified = true;
TextAlign::Left
}
};
let name: String = s.face.chars().take(256).collect();
let face = faces.entry(name.clone()).or_insert_with(|| fonts.find_face(&name)).clone();
if face.family.is_none() && !face.wanted.is_empty() && !missing.contains(&face.wanted) {
missing.push(face.wanted.clone());
}
let finite = |v: f32, lo: f32, hi: f32| if v.is_finite() { v.clamp(lo, hi) } else { 0.0 };
let c = CharStyle {
font: face.family.clone().unwrap_or_default(),
size: s.size.clamp(1.0, 2000.0),
bold: s.bold | face.bold,
italic: s.italic | face.italic,
color: s.color(),
letter_spacing: finite(s.letter_spacing, -1000.0, 1000.0),
shift: s.shift,
underline: false,
url: String::new(),
};
let p = ParagraphStyle { align, indent: finite(s.indent, -1000.0, 1000.0), left_margin: 0.0, right_margin: 0.0, line_spacing: finite(s.line_spacing, -1000.0, 1000.0) };
// Animate ends lines with a carriage return; any line break starts a new line here.
let piece = run.text.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n");
let room = anicraft_text::MAX_CHARS.saturating_sub(chars);
let n = piece.chars().count();
cut |= n > room;
let n = n.min(room);
text.extend(piece.chars().take(n));
chars += n;
runs.push(TextRun { chars: n as u32, style: c });
para_of_run.push(p);
if chars >= anicraft_text::MAX_CHARS {
break;
}
}
if cut {
report.skip("text cut to 100,000 characters per field");
}
// Each paragraph takes the paragraph attributes of the run its first character is in.
let mut starts = vec![0usize];
starts.extend(text.chars().enumerate().filter(|(_, c)| *c == '\n').map(|(i, _)| i + 1));
let mut ends: Vec<usize> = Vec::with_capacity(runs.len());
let mut at = 0usize;
for r in &runs {
at += r.chars as usize;
ends.push(at);
}
let paragraphs = starts.into_iter().map(|s| {
let k = ends.partition_point(|e| *e <= s).min(para_of_run.len().saturating_sub(1));
para_of_run.get(k).copied().unwrap_or_default()
}).collect();
Styled { text, runs, paragraphs, missing, justified }
}
/// The record as a text block and where its box's top-left goes in the record's matrix
/// space, laid out with `fonts` exactly as the XFL importer lays out the twin element:
/// static text as wrapped (fixed width) or auto-size text inside the gutter, dynamic text
/// as a field (ADR 0066). `None` for static text with nothing to draw (the corpus's
/// empty statics), or when the computer has no fonts (reported).
pub fn block(&self, fonts: &Fonts, faces: &mut Faces, report: &mut Report) -> Option<(TextBlock, Vec2)> {
let styled = self.styled(fonts, faces, report);
if styled.justified {
report.skip("justified text (drawn left-aligned)");
}
let width = Some(self.width()).filter(|w| *w > 0.0 && w.is_finite()).map(|w| w.min(100_000.0));
if self.kind != TextKind::Static {
return self.field(fonts, report, styled, width);
}
// Trailing empty lines draw nothing.
let keep = styled.text.trim_end().chars().count();
if keep == 0 || styled.runs.is_empty() {
return None;
}
let text: String = styled.text.chars().take(keep).collect();
// A fixed-width field wraps inside its margins; an auto-size one never wraps.
let width = if self.auto_expand { None } else { width };
let mut block = TextBlock { text: text.clone(), width, ..TextBlock::default() };
block.set_styles(styled.runs, styled.paragraphs);
match lay_out(fonts, &mut block, &text, width) {
Ok(l) => {
report.missing_fonts.extend(styled.missing);
block.box_width = l.width;
block.box_height = l.height;
}
Err(LayoutError::NoFonts) => {
report.skip("text fields (no fonts on this computer)");
return None;
}
Err(LayoutError::TooLong) => {
report.skip("text cut to 100,000 characters per field");
return None;
}
}
Some((block, Vec2::new(self.left() + GUTTER, self.top() + GUTTER)))
}
/// A dynamic field: one block with the record's runs, its box from the bounds (or the
/// text's size, for an auto-size field), its text laid out inside the gutter. Empty
/// fields are kept.
fn field(&self, fonts: &Fonts, report: &mut Report, styled: Styled, width: Option<f32>) -> Option<(TextBlock, Vec2)> {
*report.runs.entry("dynamic text fields".into()).or_default() += 1;
let keep = styled.text.trim_end_matches('\n').chars().count();
let text: String = styled.text.chars().take(keep).collect();
// Dynamic fields store 0 in the static "selectable" byte; Animate's default holds.
let field = TextField { lines: self.lines, selectable: true, ..TextField::new(self.kind) };
let mut block = TextBlock { text: text.clone(), ..TextBlock::default() };
block.set_styles(styled.runs, styled.paragraphs);
let wrap = width.and_then(|w| field.wrap_width(w));
// A fixed box that doesn't wrap still aligns its lines in the box.
let lay_width = wrap.or(if self.auto_expand { None } else { width.map(|w| (w - 2.0 * GUTTER).max(1.0)).filter(|_| block.align != TextAlign::Left) });
let shown = field.shown(&text);
let (tw, th) = match lay_out(fonts, &mut block, &shown, lay_width) {
Ok(l) => {
report.missing_fonts.extend(styled.missing);
let to = Affine::translate(GUTTER, GUTTER);
let pieces: Vec<(Rgba, String, Path)> = block.fill_paths().into_iter().map(|(c, u, p)| (c, u.to_string(), p.transformed(&to))).collect();
block.set_outline(pieces);
(l.width, l.height)
}
Err(e) => {
report.skip(if e == LayoutError::NoFonts { "text fields (no fonts on this computer)" } else { "text cut to 100,000 characters per field" });
block.outline = Arc::new(Path::new());
(0.0, block.size * 1.2)
}
};
block.box_width = match (width, self.auto_expand) {
(Some(w), false) => w,
(Some(w), true) => w.max(tw + 2.0 * GUTTER),
(None, _) => tw + 2.0 * GUTTER,
};
let height = self.height();
block.box_height = if height > 0.0 && height.is_finite() { height.min(100_000.0) } else { th + 2.0 * GUTTER };
block.width = wrap;
block.field = Some(field);
Some((block, Vec2::new(self.left(), self.top())))
}
/// The record as a text element with the given id, placed by its matrix (premultiply a
/// parent's transform for texts inside groups). Reports what it approximated, as the
/// record's report kinds, plus anything [`TextRecord::block`] reports.
pub fn to_element(&self, id: ElementId, fonts: &Fonts, faces: &mut Faces, report: &mut Report) -> Option<Element> {
for what in &self.approximations {
report.skip(what);
}
let (block, offset) = self.block(fonts, faces, report)?;
Some(Element { id, name: String::new(), transform: self.matrix.mul(&Affine::translate(offset.x, offset.y)), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) })
}
}
/// Lays a block out from its text, runs, paragraphs and width: the XFL importer's
/// (`anicraft-xfl`'s `text::lay_out`), which sits on the same layer, so it is mirrored here.
fn lay_out(fonts: &Fonts, block: &mut TextBlock, shown: &str, wrap: Option<f32>) -> Result<anicraft_text::Layout, LayoutError> {
let mut paints: Vec<(Rgba, String)> = Vec::new();
let align = |a: TextAlign| match a {
TextAlign::Left => Align::Left,
TextAlign::Center => Align::Center,
TextAlign::Right => Align::Right,
};
let runs: Vec<anicraft_text::Run> = block
.styled_runs()
.into_iter()
.map(|r| {
let key = (r.style.color, r.style.url.clone());
let paint = paints.iter().position(|k| *k == key).unwrap_or_else(|| {
paints.push(key);
paints.len() - 1
}) as u32;
let shift = match r.style.shift {
BaselineShift::Normal => anicraft_text::Shift::Normal,
BaselineShift::Superscript => anicraft_text::Shift::Superscript,
BaselineShift::Subscript => anicraft_text::Shift::Subscript,
};
anicraft_text::Run { chars: r.chars as usize, style: anicraft_text::RunStyle { family: r.style.font, size: r.style.size, bold: r.style.bold, italic: r.style.italic, letter_spacing: r.style.letter_spacing, shift, underline: r.style.underline, paint } }
})
.collect();
let paras: Vec<anicraft_text::ParaStyle> = block.paragraph_styles().into_iter().map(|p| anicraft_text::ParaStyle { align: align(p.align), indent: p.indent, left_margin: p.left_margin, right_margin: p.right_margin, line_spacing: p.line_spacing }).collect();
let l = fonts.layout_rich(&anicraft_text::RichText { text: shown, runs: &runs, paragraphs: &paras, width: wrap }, false)?;
// The runs record the families actually used.
let mut styled = block.styled_runs();
for (r, used) in styled.iter_mut().zip(&l.families) {
r.style.font.clone_from(used);
}
let p = block.paragraph_styles();
block.set_styles(styled, p);
let pieces = l.pieces.iter().map(|(k, p)| paints.get(*k as usize).map_or((block.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p.clone()))).collect();
block.set_outline(pieces);
Ok(l)
}
+375
View File
@@ -0,0 +1,375 @@
//! Text record tests, on records encoded here from the grammar in [`crate::text`] alone (no
//! corpus bytes: the corpus is CC BY-NC-SA).
use crate::text::{self, Alignment, Faces, TextError, CHUNK, GUTTER};
use crate::Report;
use anicraft_doc::{BaselineShift, ElementId, ElementKind, LineType, Rgba, TextAlign, TextKind};
use anicraft_text::Fonts;
/// One run's attributes, as the encoder writes them.
#[derive(Clone)]
struct Style {
size: u16,
face: &'static str,
rgba: [u8; 4],
bold: bool,
italic: bool,
kern: bool,
position: u8,
align: u8,
line: i16,
indent: i16,
letter: i16,
target: &'static str,
render: u8,
thickness: f32,
}
impl Default for Style {
fn default() -> Style {
Style { size: 240, face: "Arial", rgba: [0, 0, 0, 255], bold: false, italic: false, kern: true, position: 0, align: 0, line: 40, indent: 0, letter: 0, target: "", render: 1, thickness: 0.0 }
}
}
fn utf16(s: &str) -> Vec<u8> {
s.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
fn bare(s: &str) -> Vec<u8> {
let mut out = vec![s.encode_utf16().count() as u8];
out.extend(utf16(s));
out
}
/// An MFC Unicode CString: `FF FE FF <u8 len>`, or `FF FE FF FF <u16 len>` from 255 units.
fn cstring(s: &str) -> Vec<u8> {
let n = s.encode_utf16().count();
let mut out = vec![0xFF, 0xFE, 0xFF];
if n < 0xFF {
out.push(n as u8);
} else {
out.push(0xFF);
out.extend((n as u16).to_le_bytes());
}
out.extend(utf16(s));
out
}
fn block(s: &Style) -> Vec<u8> {
let mut out = vec![0x0C];
out.extend(s.size.to_le_bytes());
out.extend(bare(s.face));
out.extend(s.rgba);
out.extend([0x22, 0x00, s.bold as u8, s.italic as u8, 0, s.kern as u8, s.position, s.align]);
out.extend(s.line.to_le_bytes());
out.extend(s.indent.to_le_bytes());
out.extend([0; 4]);
out.extend(s.letter.to_le_bytes());
out.extend([0; 5]);
out.extend(bare(s.target));
out.extend([0x02, s.render]);
out.extend(s.thickness.to_le_bytes());
out.extend(0f32.to_le_bytes());
out.push(0);
out
}
/// A record's head fields.
struct Head {
flags: u8,
matrix: [i32; 6],
bounds: [i32; 4],
auto: bool,
field: u16,
selectable: bool,
name: String,
}
impl Default for Head {
fn default() -> Head {
Head { flags: 0, matrix: [65536, 0, 0, 65536, 2000, 400], bounds: [-100, 4000, 0, 600], auto: false, field: 0, selectable: false, name: String::new() }
}
}
/// A whole record: head, runs (units and style, stored as given), trailer.
fn record(h: &Head, runs: &[(Vec<u16>, Style)]) -> Vec<u8> {
let mut out = vec![0x04, h.flags, 0, 0];
out.extend(0x8000_0000u32.to_le_bytes());
out.extend(0x8000_0000u32.to_le_bytes());
out.extend([0, 0, 0x0D]);
for v in h.matrix.iter().chain(&h.bounds) {
out.extend(v.to_le_bytes());
}
out.extend([h.auto as u8, 0]);
out.extend(h.field.to_le_bytes());
out.extend([h.selectable as u8, 0, 0, 0]);
out.extend(cstring(&h.name));
if h.field & 0x4000 != 0 {
out.extend(block(&runs[0].1));
} else {
for (units, style) in runs {
out.extend((units.len() as u16).to_le_bytes());
out.extend(block(style));
out.extend(units.iter().flat_map(|u| u.to_le_bytes()));
}
}
out.extend([0, 0]);
out.extend(cstring(""));
out.extend([0; 8]);
out.extend(cstring(""));
out.extend(cstring(""));
out.extend([0; 3]);
out
}
fn units(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
fn fonts() -> Option<&'static Fonts> {
let f = Fonts::get();
f.resolve("")?;
Some(f)
}
#[test]
fn a_static_text_decodes_its_geometry_and_run() {
let style = Style { size: 280, rgba: [0xBB, 0xBB, 0xBB, 0xFF], align: 2, line: 20, thickness: 58.0, ..Style::default() };
let h = Head { flags: 0x04, auto: true, bounds: [-109, 8801, 0, 976], ..Head::default() };
let bytes = record(&h, &[(units("First line\rsecond line"), style)]);
let t = text::decode(&bytes, 0).unwrap();
assert_eq!(t.end, bytes.len());
assert!(t.locked && !t.selected && t.auto_expand);
assert_eq!((t.kind, t.lines, t.field_flags), (TextKind::Static, LineType::Single, 0));
assert_eq!(t.matrix.m, [1.0, 0.0, 0.0, 1.0, 100.0, 20.0]);
assert_eq!((t.left(), t.width(), t.top(), t.height()), (-5.45, 445.5, 0.0, 48.8));
assert_eq!(t.runs.len(), 1);
let r = &t.runs[0];
assert_eq!(r.text, "First line\rsecond line");
assert_eq!((r.style.size, r.style.face.as_str(), r.style.align, r.style.line_spacing), (14.0, "Arial", Alignment::Center, 1.0));
assert_eq!(r.style.color(), Rgba::hex(0xBBBBBB));
assert!(r.style.auto_kern && !r.style.bold && !r.style.italic);
assert_eq!((t.anti_alias_thickness(), t.standard_rendering()), (Some(58.0), false));
assert!(t.approximations.is_empty(), "{:?}", t.approximations);
}
#[test]
fn a_dynamic_multiline_field_is_told_from_its_flags() {
for (field, kind, lines) in [(0x0003, TextKind::Dynamic, LineType::Single), (0x001B, TextKind::Dynamic, LineType::Multiline), (0x0000, TextKind::Static, LineType::Single)] {
let h = Head { field, ..Head::default() };
let t = text::decode(&record(&h, &[(units("score"), Style { line: 0, ..Style::default() })]), 0).unwrap();
assert_eq!((t.kind, t.lines), (kind, lines), "{field:#06x}");
assert!(t.approximations.is_empty());
}
}
#[test]
fn a_rotated_and_scaled_matrix_keeps_its_b_and_c_slots() {
let h = Head { matrix: [0, -81920, 81920, 0, -300, 1234], flags: 0x02, ..Head::default() };
let t = text::decode(&record(&h, &[(units("Action safe"), Style::default())]), 0).unwrap();
assert_eq!(t.matrix.m, [0.0, -1.25, 1.25, 0.0, -15.0, 61.7]);
assert!(t.selected && !t.locked);
}
#[test]
fn runs_keep_their_own_styles() {
let a = Style { bold: true, rgba: [255, 0, 0, 0x33], size: 640, ..Style::default() };
let b = Style { italic: true, indent: 520, line: -200, letter: -10, kern: false, ..Style::default() };
let c = Style { position: 1, align: 1, target: "_blank", render: 0, ..Style::default() };
let t = text::decode(&record(&Head::default(), &[(units("Bold "), a), (units("italic "), b), (units("2"), c)]), 0).unwrap();
let styles: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.bold, r.style.italic)).collect();
assert_eq!(styles, [("Bold ", true, false), ("italic ", false, true), ("2", false, false)]);
assert_eq!((t.runs[0].style.size, t.runs[0].style.color()), (32.0, Rgba::hex(0xFF0000).with_alpha(0x33 as f32 / 255.0)));
let s = &t.runs[1].style;
assert_eq!((s.indent, s.line_spacing, s.letter_spacing, s.auto_kern), (26.0, -10.0, -0.5, false));
let s = &t.runs[2].style;
assert_eq!((s.shift, s.align, s.target.as_str(), s.standard_rendering), (BaselineShift::Superscript, Alignment::Right, "_blank", true));
assert!(!t.standard_rendering(), "the record's rendering is its first run's");
}
#[test]
fn the_512_unit_pieces_of_one_run_merge_back() {
// A 530-unit run of one style, stored as 512 + 18, with a surrogate pair cut by the split.
let mut long: Vec<u16> = "©".repeat(511).encode_utf16().collect();
long.extend("😀".encode_utf16()); // units 511 and 512: the split falls inside
long.extend("tail of the notice".encode_utf16().take(17));
assert_eq!(long.len(), 530);
let (first, second) = long.split_at(CHUNK);
let style = Style::default();
let other = Style { bold: true, ..Style::default() };
let runs = [(first.to_vec(), style.clone()), (second.to_vec(), style.clone()), (units(" next"), other.clone()), (units("x"), other)];
let t = text::decode(&record(&Head::default(), &runs), 0).unwrap();
let texts: Vec<&str> = t.runs.iter().map(|r| r.text.as_str()).collect();
assert_eq!(texts.len(), 3, "pieces merge; a different style starts a run, and short runs stay apart");
assert_eq!(texts[0], String::from_utf16_lossy(&long));
assert!(texts[0].contains('😀'), "the pair survives the split");
assert_eq!(texts[1..], [" next", "x"]);
}
#[test]
fn a_short_run_is_not_merged_with_the_next_of_its_style() {
let s = Style::default();
let t = text::decode(&record(&Head::default(), &[(units("ab"), s.clone()), (units("cd"), s.clone())]), 0).unwrap();
assert_eq!(t.runs.len(), 2);
// A full 512-unit piece followed by a differently-styled one stays apart, too.
let full = vec![u16::from(b'a'); CHUNK];
let t = text::decode(&record(&Head::default(), &[(full, s), (units("b"), Style { size: 300, ..Style::default() })]), 0).unwrap();
assert_eq!(t.runs.len(), 2);
}
#[test]
fn an_empty_text_reads_its_one_attribute_block_without_a_length() {
let h = Head { field: 0x4000, ..Head::default() };
let style = Style { size: 640, bold: true, kern: false, ..Style::default() };
let bytes = record(&h, &[(Vec::new(), style)]);
let t = text::decode(&bytes, 0).unwrap();
assert_eq!(t.end, bytes.len());
assert!(t.is_empty());
assert_eq!(t.runs.len(), 1);
assert_eq!((t.runs[0].style.size, t.runs[0].style.bold, t.runs[0].style.auto_kern), (32.0, true, false));
assert_eq!(t.kind, TextKind::Static);
}
#[test]
fn a_long_form_cstring_reads_whole() {
let name = "n".repeat(300);
let h = Head { name: name.clone(), ..Head::default() };
let bytes = record(&h, &[(units("hi"), Style::default())]);
assert_eq!(&bytes[63..69], &[0xFF, 0xFE, 0xFF, 0xFF, 0x2C, 0x01]);
let t = text::decode(&bytes, 0).unwrap();
assert_eq!((t.end, t.runs[0].text.as_str()), (bytes.len(), "hi"));
assert_eq!(t.approximations, ["text field strings (not decoded yet)"]);
assert_eq!(text::cstring(&bytes, 63).unwrap(), (name, 69 + 600));
// The short form, an 8-bit string, and its u16 escape.
assert_eq!(text::cstring(&cstring("Layer"), 0).unwrap(), ("Layer".to_string(), 14));
assert_eq!(text::cstring(&[3, b'a', b'b', b'c'], 0).unwrap(), ("abc".to_string(), 4));
let mut ansi = vec![0xFF, 0x00, 0x01];
ansi.extend([b'z'; 256]);
assert_eq!(text::cstring(&ansi, 0).unwrap(), ("z".repeat(256), 259));
// A u32 length (MFC's next escape) and a doubled Unicode marker.
let mut wide = vec![0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 2, 0, 0, 0];
wide.extend(utf16("ok"));
assert_eq!(text::cstring(&wide, 0).unwrap(), ("ok".to_string(), 14));
assert_eq!(text::cstring(&[0xFF, 0xFE, 0xFF, 0xFF, 0xFE, 0xFF, 0], 0), Err(TextError::String));
assert_eq!(text::cstring(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F], 0), Err(TextError::TooLarge));
}
#[test]
fn unknown_values_degrade_and_are_counted() {
let h = Head { field: 0x0103 | 0x0008, ..Head::default() };
let style = Style { position: 7, align: 9, ..Style::default() };
let t = text::decode(&record(&h, &[(units("odd"), style)]), 0).unwrap();
assert_eq!((t.kind, t.lines), (TextKind::Dynamic, LineType::Multiline));
assert_eq!((t.runs[0].style.shift, t.runs[0].style.align), (BaselineShift::Normal, Alignment::Left));
for what in ["text field settings of an unknown kind (left out)", "text line types of an unknown kind (drawn multiline)", "character positions of an unknown kind (drawn normal)", "text alignments of an unknown kind (drawn left-aligned)"] {
assert!(t.approximations.contains(&what), "{what}: {:?}", t.approximations);
}
// A record whose structure isn't a text's is refused whole.
let mut bad = record(&Head::default(), &[(units("x"), Style::default())]);
let run_kind = 63 + 4 + 2;
bad[run_kind] = 0x0B;
assert_eq!(text::decode(&bad, 0).unwrap_err(), TextError::RunKind(0x0B));
assert_eq!(text::decode(&bad, 1).unwrap_err(), TextError::NotText);
let mut unclosed = record(&Head { field: 0x4000, ..Head::default() }, &[(Vec::new(), Style::default())]);
let close = 63 + 4 + block(&Style::default()).len();
unclosed[close] = 1;
assert_eq!(text::decode(&unclosed, 0).unwrap_err(), TextError::Unclosed);
}
#[test]
fn find_all_walks_records_behind_class_tags() {
let one = record(&Head::default(), &[(units("one"), Style::default())]);
let two = record(&Head { field: 0x4000, ..Head::default() }, &[(Vec::new(), Style::default())]);
let mut stream = vec![0x00, 0x01, 0x02];
stream.extend([0xFF, 0xFF, 0x01, 0x00, 0x08, 0x00]);
stream.extend(b"CPicText");
let first = stream.len();
stream.extend(&one);
stream.extend([0x07, 0x80]);
let second = stream.len();
stream.extend(&two);
stream.extend([0x00, 0x00]);
assert_eq!(text::heads(&stream), [first, second]);
let found = text::find_all(&stream);
assert_eq!(found.iter().map(|t| t.head).collect::<Vec<_>>(), [first, second]);
assert!(found[1].is_empty());
}
#[test]
fn truncated_or_damaged_records_never_panic() {
let chunked = vec![u16::from(b'c'); CHUNK + 3];
let samples = [
record(&Head::default(), &[(units("Hello\rworld"), Style::default()), (units("!"), Style { bold: true, ..Style::default() })]),
record(&Head { field: 0x4000, ..Head::default() }, &[(Vec::new(), Style::default())]),
record(&Head { field: 0x001B, name: "x".repeat(260), ..Head::default() }, &[(chunked[..CHUNK].to_vec(), Style::default()), (chunked[CHUNK..].to_vec(), Style::default())]),
];
for bytes in &samples {
assert!(text::decode(bytes, 0).is_ok());
for cut in 0..bytes.len() {
assert!(text::decode(&bytes[..cut], 0).is_err(), "a record cut at {cut} is refused");
let _ = text::find_all(&bytes[..cut]);
}
for at in 0..bytes.len() {
for v in [0x00, 0x7F, 0xFF] {
let mut b = bytes.clone();
b[at] = v;
let _ = text::decode(&b, 0);
let _ = text::find_all(&b);
}
}
assert!(text::decode(bytes, usize::MAX).is_err());
}
}
#[test]
fn a_static_text_becomes_the_xfl_importers_block() {
let Some(fonts) = fonts() else { return };
let h = Head { matrix: [131072, 0, 0, 131072, 2000, 1000], bounds: [-100, 4000, 0, 600], ..Head::default() };
let a = Style { size: 400, rgba: [255, 0, 0, 255], align: 2, letter: 30, line: 80, ..Style::default() };
let t = text::decode(&record(&h, &[(units("Hello\rWorld"), a)]), 0).unwrap();
let (mut faces, mut report) = (Faces::new(), Report::default());
let el = t.to_element(ElementId(7), fonts, &mut faces, &mut report).unwrap();
let ElementKind::Text(b) = &el.kind else { panic!("a text element") };
assert_eq!(el.id, ElementId(7));
assert_eq!(b.text, "Hello\nWorld", "carriage returns are line breaks");
assert_eq!((b.size, b.color, b.align, b.letter_spacing, b.line_spacing), (20.0, Rgba::hex(0xFF0000), TextAlign::Center, 1.5, 4.0));
assert_eq!(b.width, Some(205.0), "a fixed-width static text wraps at its bounds");
assert!(b.field.is_none() && !b.outline.cmds.is_empty());
// The matrix places the bounds' corner; the text sits inside the gutter.
assert_eq!(el.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0 + 2.0 * (-5.0 + GUTTER), 50.0 + 2.0 * GUTTER]);
assert!(report.skipped.is_empty(), "{report:?}");
}
#[test]
fn a_dynamic_field_becomes_a_field_block_and_empty_statics_draw_nothing() {
let Some(fonts) = fonts() else { return };
let (mut faces, mut report) = (Faces::new(), Report::default());
let h = Head { field: 0x001B, bounds: [0, 3000, 0, 800], ..Head::default() };
let t = text::decode(&record(&h, &[(units("Panel notes"), Style { line: 0, ..Style::default() })]), 0).unwrap();
let el = t.to_element(ElementId(1), fonts, &mut faces, &mut report).unwrap();
let ElementKind::Text(b) = &el.kind else { panic!("a text element") };
let field = b.field.as_ref().expect("a dynamic field");
assert_eq!((field.kind, field.lines, field.selectable), (TextKind::Dynamic, LineType::Multiline, true));
assert_eq!((b.box_width, b.box_height, b.text.as_str()), (150.0, 40.0, "Panel notes"));
assert_eq!(el.transform.m[4..], [100.0, 20.0]);
assert_eq!(report.runs.get("dynamic text fields"), Some(&1));
// An empty dynamic field is kept; an empty static text draws nothing.
let empty = |field| text::decode(&record(&Head { field, ..Head::default() }, &[(Vec::new(), Style::default())]), 0).unwrap();
assert!(empty(0x4003).to_element(ElementId(2), fonts, &mut faces, &mut report).is_some());
assert!(empty(0x4000).to_element(ElementId(3), fonts, &mut faces, &mut report).is_none());
// Justified text is drawn left-aligned and reported, as the XFL importer does.
let t = text::decode(&record(&Head::default(), &[(units("wide"), Style { align: 3, ..Style::default() })]), 0).unwrap();
assert!(t.to_element(ElementId(4), fonts, &mut faces, &mut report).is_some());
assert_eq!(report.skipped.get("justified text (drawn left-aligned)"), Some(&1));
}
#[test]
fn without_fonts_static_text_is_reported_and_fields_stay() {
let none = Fonts::from_faces(Vec::<Vec<u8>>::new());
let (mut faces, mut report) = (Faces::new(), Report::default());
let t = text::decode(&record(&Head::default(), &[(units("Hi"), Style::default())]), 0).unwrap();
assert!(t.to_element(ElementId(1), &none, &mut faces, &mut report).is_none());
assert_eq!(report.skipped.get("text fields (no fonts on this computer)"), Some(&1));
let t = text::decode(&record(&Head { field: 3, ..Head::default() }, &[(units("Hi"), Style::default())]), 0).unwrap();
assert!(t.to_element(ElementId(2), &none, &mut faces, &mut report).is_some());
}
+300
View File
@@ -0,0 +1,300 @@
//! Differential text test against the local (uncommitted) ground-truth corpus, run only when
//! it is available: `ANICRAFT_FLA_CORPUS=/path/to/corpus cargo test -p anicraft-fla --test
//! corpus_text -- --nocapture`.
//!
//! Every `CPicText` record in the legacy files is decoded and paired with its Animate twin's
//! `DOMStaticText` / `DOMDynamicText` (by characters and position), then compared field by
//! field, element and merged run alike. The corpus files are EDAP Tools sample rigs (CC
//! BY-NC-SA), so they stay out of the MIT-licensed repo: these tests observe behaviour, they
//! don't commit fixtures.
use anicraft_fla::text::{self, Alignment, TextRecord};
use anicraft_xml::Element as X;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
fn corpus() -> Option<PathBuf> {
std::env::var_os("ANICRAFT_FLA_CORPUS").map(PathBuf::from)
}
/// The corpus's legacy files and their Animate twins (a zip package, or the extracted folder
/// where the twin's zip directory is damaged).
const TWINS: &[(&str, &str)] = &[
("giskard-legacy.fla", "giskard-animate.fla"),
("kinefox-legacy.fla", "kinefox-animate.fla"),
("mademoiselle-legacy.fla", "mademoiselle-animate"),
("magnebot-legacy.fla", "magnebot-animate.fla"),
("movietemplate-legacy.fla", "movietemplate-animate.fla"),
("rabbit-legacy.fla", "rabbit-animate.fla"),
("robokit-legacy/EDAPT_SMR_FreeStyle_RoboKit_v1b.fla", "robokit-animate/EDAPT_SMR_FreeStyle_RoboKit_v1b_CC.fla"),
("storyboard-legacy/EDAPT_Storyboard_Template.fla", "storyboard-animate/EDAPT_Storyboard_Template_CC.fla"),
("storyboard-legacy/EDAPT_Storyboard_Template_Sample_Animatic.fla", "storyboard-animate/EDAPT_Storyboard_Template_Sample_Animatic_CC.fla"),
];
/// The one known difference: Animate recomputed this text's bounds on resave, one twip
/// narrower on each side (the legacy value is authoritative).
const TOLERATED: &[(&str, &str, usize, &str)] = &[("mademoiselle-legacy.fla", "P 2 1609991139", 3619, "left"), ("mademoiselle-legacy.fla", "P 2 1609991139", 3619, "width")];
/// A twin text element: where it was, its kind, attributes, matrix and runs.
struct Twin {
member: String,
kind: String,
attrs: BTreeMap<String, String>,
matrix: BTreeMap<String, String>,
runs: Vec<(String, BTreeMap<String, String>)>,
}
impl Twin {
fn text(&self) -> String {
self.runs.iter().map(|(c, _)| c.as_str()).collect()
}
fn m(&self, k: &str, default: f64) -> f64 {
num(self.matrix.get(k), default)
}
}
fn num(v: Option<&String>, default: f64) -> f64 {
v.and_then(|s| s.trim().parse().ok()).unwrap_or(default)
}
fn local(name: &str) -> &str {
name.rsplit(':').next().unwrap_or(name)
}
fn child<'a>(el: &'a X, name: &str) -> Option<&'a X> {
el.children.iter().find(|c| local(&c.name) == name)
}
fn attrs(el: &X) -> BTreeMap<String, String> {
el.attrs.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
}
/// Every text element in a twin XML, in document order (frames and group members alike).
fn walk(el: &X, member: &str, out: &mut Vec<Twin>) {
let name = local(&el.name);
if matches!(name, "DOMStaticText" | "DOMDynamicText" | "DOMInputText") {
let matrix = child(el, "matrix").and_then(|m| child(m, "Matrix")).map(attrs).unwrap_or_default();
let runs = child(el, "textRuns")
.map(|r| {
r.children.iter().filter(|c| local(&c.name) == "DOMTextRun").map(|run| {
let chars = child(run, "characters").map(|c| c.text.clone()).unwrap_or_default();
let a = child(run, "textAttrs").and_then(|t| child(t, "DOMTextAttrs")).map(attrs).unwrap_or_default();
(chars, a)
}).collect()
})
.unwrap_or_default();
out.push(Twin { member: member.to_string(), kind: name.to_string(), attrs: attrs(el), matrix, runs });
return;
}
for c in &el.children {
walk(c, member, out);
}
}
/// The twin's documents: `DOMDocument.xml` and every library item.
fn twin_texts(path: &Path) -> Vec<Twin> {
let mut docs: Vec<(String, Vec<u8>)> = Vec::new();
if path.is_dir() {
docs.push(("DOMDocument.xml".into(), std::fs::read(path.join("DOMDocument.xml")).expect("twin document reads")));
let mut dirs = vec![path.join("LIBRARY")];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir).expect("twin library lists") {
let p = entry.expect("entry").path();
if p.is_dir() {
dirs.push(p);
} else if p.extension().is_some_and(|e| e == "xml") {
let name = p.strip_prefix(path).expect("inside the twin").to_string_lossy().replace('\\', "/");
docs.push((name, std::fs::read(&p).expect("twin item reads")));
}
}
}
} else {
let bytes = std::fs::read(path).expect("twin reads");
let archive = craft_xfl::Archive::open(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let names: Vec<String> = archive.names().filter(|n| *n == "DOMDocument.xml" || (n.starts_with("LIBRARY/") && n.ends_with(".xml"))).map(str::to_string).collect();
for name in names {
if let Ok(Some(xml)) = archive.read(&name) {
docs.push((name, xml));
}
}
}
let mut out = Vec::new();
for (name, xml) in docs {
let root = anicraft_xml::parse(&xml).unwrap_or_else(|e| panic!("{}: {name}: {e:?}", path.display()));
walk(&root, &name, &mut out);
}
out
}
/// The stem of a twin member (`LIBRARY/Copyright/CC_note.xml` → `CC_note`).
fn stem(member: &str) -> &str {
let file = member.rsplit('/').next().unwrap_or(member);
file.strip_suffix(".xml").unwrap_or(file)
}
/// Field-by-field comparison of a record and its twin: (check name, equal) pairs.
fn compare(t: &TextRecord, w: &Twin) -> Vec<(&'static str, bool)> {
let near = |a: f64, b: f64| (a - b).abs() < 1e-4;
let a = |k: &str| w.attrs.get(k).map(String::as_str);
let m = t.matrix.m;
let mut out = vec![
("matrix a b c d", [("a", 1.0), ("b", 0.0), ("c", 0.0), ("d", 1.0)].iter().zip(&m[..4]).all(|((k, d), v)| near(*v as f64, w.m(k, *d)))),
("matrix tx ty", near(m[4] as f64, w.m("tx", 0.0)) && near(m[5] as f64, w.m("ty", 0.0))),
("left", near(t.left() as f64, num(w.attrs.get("left"), 0.0))),
("width", near(t.width() as f64, num(w.attrs.get("width"), 0.0))),
("height", near(t.height() as f64, num(w.attrs.get("height"), 0.0))),
("autoExpand", t.auto_expand == (a("autoExpand") == Some("true"))),
("selected", t.selected == (a("selected") == Some("true"))),
("locked", t.locked == (a("locked") == Some("true"))),
("static or dynamic", (t.kind == anicraft_doc::TextKind::Dynamic) == (w.kind == "DOMDynamicText") && w.kind != "DOMInputText"),
("lineType", (t.lines == anicraft_doc::LineType::Multiline) == (a("lineType") == Some("multiline"))),
("static isSelectable", t.kind != anicraft_doc::TextKind::Static || t.selectable == (a("isSelectable") != Some("false"))),
("dynamic isSelectable", t.kind == anicraft_doc::TextKind::Static || a("isSelectable") != Some("false")),
("antiAliasThickness", match (t.anti_alias_thickness(), a("antiAliasThickness")) {
(None, None) => true,
(Some(v), Some(x)) => x.parse::<f32>().is_ok_and(|x| x == v),
_ => false,
}),
("fontRenderingMode", t.standard_rendering() == (a("fontRenderingMode") == Some("standard"))),
("run count", t.runs.len() == w.runs.len()),
];
if t.runs.len() != w.runs.len() {
return out;
}
for (r, (chars, ra)) in t.runs.iter().zip(&w.runs) {
let s = &r.style;
let g = |k: &str| ra.get(k).map(String::as_str);
let face = g("face").unwrap_or("");
let align = match s.align {
Alignment::Left => None,
Alignment::Right => Some("right"),
Alignment::Center => Some("center"),
Alignment::Justify => Some("justify"),
};
let fill = format!("#{:02X}{:02X}{:02X}", s.rgba[0], s.rgba[1], s.rgba[2]);
out.extend([
("run characters", &r.text == chars),
("run size", near(s.size as f64, num(ra.get("size"), 12.0))),
("run face", !s.face.is_empty() && face.starts_with(s.face.as_str())),
("run bold", s.bold == face.contains("Bold")),
("run italic", s.italic == face.contains("Italic")),
("run fillColor", fill == g("fillColor").unwrap_or("#000000").to_ascii_uppercase()),
("run alpha", (s.rgba[3] as f64 / 255.0 - num(ra.get("alpha"), 1.0)).abs() < 0.003),
("run autoKern", s.auto_kern == (g("autoKern") != Some("false"))),
("run characterPosition", (s.shift == anicraft_doc::BaselineShift::Superscript) == (g("characterPosition") == Some("superscript"))),
("run alignment", align == g("alignment")),
// Animate leaves lineSpacing out at its default, 2 px (stored as 40 twips).
("run lineSpacing", near(s.line_spacing as f64, num(ra.get("lineSpacing"), 2.0))),
("run indent", near(s.indent as f64, num(ra.get("indent"), 0.0))),
("run letterSpacing", near(s.letter_spacing as f64, num(ra.get("letterSpacing"), 0.0))),
("run target", s.target == g("target").unwrap_or("")),
]);
}
out
}
#[test]
fn every_corpus_text_record_decodes_like_its_twin() {
let Some(dir) = corpus() else { return };
let fonts = anicraft_text::Fonts::get();
let has_fonts = fonts.resolve("").is_some();
let (mut heads, mut decoded, mut paired, mut exact, mut elements) = (0usize, 0usize, 0usize, 0usize, 0usize);
let mut checks: BTreeMap<&'static str, (usize, usize)> = BTreeMap::new();
let mut problems: Vec<String> = Vec::new();
let mut approximated: BTreeMap<&'static str, usize> = BTreeMap::new();
for (legacy, twin) in TWINS {
let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin));
if !legacy_path.exists() || !twin_path.exists() {
continue;
}
let data = std::fs::read(&legacy_path).expect("legacy reads");
let file = anicraft_fla::cfb::Compound::new(&data).expect("opens");
let contents = file.stream("Contents").expect("Contents reads");
let labels: BTreeMap<String, String> = anicraft_fla::doc::library(&contents, &mut anicraft_fla::Report::default()).into_iter().collect();
let twins = twin_texts(&twin_path);
let mut used = vec![false; twins.len()];
let (mut faces, mut report) = (text::Faces::new(), anicraft_fla::Report::default());
for entry in file.entries() {
if entry.kind != anicraft_fla::cfb::Kind::Stream {
continue;
}
let bytes = file.stream(&entry.path).expect("stream reads");
let found = text::find_all(&bytes);
heads += text::heads(&bytes).len();
decoded += found.len();
let label = labels.get(&entry.path).map(String::as_str);
for t in &found {
for what in &t.approximations {
*approximated.entry(what).or_default() += 1;
}
let chars: String = t.runs.iter().map(|r| r.text.as_str()).collect();
let (tx, ty) = (t.matrix.m[4] as f64, t.matrix.m[5] as f64);
let candidates: Vec<usize> = (0..twins.len())
.filter(|&i| !used[i] && twins[i].text() == chars && (twins[i].m("tx", 0.0) - tx).abs() < 0.01 && (twins[i].m("ty", 0.0) - ty).abs() < 0.01)
.collect();
// The twin in the same library item (or the document, for a page) first; among
// those, one that matches field for field.
let home = |i: &usize| match label {
Some(l) => stem(&twins[*i].member) == l.rsplit('/').next().unwrap_or(l),
None => twins[*i].member == "DOMDocument.xml",
};
let mut order: Vec<usize> = candidates.iter().copied().filter(home).collect();
order.extend(candidates.iter().copied().filter(|i| !home(i)));
let Some(&first) = order.first() else {
problems.push(format!("{legacy} {} @{}: no twin for {:?}", entry.path, t.head, chars.chars().take(30).collect::<String>()));
continue;
};
let pick = order.iter().copied().find(|&i| compare(t, &twins[i]).iter().all(|(_, ok)| *ok)).unwrap_or(first);
used[pick] = true;
paired += 1;
let mut all = true;
for (name, ok) in compare(t, &twins[pick]) {
let tolerated = TOLERATED.iter().any(|(f, s, h, c)| f == legacy && *s == entry.path && *h == t.head && *c == name);
let e = checks.entry(name).or_default();
e.1 += 1;
if ok || tolerated {
e.0 += 1;
}
if !ok {
all = false;
if !tolerated {
problems.push(format!("{legacy} {} @{}: {name} differs from {} ({})", entry.path, t.head, twins[pick].member, twins[pick].kind));
}
}
}
exact += all as usize;
// The record as a document element, laid out as the XFL importer lays out
// the twin: its text, kind and line type.
if has_fonts {
let element = t.to_element(anicraft_doc::ElementId(1), fonts, &mut faces, &mut report);
let shown = chars.replace(['\r'], "\n");
match (&element, t.kind) {
(Some(e), kind) => {
elements += 1;
let anicraft_doc::ElementKind::Text(b) = &e.kind else { panic!("a text element") };
let want = if kind == anicraft_doc::TextKind::Static { shown.trim_end() } else { shown.trim_end_matches('\n') };
if b.text != want || b.field.as_ref().map(|f| (f.kind, f.lines)) != (kind != anicraft_doc::TextKind::Static).then_some((kind, t.lines)) {
problems.push(format!("{legacy} {} @{}: element text or field differs", entry.path, t.head));
}
}
(None, anicraft_doc::TextKind::Static) if shown.trim_end().is_empty() => {}
(None, _) => problems.push(format!("{legacy} {} @{}: no element", entry.path, t.head)),
}
}
}
}
let unused = used.iter().filter(|u| !**u).count();
if unused > 0 {
problems.push(format!("{legacy}: {unused} twin texts without a legacy record"));
}
}
for (name, (ok, n)) in &checks {
eprintln!("{name:24} {ok:4}/{n:4}");
}
eprintln!("approximated: {approximated:?}");
eprintln!("{decoded}/{heads} text records decoded, {paired} paired with twins, {exact} exact on every field, {elements} document elements");
assert!(problems.is_empty(), "{} problems: {:#?}", problems.len(), &problems[..problems.len().min(30)]);
assert_eq!(decoded, heads, "every text head decodes");
assert_eq!(paired, 372, "the corpus's 372 texts pair with their twins");
assert!(exact >= 371, "all but the one tolerated text match on every field, got {exact}");
}