DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge origin/main into feat/layout-parity
Brandon Thomas6e8e252cc436
diff --cc Cargo.lockindex 27a7e5ebb,222b525f8..b713fd3de--- a/Cargo.lock+++ b/Cargo.lock@@@ -910,7 -910,7 +910,8 @@@ dependencies ="proptest","regex","unicode-bidi",+ "unicode-bidi-mirroring",+ "unicode-segmentation",][[package]]diff --cc crates/compose/Cargo.tomlindex 19ab90a71,83ba81835..e2be89084--- a/crates/compose/Cargo.toml+++ b/crates/compose/Cargo.toml@@@ -10,7 -10,7 +10,8 @@@ workspace = tru[dependencies]unicode-bidi = { workspace = true }+unicode-segmentation = { workspace = true }+ unicode-bidi-mirroring = { workspace = true }designcraft-geom = { workspace = true }designcraft-color = { workspace = true }designcraft-doc = { workspace = true }diff --cc crates/compose/src/lib.rsindex bd33ad748,5a3056d8f..156f55a90--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -559,9 -583,8 +597,9 @@@ fn compose_with_db(doc: &Document, stornotes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub);}let sub_objects = sub.objects.clone();+ let drop_end = drop_cap_end(&story.text, prange.clone(), &pp, sub.vertical);let mut table = StyleTable { styles: &mut styles_tab, missing: &mut missing_fonts };- let env = shape::TypeEnv { auto_leading: pp.auto_leading, adv: doc.settings.advanced_type };+ let env = shape::TypeEnv { auto_leading: pp.auto_leading, adv: doc.settings.advanced_type, glyph_fallback: doc.settings.glyph_fallback };let mut sp = shape::shape_para(db,&doc.styles,@@@ -653,17 -654,8 +691,19 @@@);}}+ // Rules in Text Color: the colour of the paragraph's first character (rule above) and last+ // character (rule below).+ let text_color = |g: Option<&Glyph>| {+ g.and_then(|g| table.styles.get(g.style as usize))+ .map_or((base_chars.fill.clone(), base_chars.fill_tint), |s| (s.fill.clone(), s.fill_tint))+ };+ let (above, below) = (text_color(sp.glyphs.iter().find(|g| g.len > 0)), text_color(sp.glyphs.iter().rev().find(|g| g.len > 0)));+ let rule_color = |r: &designcraft_doc::Rule, text: &(String, f32)| {+ if r.color == designcraft_doc::TEXT_COLOR { text.clone() } else { (r.color.clone(), r.tint) }+ };+ let drop_cap = split_drop_cap(db, &mut sp.glyphs, drop_end, pp.drop_cap_lines, base_leading, base_cap, drop_grid, drop_align);+ // List labels take the default super/subscript settings.+ let label_env = shape::TypeEnv { adv: Default::default(), ..env };match pp.list_type {designcraft_doc::ListType::Numbers if !pp.list_name.is_empty() => {// A named list: carries on past other paragraphs (and from earlier stories).@@@ -767,31 -755,39 +814,36 @@@for (k, b) in breaks.iter().enumerate() {let (s, e) = (g0 + b.start, g0 + b.end);let line_glyphs = &glyphs[s..e.max(s)];- let (asc, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);+ let (asc, tops, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);+ let reference = cjk_line_reference(line_glyphs);- let mut baseline = cur.next_baseline(f, col, lead, asc, &pp);+ // Baseline grid: the next grid line at or below.+ let grid = f.grid.filter(|&(_, inc)| {+ inc > 0.0 && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))+ });+ let snap = |y: f64| grid.map_or(y, |(g_start, inc)| g_start + ((y - g_start) / inc - 1e-6).ceil() * inc);- let mut baseline = snap(cur.next_baseline(f, col, lead, asc, tops, &pp));++ let mut baseline = cur.next_baseline(f, col, lead, asc, tops, &pp);+ if cur.last_baseline.is_some() {+ baseline += cur.last_reference - reference;+ }- // Baseline grid.- if let Some((g_start, inc)) = f.grid- && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))- && inc > 0.0- {- let n = ((baseline - g_start) / inc - 1e-6).ceil();- baseline = g_start + n * inc;- }- // Wrap: push the line down until a slot exists.++ baseline = snap(baseline);+ // Wrap: push the line down to the first position with a slot (back on the grid).let (mut x0, mut x1) = (col.x0, col.x1);if !f.exclusions.is_empty() {+ let jump = cur.jump(f, lead, asc, tops);let mut tries = 0;loop {- match free_slot(f, col, baseline - asc, baseline + desc, base_size) {- Some((a, b)) => {- x0 = a;- x1 = b;- break;- }- None => {- baseline += 1.0;- tries += 1;- if baseline > col.y1 || tries > 4000 {- break;- }- }+ let Some((nb, (a, z))) = wrap_slot(f, col, baseline, asc, desc, jump, base_size) else {+ // No room in this column.+ baseline = baseline.max(col.y1) + 1.0;+ break;+ };+ let pushed = nb > baseline;+ (baseline, x0, x1) = (nb, a, z);+ tries += 1;+ if !pushed || grid.is_none() || tries > 4000 {+ break;}+ baseline = snap(baseline);}}let capped = line_cap[pi] == Some(line_no) && line_no > col_first_line;@@@ -844,31 -840,13 +896,31 @@@moved = true;break;}- let ind_l = pp.left_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 };+ // A drop cap sits at the start-side indent; the first-line indent doesn't move it.+ let beside = drop_cap.as_ref().filter(|dc| line_no < dc.lines && col_first_line == 0).map(DropCap::indent);+ let (ind_l, ind_r) = match beside {+ Some(w) if rtl => (pp.left_indent, pp.right_indent + w),+ Some(w) => (pp.left_indent + w, pp.right_indent),+ None => (pp.left_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 }, pp.right_indent),+ };let lx0 = x0 + ind_l;- let lx1 = x1 - pp.right_indent;+ let lx1 = x1 - ind_r;let last = k + 1 == breaks.len();let (mut placed, end_x, ratio) =- layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page);+ layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page, &bidi_info);+ let mut drop_box = None;+ if line_no == 0+ && let Some(dc) = &drop_cap+ {+ let at = if rtl { x1 - pp.right_indent - dc.width } else { x0 + pp.left_indent - dc.lsb };+ placed.splice(0..0, place_drop_cap(dc, at, rtl));+ drop_box = Some(DropCapBox {+ end: dc.end,+ baseline: baseline + dc.drop,+ rect: Rect::new(at, baseline - asc, at + dc.width, baseline + dc.drop + desc),+ });+ }- ruby::annotate(&styles_tab, &mut placed);+ ruby::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);let range_start = if line_no == 0 { prange.start } else { range_start };@@@ -1399,121 -1392,64 +1487,154 @@@ impl Cursor}}+/// The frame's first baseline offset below the top of a column, for a line with leading `lead`,+/// ascent `asc` and first baseline heights `tops`.+fn first_baseline_offset(f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> f64 {+ let off = match f.opts.first_baseline {+ // Vertical frames measure from the ascent.- FirstBaseline::Ascent if f.opts.vertical => asc,- FirstBaseline::CapHeight if f.opts.vertical => asc * 0.72,- FirstBaseline::XHeight if f.opts.vertical => asc * 0.5,++ FirstBaseline::Ascent if f.vertical => asc,++ FirstBaseline::CapHeight if f.vertical => asc * 0.72,++ FirstBaseline::XHeight if f.vertical => asc * 0.5,+ FirstBaseline::Ascent => tops.typo_ascent,+ FirstBaseline::CapHeight => tops.cap,+ FirstBaseline::XHeight => tops.xh,+ FirstBaseline::Leading => lead,+ FirstBaseline::Fixed => 0.0,+ };+ off.max(f.opts.first_baseline_min)+}++/// A line's tallest typographic ascender, cap height and x height above its baseline: the+/// first baseline offsets.+#[derive(Clone, Copy, Default)]+struct Tops {+ typo_ascent: f64,+ cap: f64,+ xh: f64,+}++ /// Em box relative to the baseline. Font ascender/descender proportions locate it;+ /// the box's total extent is the em, rather than the font's optional line gap.+ fn cjk_em_box(g: &Glyph) -> (f64, f64) {+ let height = g.face.units_per_em() * g.sy.abs();+ let top = -height * g.ascent / (g.ascent + g.descent).max(1e-9);+ (top, top + height)+ }+ fn cjk_alignment_shift(g: &Glyph, reference: &Glyph) -> f64 {+ use designcraft_doc::cjk::CharacterAlignment as A;+ let (t, b) = cjk_em_box(g);+ let (rt, rb) = cjk_em_box(reference);+ match g.character_alignment {+ A::Baseline => 0.0,+ A::EmTop => t - rt,+ A::EmCenter => (t + b - rt - rb) / 2.0,+ A::EmBottom => b - rb,+ A::IcfTop => reference.ascent - g.ascent,+ A::IcfBottom => g.descent - reference.descent,+ }+ }+ fn cjk_line_reference(line: &[Glyph]) -> f64 {+ use designcraft_doc::cjk::LeadingModel as L;+ let Some(g) = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)) else { return 0.0 };+ let (top, bottom) = cjk_em_box(g);+ match g.leading_model {+ L::Roman => 0.0,+ L::AkiBelow => bottom,+ L::AkiAbove => top,+ L::Center | L::CenterDown => (top + bottom) / 2.0,+ }+ }+fn line_metrics(line: &[Glyph],all: &[Glyph],s: usize,base_leading: f64,base_size: f64,- db: &FontDb,+ db: &ScopedFonts<'_>,base: &designcraft_doc::CharProps,-) -> (f64, f64, f64) {+) -> (f64, Tops, f64, f64) {- let _ = db;let src: &[Glyph] = if line.is_empty() { all.get(s..(s + 1).min(all.len())).unwrap_or(&[]) } else { line };if src.is_empty() {- let face = FontDb::global().face(&base.font_family, &base.font_style);+ let face = db.face(&base.font_family, &base.font_style);let k = base_size / face.upem;- return (face.ascent * k, face.descent * k, base_leading);+ let tops = Tops { typo_ascent: face.typo_ascent * k, cap: face.cap_height * k, xh: face.x_height * k };+ return (face.ascent * k, tops, face.descent * k, base_leading);}let mut asc: f64 = 0.0;+ let mut tops = Tops::default();let mut desc: f64 = 0.0;let mut lead: f64 = 0.0;+ let reference = src.iter().max_by(|a, b| a.size.total_cmp(&b.size));for g in src {- asc = asc.max(g.ascent + g.shift.max(0.0));- let up = g.shift.max(0.0);+ let shift = g.shift + reference.map_or(0.0, |r| cjk_alignment_shift(g, r));- asc = asc.max(g.ascent + shift.max(0.0));++ let up = shift.max(0.0);++ asc = asc.max(g.ascent + up);+ tops.typo_ascent = tops.typo_ascent.max(g.typo_ascent + up);+ tops.cap = tops.cap.max(g.cap + up);+ tops.xh = tops.xh.max(g.xh + up);- desc = desc.max(g.descent - g.shift.min(0.0));+ desc = desc.max(g.descent - shift.min(0.0));lead = lead.max(g.leading);}- (asc, desc, lead)+ (asc, tops, desc, lead)+}++/// How a line clears Jump Object wraps. The line occupies `[baseline − top, baseline]` (its leading,+/// or its first baseline offset at the top of a column) and must not overlap the wrap; it may hang its+/// descenders into the wrap. Below a wrap it moves down from its place in whole `step`s until it clears+/// the wrap bottom (`step` 0: its top lands on the wrap bottom).+#[derive(Clone, Copy, Debug)]+struct Jump {+ top: f64,+ step: f64,+}++/// Slack for float error when a line is tested against a Jump Object wrap's edges.+const JUMP_EPS: f64 = 1e-6;++/// The first baseline at or below `baseline` where a line with ascent `asc` and descent `desc` has a+/// free slot in `col`, and that slot; None if there is none above the column bottom.+///+/// A line under a Jump Object wrap moves below it as `jump` says. Other wraps are rectangles, so the+/// free space only grows where one in the line's band ends: the search jumps from one such bottom+/// edge to the next, and a line that clears a wrap has its top exactly on the wrap's bottom.+fn wrap_slot(f: &FrameSpec, col: Rect, baseline: f64, asc: f64, desc: f64, jump: Jump, size: f64) -> Option<(f64, (f64, f64))> {+ let top = jump.top.max(0.0);+ let mut b = baseline;+ // Each step passes at least one wrap; the cap bounds hostile geometry.+ for _ in 0..4000 {+ let jumped = f+ .exclusions+ .iter()+ .filter(|e| e.mode == WrapMode::JumpObject)+ .map(|e| e.rect)+ .filter(|r| r.x0 < col.x1 && r.x1 > col.x0 && b > r.y0 + JUMP_EPS && b - top < r.y1 - JUMP_EPS)+ .fold(f64::NEG_INFINITY, |m, r| m.max(r.y1));+ b = if jumped > f64::NEG_INFINITY {+ if jump.step > 0.0 {+ // Whole steps from the line's own place (at least one step past the line above).+ baseline + ((jumped + top - baseline - JUMP_EPS / 2.0) / jump.step).ceil().max(0.0) * jump.step+ } else {+ jumped + top+ }+ } else if let Some(slot) = free_slot(f, col, b - asc, b + desc, size) {+ return Some((b, slot));+ } else {+ let (y0, y1) = (b - asc, b + desc);+ let edge = f+ .exclusions+ .iter()+ .filter(|e| e.mode != WrapMode::JumpObject)+ .map(|e| e.rect)+ .filter(|r| r.y0 < y1 && r.y1 > y0)+ .fold(f64::INFINITY, |m, r| m.min(r.y1));+ edge + asc+ };+ if b.is_nan() || b > col.y1 {+ return None;+ }+ }+ None}/// Widest free horizontal interval of `col` in the band, or None if blocked.@@@ -2034,124 -1987,8 +2182,124 @@@ fn place(g: &Glyph, x: f64) -> PlacedGl}}+/// Drop caps are at most this many lines and characters (larger values are capped).+pub const MAX_DROP_CAP_LINES: u32 = 25;+pub const MAX_DROP_CAP_CHARS: u32 = 150;++/// Byte where paragraph `prange`'s drop cap ends: after its first `drop_cap_chars` characters+/// (code points, as InDesign counts them, spaces included), extended to the end of the grapheme+/// cluster they end in so a letter keeps its combining marks; all of them in a shorter paragraph.+/// `prange.start` when it has none: no lines or characters, or vertical text (which sets no drop+/// caps).+fn drop_cap_end(text: &str, prange: Range<usize>, pp: &ParaProps, vertical: bool) -> usize {+ use unicode_segmentation::UnicodeSegmentation as _;+ if vertical || pp.drop_cap_lines == 0 || pp.drop_cap_chars == 0 {+ return prange.start;+ }+ let Some(para) = text.get(prange.clone()) else { return prange.start };+ let para = para.trim_end_matches('\n');+ let n = pp.drop_cap_chars.min(MAX_DROP_CAP_CHARS) as usize;+ let end = para.char_indices().nth(n).map_or(para.len(), |(i, _)| i);+ prange.start + para.grapheme_indices(true).map(|(i, _)| i).find(|i| *i >= end).unwrap_or(para.len())+}++/// A paragraph's drop cap: its first glyphs, enlarged to reach down `lines` lines.+struct DropCap {+ glyphs: Vec<Glyph>,+ /// Story byte it ends at.+ end: usize,+ lines: usize,+ /// Its advance.+ width: f64,+ /// How far its origin sits left of the indent: its first letter's left side bearing with+ /// Align Left Edge, else 0.+ lsb: f64,+ /// Its baseline below the first line's, at the paragraph's leading.+ drop: f64,+}++/// Take the drop cap (the glyphs before byte `end`) off the front of a paragraph's glyphs and scale+/// it so its cap height reaches from the first line's cap height down to line `lines`' baseline,+/// measured in the leading and cap height of the text after it.+/// On a baseline grid of increment `grid`, lines are that many grid steps apart. With+/// `align_left` its ink starts at the indent (see [`DropCap::lsb`]).+#[allow(clippy::too_many_arguments)]+fn split_drop_cap(- db: &FontDb,++ db: &ScopedFonts<'_>,+ glyphs: &mut Vec<Glyph>,+ end: usize,+ lines: u32,+ base_leading: f64,+ base_cap: f64,+ grid: Option<f64>,+ align_left: bool,+) -> Option<DropCap> {+ let n = glyphs.iter().take_while(|g| g.byte < end).count();+ if n == 0 {+ return None;+ }+ let lines = lines.clamp(1, MAX_DROP_CAP_LINES) as usize;+ let mut dc: Vec<Glyph> = glyphs.drain(..n).collect();+ let body = glyphs.iter().find(|g| g.len > 0 && g.cap > 0.0);+ let (lead, cap) = body.map_or((base_leading, base_cap), |g| (g.leading, g.cap));+ let lead = match grid.map(|inc| (lead / inc - 1e-6).ceil().max(1.0) * inc) {+ Some(pitch) if pitch.is_finite() && pitch > 0.0 => pitch,+ _ => lead,+ };+ let drop = (lines - 1) as f64 * lead;+ let own = dc.iter().map(|g| g.cap).fold(0.0, f64::max);+ let k = if own > 0.0 { (drop + cap) / own } else { 1.0 };+ let k = if k.is_finite() && k > 0.0 { k.min(1000.0) } else { 1.0 };+ for g in &mut dc {+ g.adv *= k;+ g.dx *= k;+ g.dy *= k;+ g.sx *= k;+ g.sy *= k;+ g.ascent *= k;+ g.typo_ascent *= k;+ g.descent *= k;+ g.cap *= k;+ g.xh *= k;+ g.size *= k;+ g.space *= k;+ }+ let width = dc.iter().map(|g| g.adv).sum();+ let lsb = match dc.first() {+ Some(g) if align_left => {+ let ink = designcraft_geom::Shape::bounding_box(&*db.outline(g.face.get(), g.gid));+ let lsb = g.dx + ink.x0 * g.sx;+ if ink.width() > 0.0 && lsb.is_finite() { lsb } else { 0.0 }+ }+ _ => 0.0,+ };+ Some(DropCap { glyphs: dc, end, lines, width, drop, lsb })+}++impl DropCap {+ /// How far the lines beside it are indented: to the end of its advance.+ fn indent(&self) -> f64 {+ self.width - self.lsb+ }+}++/// The drop cap's glyphs set from `at` (right to left: mirrored, its first character on the right).+fn place_drop_cap(dc: &DropCap, at: f64, rtl: bool) -> Vec<PlacedGlyph> {+ let mut x = at;+ let mut out = Vec::with_capacity(dc.glyphs.len());+ for g in &dc.glyphs {+ let pen = if rtl { at + at + dc.width - x - g.adv } else { x };+ let mut p = place(g, pen);+ p.y += dc.drop;+ p.rtl = rtl;+ out.push(p);+ x += g.adv;+ }+ out+}+fn prepend_label(- db: &FontDb,+ db: &ScopedFonts<'_>,glyphs: &mut Vec<Glyph>,label: &str,at: usize,@@@ -2163,21 -2000,7 +2311,7 @@@let mut tmp = Story::new(StoryId(0));tmp.insert(0, label);let styles = designcraft_doc::Styles::default();- let shaped = shape::shape_para(- db,- &styles,- &tmp,- 0,- 0..label.len(),- base,- shape::TypeEnv { auto_leading: pp.auto_leading, adv: Default::default() },- &SubstCtx::default(),- table,- &[],- &[],- &[],- (0, ""),- );- let shaped = shape::shape_para(db, &styles, &tmp, 0, 0..label.len(), base, env, &SubstCtx::default(), table, &[], &[], &[]);++ let shaped = shape::shape_para(db, &styles, &tmp, 0, 0..label.len(), base, env, &SubstCtx::default(), table, &[], &[], &[], (0, ""));let mut pre: Vec<Glyph> = shaped.glyphs.into_iter()diff --cc crates/compose/src/shape.rsindex 14a5ffd34,41583b0a9..6448ab4bb--- a/crates/compose/src/shape.rs+++ b/crates/compose/src/shape.rs@@@ -154,12 -169,18 +173,19 @@@ impl StyleTable<'_>self.styles.push(rs);(self.styles.len() - 1) as u32}++ /// `env` for text in run style `style`: a missing font's substitute draws the characters it+ /// lacks from fallback fonts whatever the document's setting.+ fn env_for(&self, env: TypeEnv, style: u32) -> TypeEnv {+ let missing = self.styles.get(style as usize).is_some_and(|s| s.missing_font);+ TypeEnv { glyph_fallback: env.glyph_fallback || missing, ..env }+ }}-/// Resolve and shape one paragraph.+/// Resolve and shape one paragraph. Its drop cap ends at byte `drop.0` (`range.start` without+/// one) and takes the character style `drop.1` ("" = none).pub(crate) fn shape_para(- db: &FontDb,+ db: &ScopedFonts<'_>,styles: &Styles,story: &Story,pi: usize,diff --cc crates/compose/src/tests.rsindex 9d6d29e92,549e7bccf..b9da78381--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -1267,526 -1069,811 +1308,1339 @@@ fn only_english_text_gets_english_hypheassert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules");}+/// OS/2 field offsets: sTypoAscender, sxHeight, sCapHeight.+const TYPO_ASCENDER: usize = 68;+const X_HEIGHT: usize = 86;+const CAP_HEIGHT: usize = 88;++/// Source Sans 3 Regular (1000 units per em; OS/2 typo ascender = hhea ascender = 1000, cap height+/// 660, x height 486) renamed to `family` (13 characters, the length of "Source Sans 3"), with the+/// OS/2 fields at the given offsets set, or without an OS/2 table for `None`.+fn test_font(family: &str, os2_fields: Option<&[(usize, i16)]>) -> Vec<u8> {+ let mut b = designcraft_fonts::bundled()[0].to_vec();+ assert_eq!(family.len(), "Source Sans 3".len());+ let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();+ for (from, to) in [(utf16("Source Sans 3"), utf16(family)), (b"Source Sans 3".to_vec(), family.as_bytes().to_vec())] {+ let mut i = 0;+ while let Some(p) = b[i..].windows(from.len()).position(|w| w == from.as_slice()) {+ b[i + p..i + p + to.len()].copy_from_slice(&to);+ i += p + to.len();+ }+ }+ let tables = u16::from_be_bytes([b[4], b[5]]) as usize;+ let rec = (0..tables).map(|t| 12 + 16 * t).find(|&r| &b[r..r + 4] == b"OS/2").unwrap();+ match os2_fields {+ Some(fields) => {+ let os2 = u32::from_be_bytes(b[rec + 8..rec + 12].try_into().unwrap()) as usize;+ for &(at, v) in fields {+ b[os2 + at..os2 + at + 2].copy_from_slice(&v.to_be_bytes());+ }+ }+ // Still sorted between its neighbours, so the table directory stays valid.+ None => b[rec..rec + 4].copy_from_slice(b"OS/1"),+ }+ b+}++/// [`test_font`] with OS/2 `sTypoAscender` set to `typo_ascender`, or without OS/2 for `None`.+fn typo_test_font(family: &str, typo_ascender: Option<i16>) -> Vec<u8> {+ test_font(family, typo_ascender.map(|v| [(TYPO_ASCENDER, v)]).as_ref().map(|f| f.as_slice()))+}++/// First baseline (frame space) of a 20 pt line in `family` in a frame at y = 36 with a 4 pt top+/// inset, set up by `opts`.+fn first_baseline_in(family: &str, opts: impl Fn(&mut designcraft_doc::TextFrameOptions)) -> f64 {++ first_baseline_in_dir(family, false, opts)++}++++/// [`first_baseline_in`] in a vertical story when `vertical`.++fn first_baseline_in_dir(family: &str, vertical: bool, opts: impl Fn(&mut designcraft_doc::TextFrameOptions)) -> f64 {+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..7, |f| {+ f.over.font_family = Some(family.into());+ f.over.font_style = Some("Regular".into());+ f.over.size = Some(20.0);+ });++ d.story_mut(sid).unwrap().vertical = vertical;+ let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();+ tf.options.inset = [4.0, 0.0, 0.0, 0.0];+ opts(&mut tf.options);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].baseline+}++#[test]+fn ascent_first_baseline_uses_the_typographic_ascender() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ db.add_font(typo_test_font("TypoAscent 07", Some(700)));+ let face = db.face("TypoAscent 07", "Regular");+ assert_eq!(face.family, "TypoAscent 07");+ assert_eq!((face.ascent, face.typo_ascent), (1000.0, 700.0), "hhea 1 em, typo 0.7 em");+ let top = 36.0 + 4.0;+ let at = |kind: FirstBaseline, min: f64| {+ first_baseline_in("TypoAscent 07", |o| {+ o.first_baseline = kind;+ o.first_baseline_min = min;+ })+ };+ let close = |a: f64, b: f64| (a - b).abs() < 0.01;+ // Ascent: top + typo ascender (0.7 em of 20 pt), not the hhea ascender (1 em).+ assert!(close(at(FirstBaseline::Ascent, 0.0), top + 14.0), "{}", at(FirstBaseline::Ascent, 0.0));+ // The minimum offset still wins when it is larger.+ assert!(close(at(FirstBaseline::Ascent, 18.0), top + 18.0));+ assert!(close(at(FirstBaseline::Ascent, 10.0), top + 14.0));+ // The other kinds don't use it.+ assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 0.660 * 20.0));+ assert!(close(at(FirstBaseline::XHeight, 0.0), top + 0.486 * 20.0));+ assert!(close(at(FirstBaseline::Leading, 0.0), top + 24.0));+ assert!(close(at(FirstBaseline::Fixed, 0.0), top));+ // Vertical scale scales it like the ascent.+ let (mut d, sid, fid) = doc_with("Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {+ f.over.font_family = Some("TypoAscent 07".into());+ f.over.size = Some(20.0);+ f.over.v_scale = Some(1.5);+ });+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [4.0, 0.0, 0.0, 0.0];+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];+ assert!(close(l.baseline, top + 21.0), "{}", l.baseline);+ // The line box keeps the font's ascent.+ assert!(close(l.ascent, 30.0), "{}", l.ascent);+ // A mixed first line takes its tallest typographic ascender: 0.7 × 20 pt beats 1 em × 10 pt …+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..3, |f| {+ f.over.font_family = Some("TypoAscent 07".into());+ f.over.size = Some(20.0);+ });+ st.format_chars(3..7, |f| {+ f.over.font_family = Some("Source Sans 3".into());+ f.over.size = Some(10.0);+ });+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [4.0, 0.0, 0.0, 0.0];+ let first = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline;+ assert!(close(first(&d), top + 14.0), "{}", first(&d));+ // … and 1 em × 16 pt beats it.+ d.story_mut(sid).unwrap().format_chars(3..7, |f| f.over.size = Some(16.0));+ assert!(close(first(&d), top + 16.0), "{}", first(&d));+}++#[test]+fn ascent_first_baseline_falls_back_to_the_ascent_without_a_usable_typo_ascender() {+ let db = designcraft_fonts::FontDb::global();+ // No OS/2 table, a negative and an absurd typo ascender: the (hhea) ascent, 1 em.+ for (family, typo) in [("TypoAscentNoO", None), ("TypoAscentNeg", Some(-300)), ("TypoAscentBig", Some(i16::MAX))] {+ db.add_font(typo_test_font(family, typo));+ let face = db.face(family, "Regular");+ assert_eq!(face.family, family);+ assert_eq!(face.typo_ascent, face.ascent, "{family}");+ let b = first_baseline_in(family, |_| {});+ assert!((b - (36.0 + 4.0 + 20.0)).abs() < 0.01, "{family}: {b}");+ }+}++#[test]+fn vertical_frames_keep_the_ascent_first_baseline() {+ let db = designcraft_fonts::FontDb::global();+ db.add_font(typo_test_font("TypoAscentVrt", Some(700)));- let b = first_baseline_in("TypoAscentVrt", |o| {- o.vertical = true;++ let b = first_baseline_in_dir("TypoAscentVrt", true, |o| {+ o.inset = [0.0; 4];+ });+ // Composed in the turned box (no inset): the hhea ascent, 1 em of 20 pt.+ assert!((b - 20.0).abs() < 0.01, "{b}");+}++#[test]+fn cap_height_and_x_height_first_baselines_use_the_fonts_cap_and_x_heights() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ db.add_font(test_font("CapXHeight 01", Some(&[(CAP_HEIGHT, 500), (X_HEIGHT, 300)])));+ let face = db.face("CapXHeight 01", "Regular");+ assert_eq!(face.family, "CapXHeight 01");+ assert_eq!((face.ascent, face.cap_height, face.x_height), (1000.0, 500.0, 300.0));+ let top = 36.0 + 4.0;+ let at = |kind: FirstBaseline, min: f64| {+ first_baseline_in("CapXHeight 01", |o| {+ o.first_baseline = kind;+ o.first_baseline_min = min;+ })+ };+ let close = |a: f64, b: f64| (a - b).abs() < 0.01;+ // Cap height 0.5 em and x height 0.3 em of 20 pt, not 0.72 / 0.5 of the 1 em ascent.+ assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 10.0), "{}", at(FirstBaseline::CapHeight, 0.0));+ assert!(close(at(FirstBaseline::XHeight, 0.0), top + 6.0), "{}", at(FirstBaseline::XHeight, 0.0));+ // The minimum offset still wins when it is larger.+ assert!(close(at(FirstBaseline::CapHeight, 12.0), top + 12.0));+ assert!(close(at(FirstBaseline::XHeight, 5.0), top + 6.0));+ // Vertical scale and a raised baseline count, as for the ascent.+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..7, |f| {+ f.over.font_family = Some("CapXHeight 01".into());+ f.over.size = Some(20.0);+ f.over.v_scale = Some(1.5);+ });+ st.format_chars(4..5, |f| f.over.baseline_shift = Some(1.0));+ let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();+ tf.options.inset = [4.0, 0.0, 0.0, 0.0];+ tf.options.first_baseline = FirstBaseline::CapHeight;+ let first = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline;+ assert!(close(first(&d), top + 15.0 + 1.0), "{}", first(&d));+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::XHeight;+ assert!(close(first(&d), top + 9.0 + 1.0), "{}", first(&d));+}++#[test]+fn cap_height_and_x_height_fall_back_without_usable_os2_values() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ // No OS/2 table, zero / negative and absurd values: the top of the H (0.656 em) and 0.5 of the+ // (1 em) ascent.+ let zero: &[(usize, i16)] = &[(CAP_HEIGHT, 0), (X_HEIGHT, -40)];+ let big: &[(usize, i16)] = &[(CAP_HEIGHT, i16::MAX), (X_HEIGHT, i16::MAX)];+ for (family, fields) in [("CapXHeightNoO", None), ("CapXHeightNeg", Some(zero)), ("CapXHeightBig", Some(big))] {+ db.add_font(test_font(family, fields));+ let face = db.face(family, "Regular");+ assert_eq!(face.family, family);+ assert_eq!((face.cap_height, face.x_height), (656.0, face.ascent * 0.5), "{family}");+ let cap = first_baseline_in(family, |o| o.first_baseline = FirstBaseline::CapHeight);+ let x = first_baseline_in(family, |o| o.first_baseline = FirstBaseline::XHeight);+ assert!((cap - (40.0 + 13.12)).abs() < 0.01 && (x - (40.0 + 10.0)).abs() < 0.01, "{family}: {cap} {x}");+ }+}++#[test]+fn vertical_frames_keep_the_cap_height_and_x_height_first_baselines() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ db.add_font(test_font("CapXHeightVrt", Some(&[(CAP_HEIGHT, 500), (X_HEIGHT, 300)])));+ let at = |kind: FirstBaseline| {- first_baseline_in("CapXHeightVrt", |o| {++ first_baseline_in_dir("CapXHeightVrt", true, |o| {+ o.first_baseline = kind;- o.vertical = true;+ o.inset = [0.0; 4];+ })+ };+ // 0.72 and 0.5 of the 1 em ascent of 20 pt.+ assert!((at(FirstBaseline::CapHeight) - 14.4).abs() < 0.01, "{}", at(FirstBaseline::CapHeight));+ assert!((at(FirstBaseline::XHeight) - 10.0).abs() < 0.01, "{}", at(FirstBaseline::XHeight));+}++// ---------- drop caps ----------++/// `text` set 10 pt on 12 pt leading in a 300 pt measure, with `para` on top.+fn drop_doc(text: &str, para: ParaAttrs) -> (Document, StoryId, ItemId) {+ drop_doc_in(text, Rect::new(0.0, 0.0, 300.0, 1000.0), para)+}++fn drop_doc_in(text: &str, rect: Rect, para: ParaAttrs) -> (Document, StoryId, ItemId) {+ let (mut d, sid, fid) = doc_with(text, rect, para);+ for p in &mut d.story_mut(sid).unwrap().paras {+ p.chars = designcraft_doc::CharAttrs { size: Some(10.0), leading: Some(designcraft_doc::Leading::Points(12.0)), ..Default::default() };+ }+ (d, sid, fid)+}++fn drop_cap(lines: u32, chars: u32) -> ParaAttrs {+ ParaAttrs { drop_cap_lines: Some(lines), drop_cap_chars: Some(chars), ..Default::default() }+}++/// Cap height of a placed glyph, in points.+fn cap_of(g: &PlacedGlyph) -> f64 {+ g.face.cap_height * g.sy+}++/// x of the first glyph of `l` set from story byte `from` on.+fn text_x(l: &Line, from: usize) -> f64 {+ l.glyphs.iter().find(|g| g.len > 0 && g.byte >= from).map(|g| g.x).unwrap()+}++#[test]+fn drop_cap_spans_lines_and_indents_them() {+ let text = [LOREM; 2].join(" ");+ let (plain, psid, _) = drop_doc(&text, ParaAttrs::default());+ let plain = compose_story(&plain, psid, &ComposeOptions::default());+ let (d, sid, _) = drop_doc(&text, drop_cap(3, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let pl = all_lines(&plain);+ assert!(lines.len() > 4);+ // Baselines don't move.+ for (k, l) in lines.iter().enumerate() {+ assert!((l.baseline - (pl[0].baseline + 12.0 * k as f64)).abs() < 1e-6, "line {k} at {}", l.baseline);+ }+ // The drop cap: the first glyph, on line 1, its baseline on line 3's and its cap top on line 1's.+ let dc = &lines[0].glyphs[0];+ assert_eq!((dc.byte, dc.len), (0, 1));+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "drop cap baseline {}", lines[0].baseline + dc.y);+ let body = lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ let top = lines[2].baseline - cap_of(dc);+ assert!((top - (lines[0].baseline - cap_of(body))).abs() < 0.01, "cap top {top}");+ assert!(dc.sy > body.sy * 3.0);+ // Lines 1–3 start after it, line 4 at the frame edge.+ let right = dc.x + dc.adv;+ assert!(right > 20.0);+ for l in &lines[..3] {+ assert!(text_x(l, 1) >= right - 1e-6, "{} < {right}", text_x(l, 1));+ assert!(l.end_x <= l.x1 + 0.5);+ }+ assert!(text_x(lines[3], 1) < 0.5);+ // The text stays in order: the drop cap starts line 1 (exports and caret read it there).+ assert_eq!(lines[0].range.start, 0);+}++#[test]+fn drop_cap_of_two_characters_as_a_local_override() {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(2, 2));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let (a, b) = (&lines[0].glyphs[0], &lines[0].glyphs[1]);+ assert_eq!((a.byte, b.byte), (0, 1));+ let body = lines[0].glyphs.iter().find(|g| g.byte == 2).unwrap();+ for g in [a, b] {+ assert!((lines[0].baseline + g.y - lines[1].baseline).abs() < 1e-6);+ assert!(g.sy > body.sy * 1.5);+ }+ assert!((b.x - (a.x + a.adv)).abs() < 1e-6, "the drop cap characters sit side by side");+ let right = b.x + b.adv;+ assert!(text_x(lines[0], 2) >= right - 1e-6 && text_x(lines[1], 2) >= right - 1e-6);+ assert!(text_x(lines[2], 2) < 0.5);+}++#[test]+fn short_paragraph_keeps_its_drop_cap_and_the_next_paragraph_is_not_indented() {+ let (mut d, sid, _) = drop_doc(&format!("Short.\n{LOREM}"), drop_cap(3, 1));+ d.story_mut(sid).unwrap().paras[1].para = ParaAttrs::default();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.iter().filter(|l| l.para == 0).count(), 1);+ let dc = &lines[0].glyphs[0];+ // Still three lines tall (it may overlap the next paragraph, which isn't indented).+ assert!((dc.y - 24.0).abs() < 1e-6, "{}", dc.y);+ assert!(text_x(lines[1], 7) < 0.5);+}++#[test]+fn drop_cap_counts_code_points_without_splitting_clusters_and_clamps_to_the_paragraph() {+ // Four characters: a letter, its combining mark, another letter and a no-break space.+ let (d, sid, _) = drop_doc("A\u{301}B\u{a0}rest of the words", drop_cap(2, 4));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let big: Vec<usize> = l.glyphs.iter().filter(|g| g.len > 0 && g.y > 1.0).map(|g| g.byte).collect();+ assert!(big.contains(&0) && big.contains(&3), "{big:?}");+ assert!(big.iter().all(|b| *b < 6), "the r isn't part of it: {big:?}");+ // One character that has a combining mark after it takes the mark too.+ let (d, sid, _) = drop_doc("e\u{301}tude and more words", drop_cap(2, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let big: Vec<usize> = l.glyphs.iter().filter(|g| g.y > 1.0).map(|g| g.byte).collect();+ assert!(!big.is_empty() && big.iter().all(|b| *b < 3), "{big:?}");+ assert!(l.glyphs.iter().any(|g| g.byte == 0 && g.y > 1.0));+ // More characters than the paragraph has: all of them, and nothing of the next paragraph.+ let (mut d, sid, _) = drop_doc("Hi\nNext", drop_cap(2, 50));+ d.story_mut(sid).unwrap().paras[1].para = ParaAttrs::default();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines[0].glyphs.iter().filter(|g| g.len > 0).all(|g| g.y > 1.0));+ assert!(lines[1].glyphs.iter().all(|g| g.y.abs() < 1e-6));+}++#[test]+fn hostile_drop_cap_values_do_not_panic() {+ for (lines, chars) in [(u32::MAX, u32::MAX), (1_000_000, 1), (2, 0), (0, 3)] {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(lines, chars));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let g = &cs.frames[0].lines[0].glyphs[0];+ assert!(g.y.is_finite() && g.sy.is_finite() && g.y <= 12.0 * 25.0, "{lines}/{chars}: {}", g.y);+ }+ // No lines or no characters: no drop cap.+ let (d, sid, _) = drop_doc(LOREM, drop_cap(0, 3));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs[0].y.abs() < 1e-6);+}++#[test]+fn one_line_drop_cap_is_not_enlarged() {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(1, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let (dc, body) = (&l.glyphs[0], l.glyphs.iter().find(|g| g.byte == 1).unwrap());+ assert!((cap_of(dc) - cap_of(body)).abs() < 0.01 && dc.y.abs() < 1e-6);+}++#[test]+fn drop_cap_stays_with_the_first_line_across_a_column_break() {+ // Two lines fit a column: line 3 starts the second column, at its edge.+ let (mut d, sid, fid) = drop_doc_in(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 400.0, 30.0), drop_cap(3, 1));+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ let col1: Vec<&Line> = ft.lines.iter().filter(|l| l.column == 1).collect();+ assert_eq!(ft.lines.iter().filter(|l| l.column == 0).count(), 2, "{:?}", ft.lines.iter().map(|l| l.column).collect::<Vec<_>>());+ let dc = &ft.lines[0].glyphs[0];+ assert!((dc.y - 24.0).abs() < 1e-6, "{}", dc.y);+ assert!(text_x(&ft.lines[1], 1) >= dc.x + dc.adv - 1e-6);+ assert!((text_x(col1[0], 1) - ft.columns[1].x0).abs() < 0.5);+}++#[test]+fn drop_cap_in_right_to_left_paragraphs_is_on_the_right() {+ let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::Right), ..drop_cap(2, 1) };+ let (d, sid, _) = drop_doc(LOREM, para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let dc = lines[0].glyphs.iter().find(|g| g.byte == 0).unwrap();+ assert!((dc.x + dc.adv - 300.0).abs() < 0.5, "{}", dc.x + dc.adv);+ for l in &lines[..2] {+ assert!(l.glyphs.iter().filter(|g| g.byte > 0 && g.visible).all(|g| g.x + g.adv <= dc.x + 0.5));+ }+ assert!(lines[2].end_x > 299.0 || lines[2].glyphs.iter().any(|g| g.x + g.adv > 299.0));+}++#[test]+fn vertical_frames_set_no_drop_cap() {- let (mut d, sid, fid) = drop_doc(LOREM, drop_cap(3, 1));- d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical = true;++ let (mut d, sid, _) = drop_doc(LOREM, drop_cap(3, 1));++ d.story_mut(sid).unwrap().vertical = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs[0].y.abs() < 1e-6);+}++#[test]+fn drop_cap_takes_its_character_style_and_nested_styles_count_it() {+ let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { drop_cap_style: Some("Initial".into()), ..drop_cap(2, 3) });+ for (name, fill) in [("Initial", "Initial Red"), ("Lead", "Lead Blue")] {+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {+ name: name.into(),+ based_on: None,+ chars: designcraft_doc::CharAttrs { fill: Some(fill.into()), ..Default::default() },+ shortcut: String::new(),+ });+ }+ let fill = |cs: &ComposedStory, g: &PlacedGlyph| cs.styles[g.style as usize].fill.clone();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();+ assert_eq!(fill(&cs, at(0)), "Initial Red");+ assert_eq!(fill(&cs, at(2)), "Initial Red");+ assert_eq!(fill(&cs, at(3)), "[Black]");+ // A nested style "through 1 drop cap" covers the drop cap; the next one starts after it.+ let ns = |style: &str, until: designcraft_doc::NestedUntil| designcraft_doc::NestedStyle { style: style.into(), through: true, count: 1, until };+ d.story_mut(sid).unwrap().paras[0].para = ParaAttrs {+ nested_styles: Some(vec![ns("Lead", designcraft_doc::NestedUntil::Dropcap), ns("Initial", designcraft_doc::NestedUntil::Words)]),+ ..drop_cap(2, 3)+ };+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();+ assert_eq!(fill(&cs, at(0)), "Lead Blue");+ assert_eq!(fill(&cs, at(2)), "Lead Blue");+ assert_eq!(fill(&cs, at(3)), "Initial Red", "the second nested style starts after the drop cap");+ let first_space = LOREM.find(' ').unwrap();+ assert_eq!(fill(&cs, at(first_space + 1)), "[Black]");+}++#[test]+fn drop_cap_caret_and_hit_testing() {+ let (d, sid, _) = drop_doc(LOREM, drop_cap(3, 1));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let dc = lines[0].glyphs[0].clone();+ let drop_box = lines[0].drop_cap.unwrap().rect;+ assert!(drop_box.y1 > lines[2].baseline - 0.01 && drop_box.y0 < lines[0].baseline - 5.0, "{drop_box:?}");+ // A click on the lower half of the big letter (beside line 3) is at the drop cap.+ let y = lines[2].baseline - 2.0;+ assert_eq!(hit(&cs, 0, Point::new(dc.x + dc.adv * 0.25, y)), Some(0));+ assert_eq!(hit(&cs, 0, Point::new(dc.x + dc.adv * 0.75, y)), Some(1));+ // The caret before the drop cap is as tall as it; after it, beside line 1's text.+ let (_, x, bl, asc, _) = caret(&cs, 0).unwrap();+ assert!((x - dc.x).abs() < 1e-6 && (bl - lines[2].baseline).abs() < 1e-6 && asc > 24.0, "{x} {bl} {asc}");+ let (_, x, bl, _, _) = caret(&cs, 1).unwrap();+ assert!(x >= dc.x + dc.adv - 1e-6 && (bl - lines[0].baseline).abs() < 1e-6);+}++#[test]+fn drop_cap_sits_on_its_line_as_set() {+ // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap follows line 3.+ let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), ..drop_cap(3, 1) });+ d.settings.baseline_grid.increment = 15.0;+ d.settings.baseline_grid.start = 0.0;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!((lines[1].baseline - lines[0].baseline - 15.0).abs() < 1e-6);+ let dc = &lines[0].glyphs[0];+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6);+ let b = lines[0].drop_cap.unwrap();+ assert!((b.baseline - lines[2].baseline).abs() < 1e-6 && b.rect.y1 > lines[2].baseline);+ // Scaled to the grid's line pitch: its cap top is still line 1's.+ let body = lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert!((lines[2].baseline - cap_of(dc) - (lines[0].baseline - cap_of(body))).abs() < 0.01);+}++/// A rule in Text Color takes the colour of the paragraph's text: the first character's for the+/// rule above, the last character's for the rule below. A swatch colour is used as is.+#[test]+fn text_color_rules_follow_the_text() {+ use designcraft_doc::{CharAttrs, CharFormat, Rule, TEXT_COLOR};+ let rule = Rule { on: true, weight: 2.0, ..Default::default() };+ let para = ParaAttrs { rule_above: Some(rule.clone()), rule_below: Some(rule.clone()), ..Default::default() };+ let (mut d, sid, fid) = doc_with("Red then blue", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ {+ let s = d.story_mut(sid).unwrap();+ s.format_chars(0..3, |f: &mut CharFormat| f.over.merge(&CharAttrs { fill: Some("Red".into()), fill_tint: Some(0.5), ..Default::default() }));+ s.format_chars(9..13, |f: &mut CharFormat| f.over.fill = Some("Blue".into()));+ }+ let decos = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ let mut v: Vec<(f64, String, f32)> = cs.frame(fid).unwrap().decos.iter().map(|dc| (dc.rect.y0, dc.color.clone(), dc.tint)).collect();+ v.sort_by(|a, b| a.0.total_cmp(&b.0));+ v.into_iter().map(|(_, c, t)| (c, t)).collect::<Vec<_>>()+ };+ assert_eq!(rule.color, TEXT_COLOR);+ assert_eq!(decos(&d), vec![("Red".to_string(), 0.5), ("Blue".to_string(), 1.0)]);+ let swatch = Rule { color: "[Black]".into(), tint: 0.3, ..rule };+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(swatch);+ assert_eq!(decos(&d)[0], ("[Black]".to_string(), 0.3));+}++/// Align Left Edge (InDesign's default): the drop cap's origin moves left by its first letter's+/// left side bearing so its ink starts at the indent, and the lines beside it start where its+/// advance ends. Measured case: 14/18 text, two lines, one character.+#[test]+fn drop_cap_aligns_its_left_edge() {+ let text = format!("Once {LOREM}");+ let compose = |align: Option<bool>| {+ let para = ParaAttrs { left_indent: Some(10.0), drop_cap_align_left: align, ..drop_cap(2, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.story_mut(sid).unwrap().paras[0].chars =+ designcraft_doc::CharAttrs { size: Some(14.0), leading: Some(designcraft_doc::Leading::Points(18.0)), ..Default::default() };+ compose_story(&d, sid, &ComposeOptions::default())+ };+ use designcraft_geom::Shape as _;+ let ink_left = |g: &PlacedGlyph| g.x + designcraft_fonts::FontDb::global().outline(g.face.get(), g.gid).bounding_box().x0 * g.sx;+ for align in [None, Some(true), Some(false)] {+ let cs = compose(align);+ let lines = all_lines(&cs);+ let dc = &lines[0].glyphs[0];+ assert_eq!(dc.byte, 0);+ let lsb = ink_left(dc) - dc.x;+ assert!(lsb > 0.5, "the O has a visible side bearing at this size: {lsb}");+ if align != Some(false) {+ assert!((ink_left(dc) - 10.0).abs() < 1e-6, "{align:?}: ink at {}", ink_left(dc));+ } else {+ assert!((dc.x - 10.0).abs() < 1e-6, "origin at {}", dc.x);+ }+ for l in &lines[..2] {+ assert!((text_x(l, 1) - (dc.x + dc.adv)).abs() < 1e-6, "{align:?}: {} vs {}", text_x(l, 1), dc.x + dc.adv);+ }+ assert!((text_x(lines[2], 1) - 10.0).abs() < 1e-6);+ }+}+++ #[test]+ fn cjk_aki_adds_space_without_scaling_outlines() {+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let old = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.leading_aki = Some(Some(0.25));+ f.over.trailing_aki = Some(Some(0.5));+ });+ let new = compose_story(&d, sid, &ComposeOptions::default());+ let a = &old.frames[0].lines[0];+ let b = &new.frames[0].lines[0];+ assert!((b.end_x - a.end_x - 18.0).abs() < 1e-6);+ assert_eq!(a.glyphs[0].sx, b.glyphs[0].sx);+ assert!((b.glyphs[0].x - a.glyphs[0].x - 3.0).abs() < 1e-6);+ }++ #[test]+ fn cjk_jidori_sets_group_width_and_survives_narrow_frames() {+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {+ let (mut d, sid, _) = doc_with(+ "AB",+ Rect::new(0.0, 0.0, 30.0, 150.0),+ ParaAttrs { composer: Some(composer), glyph_scale_desired: Some(1.2), letter_space_desired: Some(0.2), ..Default::default() },+ );+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.jidori = Some(4));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 1, "an indivisible jidori group must not be emergency-split");+ assert!((lines[0].end_x - lines[0].x0 - 48.0).abs() < 1e-6);+ assert_eq!(lines[0].range, 0..2);+ }+ }++ #[test]+ fn cjk_tsume_removes_sidebearings_without_collapsing_ink() {+ let (mut d, sid, _) = doc_with("HH", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let old = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.tsume = Some(1.0));+ let new = compose_story(&d, sid, &ComposeOptions::default());+ let a = &old.frames[0].lines[0];+ let b = &new.frames[0].lines[0];+ let g = &b.glyphs[0];+ let outline = designcraft_fonts::FontDb::global().outline(&g.face, g.gid);+ let ink_width = designcraft_geom::Shape::bounding_box(&*outline).width() * g.sx;+ assert!(ink_width > 0.0);+ assert!((b.end_x - b.x0 - 2.0 * ink_width).abs() < 1e-6);+ assert!(b.end_x < a.end_x);+ assert_eq!(a.glyphs[0].sx, g.sx);+ }++ #[test]+ fn cjk_composite_font_selects_entries_before_shaping() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "0123456789".into(), family: "Source Sans 3".into(), relative_size: 0.5, ..Default::default() },+ ],+ });+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = &cs.frames[0].lines[0];+ let a = line.glyphs.iter().find(|g| g.byte == 0).unwrap();+ let n = line.glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert_ne!(a.face.id(), n.face.id());+ assert_eq!(cs.styles[a.style as usize].size, 12.0);+ assert_eq!(cs.styles[n.style as usize].size, 6.0);+ assert!(!cs.styles.iter().any(|s| s.missing_font));+ }++ #[test]+ fn cjk_bunri_does_not_split_double_dash() {+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {+ let (d, sid, _) =+ doc_with("--", Rect::new(0.0, 0.0, 5.0, 100.0), ParaAttrs { composer: Some(composer), bunri_kinshi: Some(true), ..Default::default() });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ }+ }++ #[test]+ fn cjk_custom_kinsoku_disables_selected_breaks() {+ let (mut d, sid, _) = doc_with(+ "甲乙丙丁",+ Rect::new(0.0, 0.0, 25.0, 200.0),+ ParaAttrs {+ composer: Some(designcraft_doc::Composer::SingleLine),+ kinsoku: Some(Some(designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: "乙丙丁".into(), ..Default::default() })),+ ..Default::default()+ },+ );+ d.story_mut(sid).unwrap().format_chars(0.."甲乙丙丁".len(), |f| f.over.size = Some(12.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ }++ #[test]+ fn cjk_center_leading_measures_em_centers_across_different_sizes() {+ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {+ f.over.leading = Some(designcraft_doc::Leading::Points(30.0));+ f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::Center);+ });+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ let center = |l: &Line| {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ l.baseline + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy+ };+ assert!((center(lines[1]) - center(lines[0]) - 30.0).abs() < 1e-6);+ assert!((lines[1].baseline - lines[0].baseline - 30.0).abs() > 0.1);+ }++ #[test]+ fn cjk_em_center_alignment_moves_small_characters() {+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ d.story_mut(sid).unwrap().format_chars(1..2, |f| f.over.character_alignment = Some(designcraft_doc::cjk::CharacterAlignment::EmCenter));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = &cs.frames[0].lines[0];+ let center = |g: &PlacedGlyph| {+ let (a, b) = g.face.vertical_metrics();+ g.y + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy+ };+ assert!((center(&line.glyphs[0]) - center(&line.glyphs[1])).abs() < 1e-6);+ }++ #[test]+ fn cjk_hanging_punctuation_uses_frame_edge_without_changing_glyph_size() {+ let k = designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: ",".into(), hanging: ",".into(), ..Default::default() };+ let (mut d, sid, fid) = doc_with(+ "AB,",+ Rect::new(0.0, 0.0, 300.0, 100.0),+ ParaAttrs {+ composer: Some(designcraft_doc::Composer::SingleLine),+ kinsoku: Some(Some(k)),+ kinsoku_hang: Some(designcraft_doc::cjk::KinsokuHang::Regular),+ ..Default::default()+ },+ );+ let initial = compose_story(&d, sid, &ComposeOptions::default());+ let line = &initial.frames[0].lines[0];+ let text_w = line.glyphs.iter().take(2).map(|g| g.adv).sum::<f64>();+ // A fresh frame whose measure fits the letters, but not the comma.+ let frame = d.item_mut(fid).unwrap();+ frame.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, text_w + 1.0, 100.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ assert_eq!(cs.frames[0].lines[0].glyphs.last().unwrap().sx, line.glyphs.last().unwrap().sx);+ }++ #[test]+ fn cjk_fullwidth_space_obeys_the_paragraph_spacing_switch() {+ let text = "A B";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 300.0, 100.0),+ ParaAttrs { word_space_desired: Some(2.0), treat_ideographic_space_as_space: Some(false), ..Default::default() },+ );+ let fixed = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().paras[0].para.treat_ideographic_space_as_space = Some(true);+ let elastic = compose_story(&d, sid, &ComposeOptions::default());+ let space = fixed.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap().adv;+ assert!((elastic.frames[0].lines[0].end_x - fixed.frames[0].lines[0].end_x - space).abs() < 1e-6);+ }++ #[test]+ fn arabic_bidi_keeps_paragraph_context_across_forced_lines() {+ let text = "مرحبا\u{2028}123 - 456";+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ let mut gs: Vec<_> = lines[1].glyphs.iter().filter(|g| g.len > 0).collect();+ gs.sort_by(|a, b| a.x.total_cmp(&b.x));+ let actual: String = gs.iter().map(|g| text[g.byte..].chars().next().unwrap()).collect();+ let info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));+ let start = text.find('1').unwrap();+ let expected = info.reorder_line(&info.paragraphs[0], start..text.len()).to_string();+ assert_eq!(actual, expected);+ assert_ne!(actual, "123 - 456", "the previous Arabic strong character affects number ordering");+ }++ #[test]+ fn arabic_character_direction_override_survives_line_layout() {+ let text = "abc 123 def";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(4..7, |f| f.over.character_direction = Some(designcraft_doc::arabic::CharacterDirection::RightToLeft));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&cs)[0];+ let x = |byte| line.glyphs.iter().find(|g| g.byte == byte).unwrap().x;+ assert!(x(4) > x(5) && x(5) > x(6));+ assert!(x(0) < x(6) && x(4) < x(8));+ }++ #[test]+ fn arabic_fallback_marks_stay_with_bases_and_custom_offsets_move_only_marks() {+ let db = designcraft_fonts::FontDb::global();+ let Some(face) = db.fallback_for('ب', db.face(designcraft_fonts::DEFAULT_FAMILY, "Regular").id(), None) else { return };+ if !face.covers('ُ') {+ return;+ }+ let text = "بُبَ";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert!(plain.iter().all(|g| g.face.id() == face.id()), "fallback must not split Arabic marks into the Latin face");+ assert!(plain.iter().all(|g| g.gid != 0));+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.diacritic_x_offset = Some(200.0);+ f.over.diacritic_y_offset = Some(-100.0);+ });+ let shifted = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ let mut marks = 0;+ for (a, b) in plain.iter().zip(&shifted) {+ assert_eq!(a.gid, b.gid);+ assert_eq!(a.adv, b.adv);+ if face.glyph_is_mark(a.gid) {+ marks += 1;+ assert!((b.x - a.x - 2.4).abs() < 1e-6);+ assert!((b.y - a.y - 1.2).abs() < 1e-6);+ } else {+ assert!((a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6);+ }+ }+ assert!(marks > 0);+ }++ #[test]+ fn arabic_joining_context_crosses_character_style_boundaries() {+ let text = "ببب";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ if plain.iter().any(|g| g.gid == 0) {+ return;+ }+ d.story_mut(sid).unwrap().format_chars(2..4, |f| f.over.fill = Some("Paper".into()));+ let split = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert_eq!(plain.iter().map(|g| (g.byte, g.gid)).collect::<Vec<_>>(), split.iter().map(|g| (g.byte, g.gid)).collect::<Vec<_>>());+ }++ #[test]+ fn arabic_character_kashida_switch_prevents_insertion() {+ let text = "بسم الله الرحمن الرحيم الحمد لله رب العالمين";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 160.0, 300.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::RightJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.allow_kashidas = Some(false));+ let off = compose_story(&d, sid, &ComposeOptions::default());+ assert!(all_lines(&off).iter().all(|l| l.glyphs.iter().all(|g| g.len > 0 || g.face.glyph_for('\u{0640}') != g.gid)));+ }++ #[test]+ fn arabic_indic_digit_conversion_retains_original_utf8_ranges() {+ let text = "١٢٣";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.digits = Some(designcraft_doc::Digits::Arabic));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ assert_eq!(gs.iter().map(|g| (g.byte, g.len)).collect::<Vec<_>>(), [(0, 2), (2, 2), (4, 2)]);+ for (g, c) in gs.iter().zip("123".chars()) {+ assert_eq!(g.gid, g.face.glyph_for(c));+ }+ }++ #[test]+ fn arabic_contextual_digits_follow_strong_text_across_style_changes() {+ let text = "ب 12 A 34";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let arabic_digits = text.find('1').unwrap();+ d.story_mut(sid).unwrap().format_chars(arabic_digits..arabic_digits + 2, |f| f.over.fill = Some("Paper".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ let g = gs.iter().find(|g| g.byte == arabic_digits).unwrap();+ assert_eq!(g.gid, g.face.glyph_for('١'));+ let g = gs.iter().find(|g| g.byte == text.find('3').unwrap()).unwrap();+ assert_eq!(g.gid, g.face.glyph_for('3'));+ }++ #[test]+ fn arabic_story_direction_flows_right_column_first() {+ let text = format!("first{}second", designcraft_doc::story::COLUMN_BREAK);+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ assert!(lines[0].x0 > lines[1].x0);+ assert!(cs.frames[0].columns[0].x0 > cs.frames[0].columns[1].x0);+ }++ #[test]+ fn arabic_rtl_table_keeps_logical_indices_and_merged_cell_hit_testing() {+ let mut t = designcraft_doc::Table::new(987, 2, 3, 0, 0, 240.0);+ t.options.direction = designcraft_doc::TextDirection::RightToLeft;+ t.cell_mut(0, 0).unwrap().text = designcraft_doc::Story::with_text(StoryId(0), "Right", ParaFormat::default());+ t.cell_mut(0, 2).unwrap().text = designcraft_doc::Story::with_text(StoryId(0), "Left", ParaFormat::default());+ t.merge(designcraft_doc::CellRange::new(1, 0, 1, 1)).unwrap();+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 400.0), t);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let (_, _, right) = table::find_cell(&cs, 987, 0, 0).unwrap();+ let (_, _, left) = table::find_cell(&cs, 987, 0, 2).unwrap();+ assert!(right.rect.x0 > left.rect.x0);+ let (_, _, merged) = table::find_cell(&cs, 987, 1, 0).unwrap();+ assert!((merged.rect.width() - 160.0).abs() < 1e-6);+ assert_eq!(table::hit_cell(&cs, 0, right.rect.center()).map(|(_, r, c, _)| (r, c)), Some((0, 0)));+ }++ #[test]+ fn arabic_kashida_moves_marks_with_their_cluster_and_respects_nonjoiners() {+ let text = "بُسْمِ بُسْمِ";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 180.0, 100.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ let with = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ if with.iter().any(|g| g.gid == 0) {+ return;+ }+ assert!(with.iter().any(|g| g.len == 0 && g.gid == g.face.glyph_for('\u{0640}')));+ d.story_mut(sid).unwrap().paras[0].para.kashidas = Some(false);+ let without = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ for (a, b) in with.iter().zip(&without) {+ assert_eq!((a.gid, a.byte), (b.gid, b.byte));+ let first_a = with.iter().find(|g| g.byte == a.byte).unwrap();+ let first_b = without.iter().find(|g| g.byte == b.byte).unwrap();+ assert!(((a.x - first_a.x) - (b.x - first_b.x)).abs() < 1e-6, "marks detached from their cluster");+ }+ let text = "ب\u{200C}ب ب\u{200C}ب";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 180.0, 100.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs.iter().all(|g| g.gid != g.face.glyph_for('\u{0640}') || g.len > 0));+ }++ #[test]+ fn arabic_explicit_isolated_forms_disable_contextual_joining() {+ let text = "بب";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 180.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.positional_form = Some("Isolated".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ for g in gs {+ assert_eq!(g.gid, g.face.glyph_for('ب'));+ }+ }++ #[test]+ fn arabic_character_overrides_mirror_brackets_using_final_levels() {+ use designcraft_doc::arabic::CharacterDirection as D;+ for (text, direction, mirrored) in [("(123)", D::RightToLeft, true), ("(ب)", D::LeftToRight, false)] {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.character_direction = Some(direction));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ for (byte, ch) in [(0, '('), (text.len() - 1, ')')] {+ let g = gs.iter().find(|g| g.byte == byte).unwrap();+ let expected = if mirrored { unicode_bidi_mirroring::get_mirrored(ch).unwrap() } else { ch };+ assert_eq!(g.gid, g.face.glyph_for(expected), "{text:?} {direction:?} byte {byte}");+ }+ }+ }++ #[test]+ fn language_picks_localized_forms_through_the_word_cache() {+ // Source Serif 4 has a Turkish `locl` form of `i`; the same words in English and Turkish+ // (both shaped word by word through the cache) keep their own forms.+ let text = "in in in in";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 500.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(6..text.len(), |f| f.over.language = Some("Turkish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gid_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.gid).unwrap();+ assert_eq!(gid_at(0), gid_at(3), "English i");+ assert_eq!(gid_at(6), gid_at(9), "Turkish i");+ assert_ne!(gid_at(0), gid_at(6), "Turkish i takes its localized form");+ // A single word is shaped directly, in its language too.+ let (mut d, sid, _) = doc_with("i", Rect::new(36.0, 36.0, 500.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.language = Some("Turkish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs)[0].glyphs[0].gid, gid_at(6), "Turkish i, shaped on its own");+ }++ #[test]+ fn chinese_and_japanese_take_their_localized_forms() {+ // Noto Sans CJK SC (craft-fonts) draws 直 differently for Japanese (`locl`).+ let Some(noto) = designcraft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC") else { return };+ FontDb::global().add_font(noto.bytes.to_vec());+ let gid = |language: &str| {+ let (mut d, sid, _) = doc_with("直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0.."直".len(), |f| {+ f.over.font_family = Some(noto.family.into());+ f.over.language = Some(language.into());+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let g = &all_lines(&cs)[0].glyphs[0];+ assert_eq!(g.face.family, noto.family);+ g.gid+ };+ let chinese = gid("Chinese: Simplified");+ assert_eq!(chinese, FontDb::global().face(noto.family, noto.style).glyph_for('直'));+ assert_ne!(gid("Japanese"), chinese, "Japanese 直");+ }++ #[test]+ fn cjk_fallback_follows_the_language() {+ use designcraft_fonts::testing::font_with;+ // Stand-ins for Hiragino Mincho ProN (the Japanese chain's first system font) and Songti SC+ // (first in the Simplified Chinese chain); the real ones when installed.+ let db = designcraft_fonts::FontDb::global();+ db.add_font(font_with("Hiragino Mincho ProN", &['直']).unwrap());+ db.add_font(font_with("Songti SC", &['直']).unwrap());+ // (face of the Latin letter, face of the ideograph)+ let faces_of = |language: &str| {+ let (mut d, sid, _) = doc_with("a直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.language = Some(language.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let face_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.face).unwrap();+ (face_at(0), face_at(1))+ };+ assert_eq!(faces_of("Chinese: Simplified").1.family, "Songti SC");+ // Japanese: the craft-fonts faces lead the chain (Mincho first), then the system fonts.+ let japanese = designcraft_fonts::japanese_document_fonts().first().map_or("Hiragino Mincho ProN", |f| f.family);+ assert_eq!(faces_of("Japanese").1.family, japanese);+ // Without a CJK language, the language-blind search.+ let (primary, han) = faces_of("English: USA");+ assert_eq!(Some(han.family.clone()), db.fallback_for('直', primary.id(), None).map(|f| f.family.clone()));+ }++ #[test]+ fn missing_glyphs_are_the_fonts_box_unless_fallback_is_on() {+ use designcraft_fonts::testing::font_with;+ // Some font draws 語 when fallback fonts are allowed (a system CJK font, or this stand-in).+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Missing Glyph Helper", &['語']).unwrap());+ let text = "a語";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.language = Some("Japanese".into()));+ let glyph_at = |d: &Document, byte: usize| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| (g.face, g.gid, g.adv)).unwrap()+ };+ assert!(!d.settings.glyph_fallback, "new documents draw missing glyphs as InDesign does");+ let (face, gid, adv) = glyph_at(&d, 1);+ assert_eq!((face.family.as_str(), gid), (designcraft_fonts::DEFAULT_FAMILY, 0), "Source Serif 4's .notdef");+ assert!((adv - face.advance(0) * 12.0 / face.upem).abs() < 1e-6, "its advance: {adv}");+ d.settings.glyph_fallback = true;+ let (face, gid, _) = glyph_at(&d, 1);+ assert_ne!(face.family, designcraft_fonts::DEFAULT_FAMILY);+ assert_ne!(gid, 0, "a fallback font draws it");+ }++ #[test]+ fn kenten_missing_from_the_font_are_its_box_unless_fallback_is_on() {+ use designcraft_fonts::testing::font_with;+ // Some font draws the sesame dot when fallback fonts are allowed (a system font, or this one).+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Kenten Helper", &['\u{FE45}']).unwrap());+ let (mut d, sid, _) = doc_with("ab", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.kenten = Some(true));+ let marks = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs[plain..].iter().map(|g| (g.face.family.clone(), g.gid)).collect::<Vec<_>>()+ };+ let missing = marks(&d);+ assert_eq!(missing.len(), 2);+ assert!(missing.iter().all(|(family, gid)| family == designcraft_fonts::DEFAULT_FAMILY && *gid == 0), "{missing:?}");+ d.settings.glyph_fallback = true;+ let drawn = marks(&d);+ assert_eq!(drawn.len(), 2);+ assert!(drawn.iter().all(|(family, gid)| family != designcraft_fonts::DEFAULT_FAMILY && *gid != 0), "{drawn:?}");+ }++ #[test]+ fn each_document_shapes_words_in_its_own_fonts() {+ use designcraft_fonts::testing::font_with_glyph;+ const FAMILY: &str = "DocFont Word Cache";+ // Two documents' fonts of one name: the same words, drawn as `X` in one and `O` in the other.+ let root = std::env::temp_dir().join(format!("dc-compose-docfonts-{}", std::process::id()));+ let mut scopes = Vec::new();+ for (name, glyph) in [("x", 'X'), ("o", 'O')] {+ let folder = root.join(name);+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("word.ttf"), font_with_glyph(FAMILY, &['a', 'b', ' '], glyph).unwrap()).unwrap();+ scopes.push((designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope, glyph));+ }+ let text = "ab ab ab ab";+ let mut faces = Vec::new();+ for (scope, glyph) in scopes {+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.font_scope = scope;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyphs: Vec<&PlacedGlyph> =+ all_lines(&cs).into_iter().flat_map(|l| l.glyphs.iter()).filter(|g| text[g.byte..].starts_with('a')).collect();+ assert_eq!(glyphs.len(), 4);+ let face = glyphs[0].face;+ let drawn = designcraft_fonts::FontDb::global().face(designcraft_fonts::FALLBACK_FAMILY, "Regular").glyph_for(glyph);+ assert!(glyphs.iter().all(|g| g.face == face && g.gid == drawn), "scope {scope}: {glyph}");+ faces.push(face);+ }+ assert!(faces[0] != faces[1] && faces.iter().all(|f| f.family == FAMILY));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn composite_fonts_draw_from_the_documents_fonts() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ use designcraft_fonts::testing::font_with_glyph;+ const FAMILY: &str = "DocFont Composite Member";+ // A composite font whose digits come from a font only the document has.+ let folder = std::env::temp_dir().join(format!("dc-compose-composite-docfont-{}", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("digits.ttf"), font_with_glyph(FAMILY, &['1'], 'X').unwrap()).unwrap();+ let scope = FontDb::global().load_document_fonts(&folder).scope;+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.font_scope = scope;+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: designcraft_fonts::DEFAULT_FAMILY.into(), ..Default::default() },+ CompositeFontEntry { characters: "0123456789".into(), family: FAMILY.into(), ..Default::default() },+ ],+ });+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let digit = cs.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert_eq!(digit.face.family, FAMILY);+ assert_ne!(digit.gid, 0);+ assert!(!cs.styles.iter().any(|s| s.missing_font), "the document's font isn't missing");+ let _ = std::fs::remove_dir_all(&folder);+ }++ const KO_WORDS: &str = "한국어 문장은 띄어쓰기 단위로 줄을 바꿉니다 한국어 문장은 띄어쓰기 단위로 줄을 바꿉니다";+ const KO_HANJA: &str = "大韓民國 憲法은 國民의 權利를 保障한다 大韓民國 憲法은 國民의 權利를 保障한다";+ const KO_PUNCT: &str = "가나다라마。바사아자차」카타파하가、나다라마바。사아자차카」타파하가나、다라마바사。아자차카타」파하가나다、";+ /// Syllables for words wider than the frame.+ const KO_LONG: &str = "가나다라마바사아자차카타파하」";++ /// A Korean paragraph in a narrow frame (70 pt), set in a stand-in font covering the samples.+ fn korean_doc(text: &str, language: &str, para: ParaAttrs) -> (Document, StoryId) {+ let chars: Vec<char> = [KO_WORDS, KO_HANJA, KO_PUNCT, KO_LONG].concat().chars().collect();+ let font = designcraft_fonts::testing::font_with("DC Test Korean", &chars).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 106.0, 400.0), para);+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some("DC Test Korean".into());+ f.over.language = Some(language.into());+ });+ (d, sid)+ }++ /// The lines (after the first) that start inside a space-separated word.+ fn lines_starting_mid_word(d: &Document, sid: StoryId, text: &str) -> Vec<String> {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 2, "wraps: {} lines", lines.len());+ lines.iter().skip(1).filter(|l| !text[..l.range.start].ends_with(' ')).map(|l| text[l.range.clone()].to_string()).collect()+ }++ #[test]+ fn korean_breaks_at_spaces() {+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), ..Default::default() };+ // By script: Hangul is set word by word whatever the language.+ for language in ["Korean", "English: USA"] {+ let (d, sid) = korean_doc(KO_WORDS, language, para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_WORDS);+ assert!(mid.is_empty(), "{composer:?} {align:?} {language}: {mid:?}");+ }+ }+ }+ }++ #[test]+ fn korean_breaks_at_spaces_under_a_kinsoku_set() {+ let set = designcraft_doc::cjk::Kinsoku::named("KoreanKinsoku");+ assert!(set.is_some());+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ let para = ParaAttrs { composer: Some(composer), kinsoku: Some(set.clone()), ..Default::default() };+ let (d, sid) = korean_doc(KO_WORDS, "Korean", para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_WORDS);+ assert!(mid.is_empty(), "{composer:?}: {mid:?}");+ let (d, sid) = korean_doc(KO_WORDS, "Korean", ParaAttrs { korean_char_breaks: Some(true), ..para });+ assert!(!lines_starting_mid_word(&d, sid, KO_WORDS).is_empty(), "{composer:?}: breaks between syllables on request");+ }+ }++ #[test]+ fn korean_character_breaks_on_request() {+ let para = ParaAttrs { korean_char_breaks: Some(true), composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_WORDS, "Korean", para);+ assert!(!lines_starting_mid_word(&d, sid, KO_WORDS).is_empty(), "breaks between syllables");+ }++ #[test]+ fn korean_by_its_locale_code_breaks_at_spaces() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_HANJA, "ko_KR", para);+ let mid = lines_starting_mid_word(&d, sid, KO_HANJA);+ assert!(mid.is_empty(), "{mid:?}");+ }++ #[test]+ fn hanja_in_korean_text_breaks_at_spaces() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_HANJA, "Korean", para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_HANJA);+ assert!(mid.is_empty(), "{mid:?}");+ // Han in Japanese text breaks between characters.+ let (d, sid) = korean_doc(KO_HANJA, "Japanese", para);+ assert!(!lines_starting_mid_word(&d, sid, KO_HANJA).is_empty());+ }++ #[test]+ fn korean_lines_keep_kinsoku() {+ // Words of 9 to 14 syllables and a closing bracket: in one of them the bracket is what+ // overflows the frame.+ let syllables: Vec<char> = KO_LONG.chars().collect();+ let long = (9..=14).map(|n| format!("{}」 가나", syllables[..n].iter().collect::<String>()));+ for text in std::iter::once(KO_PUNCT.to_string()).chain(long) {+ let text = text.as_str();+ for char_breaks in [false, true] {+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ let para = ParaAttrs { korean_char_breaks: Some(char_breaks), composer: Some(composer), ..Default::default() };+ let (d, sid) = korean_doc(text, "Korean", para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 1, "wraps");+ let texts: Vec<&str> = lines.iter().map(|l| &text[l.range.clone()]).collect();+ assert!(texts.iter().all(|t| !t.starts_with(['、', '。', '」'])), "kinsoku ({char_breaks}, {composer:?}): {texts:?}");+ }+ }+ }+ }++ /// A synthetic font for vertical text: Source Sans 3 glyphs (CJK characters drawn as Latin ones)+ /// with vertical metrics, every glyph one em down the line and 120 units below its vertical+ /// origin, except ヸ (drawn as O): 1.024 em. No vertical forms. Added to the global database once.+ fn vertical_test_font() -> &'static str {+ use designcraft_fonts::testing::{font_mapping, with_vmtx};+ const FAMILY: &str = "DC Test Vertical";+ static ADDED: std::sync::Once = std::sync::Once::new();+ ADDED.call_once(|| {+ let glyphs = [('一', 'X'), ('二', 'X'), ('日', 'X'), ('本', 'X'), ('ま', 'o'), ('ヸ', 'O'), ('、', ','), ('A', 'A'), ('b', 'b')];+ let base = font_mapping(FAMILY, &glyphs).unwrap();+ let scratch = designcraft_fonts::FontDb::with_font_dirs(vec![]);+ scratch.add_font(base.clone());+ let wi = u16::try_from(scratch.face(FAMILY, "Regular").glyph_for('ヸ')).unwrap();+ designcraft_fonts::FontDb::global().add_font(with_vmtx(&base, (1000, 120), &[(wi, 1024, 100)]).unwrap());+ });+ FAMILY+ }++ /// Shippori Mincho (vertical forms, `vpal`) when built with craft-fonts; else `None`, with a note.+ fn shippori() -> Option<&'static str> {+ if !designcraft_fonts::japanese_fonts().any(|f| f.family == "Shippori Mincho") {+ eprintln!("skipped Shippori Mincho: built without craft-fonts (set CRAFT_FONTS_DIR to a checkout)");+ return None;+ }+ Some("Shippori Mincho")+ }++ /// The fonts vertical layout is checked in: the synthetic one, and Shippori Mincho with craft-fonts.+ fn vertical_families() -> Vec<&'static str> {+ std::iter::once(vertical_test_font()).chain(shippori()).collect()+ }++ /// A vertical frame (no inset) with `text` in `family` at 20 pt (and `over`), and its first line+ /// with the frame's first column.+ fn vertical_line(family: &str, text: &str, over: impl Fn(&mut designcraft_doc::CharFormat)) -> (Line, Rect) {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 500.0), lid, text, ParaFormat::default()).unwrap();+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {+ tf.options.inset = [0.0; 4];+ }+ d.story_mut(sid).unwrap().vertical = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some(family.into());+ f.over.size = Some(20.0);+ over(f);+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ assert!(ft.vertical);+ let line = ft.lines[0].clone();+ assert!(line.glyphs.iter().all(|g| g.face.family == family), "{family}: {:?}", line.glyphs.iter().map(|g| &g.face.family).collect::<Vec<_>>());+ (line, ft.columns[0])+ }++ /// Text-space bounds of a glyph's ink as drawn in a vertical frame.+ fn vertical_ink(g: &PlacedGlyph, baseline: f64) -> Rect {+ use designcraft_geom::{Affine, Shape};+ let ink = designcraft_fonts::FontDb::global().outline(&g.face, g.gid).bounding_box();+ let mut a = Affine::translate((g.x, baseline + g.y)) * Affine::scale_non_uniform(g.sx, g.sy);+ if let Some(turn) = g.vertical_xf(baseline) {+ a = turn * a;+ }+ a.transform_rect_bbox(ink)+ }++ /// The em box in text space: along the line from x (page down), across from its top (text -y,+ /// page right) to its bottom → (right, left, centre).+ fn em_across(l: &Line, g: &PlacedGlyph) -> (f64, f64, f64) {+ let (top, bottom) = g.face.em_box();+ let right = l.baseline + g.y - top * g.sy;+ let left = l.baseline + g.y - bottom * g.sy;+ (right, left, (right + left) / 2.0)+ }++ #[test]+ fn upright_glyphs_hang_on_the_line_centre() {+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "一", |_| {});+ let ichi = &l.glyphs[0];+ assert!(ichi.upright, "{family}");+ // An ideograph is centred across the line and inside its em along it.+ let (_, _, centre) = em_across(&l, ichi);+ let ink = vertical_ink(ichi, l.baseline);+ assert!(((ink.y0 + ink.y1) / 2.0 - centre).abs() < 0.05 * 20.0, "{family}: {ink:?} {centre}");+ assert!(ink.x0 > ichi.x && ink.x1 < ichi.x + ichi.adv, "{family}: {ink:?}");+ }+ // The synthetic glyph's top is its top side bearing (120 units) below its vertical origin.+ let (l, _) = vertical_line(vertical_test_font(), "一", |_| {});+ let ink = vertical_ink(&l.glyphs[0], l.baseline);+ assert!((ink.x0 - l.glyphs[0].x - 2.4).abs() < 1e-6, "{ink:?} {}", l.glyphs[0].x);+ }++ #[test]+ fn upright_punctuation_takes_its_vertical_form_and_place() {+ // A font with vertical forms: Shippori Mincho.+ let Some(family) = shippori() else { return };+ let (l, _) = vertical_line(family, "一、", |_| {});+ let comma = &l.glyphs[1];+ assert!(comma.upright);+ assert_ne!(comma.gid, comma.face.glyph_for('、'), "vertical form (vert)");+ let (right, _, centre) = em_across(&l, comma);+ // The comma's ink sits in the upper right quarter of its em box on the page.+ let ink = vertical_ink(comma, l.baseline);+ assert!(ink.x0 >= comma.x - 1e-6 && ink.x1 < comma.x + comma.adv / 2.0, "upper half: {ink:?} {} {}", comma.x, comma.adv);+ assert!(ink.y0 >= right - 1e-6 && ink.y1 < centre, "right half: {ink:?} {right} {centre}");+ }++ #[test]+ fn latin_in_vertical_text_turns_as_a_run() {+ // Shippori Mincho's `vrt2` has turned Latin forms; a turned run must not use them.+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "日本Ab", |_| {});+ let latin: Vec<_> = l.glyphs.iter().filter(|g| g.byte >= "日本".len()).collect();+ let face = latin[0].face;+ assert_eq!(latin.iter().map(|g| g.gid).collect::<Vec<_>>(), [face.glyph_for('A'), face.glyph_for('b')], "{family}");+ assert!(latin.iter().all(|g| !g.upright && g.vertical_xf(l.baseline).is_none()), "{family}");+ assert!((latin[0].adv - face.advance(latin[0].gid) * latin[0].sx).abs() < 1e-9, "{family}: horizontal advance");+ }+ }++ #[test]+ fn upright_glyphs_advance_by_their_vertical_metrics() {+ // ヸ is 1.024 em tall in both fonts.+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "一ヸ一", |_| {});+ let g = &l.glyphs;+ assert_eq!(g[1].face.v_advance(g[1].gid), 1024.0, "{family}");+ assert!((g[1].x - g[0].x - 20.0).abs() < 1e-9, "{family}");+ assert!((g[2].x - g[1].x - 20.48).abs() < 1e-9, "{family}: {} {}", g[1].x, g[2].x);+ }+ let Some(family) = shippori() else { return };+ // Shippori's ヸ is an em wide.+ let (l, _) = vertical_line(family, "ヸ", |_| {});+ assert_eq!(l.glyphs[0].face.advance(l.glyphs[0].gid), 1000.0);+ // Proportional vertical metrics (`vpal`): ま takes 0.974 em.+ let (l, _) = vertical_line(family, "まま", |f| f.over.otf_features = Some(vec!["vpal".into()]));+ assert!((l.glyphs[1].x - l.glyphs[0].x - 19.48).abs() < 1e-9, "{:?}", l.glyphs.iter().map(|g| g.x).collect::<Vec<_>>());+ let (l, _) = vertical_line(family, "まま", |_| {});+ assert!((l.glyphs[1].x - l.glyphs[0].x - 20.0).abs() < 1e-9);+ }++ #[test]+ fn vertical_lines_fit_the_em_box() {+ // First baseline at the ascent: an upright line's ascent is its em box top, so the em box+ // touches the frame's right edge. The synthetic font's em box is Source Sans 3's BASE one+ // (0.83 em, -0.17 em); Shippori Mincho's its OS/2 typo metrics (0.88 em, -0.12 em).+ let expected = [(vertical_test_font(), 16.6, 3.4)].into_iter().chain(shippori().map(|f| (f, 17.6, 2.4)));+ for (family, ascent, descent) in expected {+ let (l, col) = vertical_line(family, "一二", |_| {});+ assert!((l.ascent - ascent).abs() < 1e-9 && (l.descent - descent).abs() < 1e-9, "{family}: {} {}", l.ascent, l.descent);+ assert!((l.baseline - col.y0 - ascent).abs() < 1e-9, "{family}: {} {}", l.baseline, col.y0);+ }+ }diff --cc crates/format/src/lib.rsindex 72efe9e6d,f80ad0a65..b4a6f05ff--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@@ -88,15 -88,17 +89,17 @@@ fn load_zip(bytes: &[u8]) -> Result<Docf.read_to_end(&mut v).ok()?;Some(v)};- if let Some(meta) = read(&mut z, "meta.json")- && let Ok(m) = serde_json::from_slice::<Value>(&meta)- && let Some(v) = m.get("version").and_then(Value::as_u64)- && v as u32 > VERSION- {- return Err(FormatError::TooNew(v as u32));+ let version = read(&mut z, "meta.json")+ .and_then(|meta| serde_json::from_slice::<Value>(&meta).ok())+ .and_then(|m| m.get("version").and_then(Value::as_u64))+ .map_or(1, |v| u32::try_from(v).unwrap_or(u32::MAX));+ if version > VERSION {+ return Err(FormatError::TooNew(version));}let json = read(&mut z, "document.json").ok_or_else(|| FormatError::NotOurs("missing document.json".into()))?;- let mut doc: Document = serde_json::from_slice(&json).map_err(|e| FormatError::NotOurs(e.to_string()))?;+ let mut v: Value = serde_json::from_slice(&json).map_err(|e| FormatError::NotOurs(e.to_string()))?;- upgrade(&mut v);++ upgrade_json(&mut v);+ let mut doc: Document = serde_json::from_value(v).map_err(|e| FormatError::NotOurs(e.to_string()))?;let names: Vec<String> = z.file_names().map(str::to_string).collect();for name in names {let Some(stem) = name.strip_prefix("assets/") else { continue };@@@ -110,55 -111,9 +113,56 @@@Ok(doc)}+/// Bring a document saved in format `from` up to [`VERSION`].+fn upgrade(doc: &mut Document, from: u32) {+ if from < 2 {+ // Format 1 laid out an unset Keep Lines Together mode as all lines in paragraph, and drop+ // caps without Align Left Edge.+ pin_para_default(doc, |a| &mut a.keep_all_lines, true);+ pin_para_default(doc, |a| &mut a.drop_cap_align_left, false);+ }+}++/// Pin a paragraph attribute to the value an older format resolved it to where nothing set it:+/// at the start of each paragraph style chain that leaves it unset, and on paragraphs whose style+/// is missing.+fn pin_para_default<T: Clone>(doc: &mut Document, field: fn(&mut ParaAttrs) -> &mut Option<T>, old: T) {+ let unset = |a: &ParaAttrs| field(&mut a.clone()).is_none();+ let roots: std::collections::HashSet<String> = doc+ .styles+ .paragraph+ .iter()+ .filter_map(|s| {+ let chain = doc.styles.para_chain(&s.name);+ if chain.iter().all(|c| unset(&c.para)) { chain.first().map(|c| c.name.clone()) } else { None }+ })+ .collect();+ if !roots.is_empty() {+ for s in doc.styles_mut().paragraph.iter_mut().filter(|s| roots.contains(&s.name)) {+ *field(&mut s.para) = Some(old.clone());+ }+ }+ let styles = doc.styles.clone();+ let mut pin = |st: &mut Story| {+ for p in st.paras.iter_mut().filter(|p| styles.para(&p.style).is_none()) {+ let v = field(&mut p.para);+ if v.is_none() {+ *v = Some(old.clone());+ }+ }+ };+ for st in doc.stories.values_mut() {+ let st = Arc::make_mut(st);+ st.for_each_text_mut(&mut pin);+ for n in &mut st.endnotes {+ Arc::make_mut(n).text.for_each_text_mut(&mut pin);+ }+ }+}+fn load_legacy_json(bytes: &[u8]) -> Result<Document, FormatError> {- let v: Value = serde_json::from_slice(bytes).map_err(|e| FormatError::NotOurs(e.to_string()))?;+ let mut v: Value = serde_json::from_slice(bytes).map_err(|e| FormatError::NotOurs(e.to_string()))?;- upgrade(&mut v);++ upgrade_json(&mut v);let mut doc: Document = serde_json::from_value(v.clone()).map_err(|e| FormatError::NotOurs(e.to_string()))?;if let Some(data) = v.get("assetData").and_then(Value::as_object) {for (k, s) in data {@@@ -174,6 -128,54 +178,54 @@@Ok(doc)}+ /// Bring older documents' JSON up to the current model. Vertical Type was a text frame option+ /// (`content.options.vertical`); it is the story's direction, which a story takes from its first+ /// frame.-fn upgrade(doc: &mut Value) {++fn upgrade_json(doc: &mut Value) {+ let mut vertical = HashSet::new();+ vertical_frames(doc, &mut vertical, 0);+ if vertical.is_empty() {+ return;+ }+ let Some(stories) = doc.get_mut("stories").and_then(Value::as_object_mut) else { return };+ for st in stories.values_mut() {+ let first = st.get("frames").and_then(|f| f.get(0)).and_then(Value::as_u64);+ if let (Some(f), Some(st)) = (first, st.as_object_mut())+ && vertical.contains(&f)+ && !st.contains_key("vertical")+ {+ st.insert("vertical".into(), Value::Bool(true));+ }+ }+ }++ /// Ids of the text frames in `v` (any depth: groups, anchored objects) whose options say vertical.+ fn vertical_frames(v: &Value, out: &mut HashSet<u64>, depth: usize) {+ // serde_json already refuses JSON nested deeper than 128 levels.+ if depth > 256 {+ return;+ }+ match v {+ Value::Object(m) => {+ if let (Some(id), Some(c)) = (m.get("id").and_then(Value::as_u64), m.get("content"))+ && c.get("type").and_then(Value::as_str) == Some("text")+ && c.get("options").and_then(|o| o.get("vertical")).and_then(Value::as_bool) == Some(true)+ {+ out.insert(id);+ }+ for c in m.values() {+ vertical_frames(c, out, depth + 1);+ }+ }+ Value::Array(a) => {+ for c in a {+ vertical_frames(c, out, depth + 1);+ }+ }+ _ => {}+ }+ }+fn base64_decode(s: &str) -> Vec<u8> {let mut out = Vec::with_capacity(s.len() * 3 / 4);let (mut buf, mut bits) = (0u32, 0);@@@ -229,122 -231,62 +281,178 @@@ mod testsassert_eq!(back.stories, d.stories);}+ /// `doc` as format 1 wrote it.+ fn save_v1(doc: &Document) -> Vec<u8> {+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(br#"{"format": "designcraft", "version": 1}"#).unwrap();+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&serde_json::to_vec(doc).unwrap()).unwrap();+ z.finish().unwrap().into_inner()+ }++ fn para_style(name: &str, based_on: Option<&str>, keep_all_lines: Option<bool>) -> designcraft_doc::ParagraphStyle {+ designcraft_doc::ParagraphStyle {+ name: name.into(),+ based_on: based_on.map(str::to_string),+ next_style: None,+ para: designcraft_doc::ParaAttrs { keep_lines_together: Some(true), keep_all_lines, ..Default::default() },+ chars: Default::default(),+ shortcut: String::new(),+ }+ }++ /// Format 1 resolved an unset Keep Lines Together mode as all lines: those documents still+ /// do after loading, wherever the mode comes from. New documents keep lines at start/end.+ #[test]+ fn format_1_keep_lines_without_mode_stays_all_lines() {+ let mut d = Document::new(&NewDocument::default());+ let st = d.styles_mut();+ st.paragraph.push(para_style("Root", None, None));+ st.paragraph.push(para_style("Child", Some("Root"), None));+ st.paragraph.push(para_style("Explicit", None, Some(false)));+ st.paragraph.push(para_style("Under explicit", Some("Explicit"), None));+ st.paragraph.push(para_style("Loop A", Some("Loop B"), None));+ st.paragraph.push(para_style("Loop B", Some("Loop A"), None));+ let lid = d.default_layer();+ let names = [designcraft_doc::story::BASIC_PARAGRAPH, "Root", "Child", "Explicit", "Under explicit", "Loop A", "Loop B", "Missing"];+ let text = names.join("\n");+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, &text, ParaFormat::default()).unwrap();+ {+ let s = d.story_mut(sid).unwrap();+ for (p, name) in s.paras.iter_mut().zip(names) {+ p.style = name.into();+ p.para.keep_lines_together = Some(true);+ }+ s.insert_note(1, "Note", ParaFormat { style: "Missing".into(), ..Default::default() });+ }+ let back = load(&save_v1(&d)).unwrap();+ let resolve = |f: &ParaFormat| back.styles.resolve_para(f).0;+ let story = back.story(sid).unwrap();+ for (p, name) in story.paras.iter().zip(names) {+ let pp = resolve(p);+ assert!(pp.keep_lines_together);+ assert_eq!(pp.keep_all_lines, !name.contains("xplicit"), "{name}");+ }+ assert!(resolve(&story.notes[0].text.paras[0]).keep_all_lines, "footnote with a missing style");+ assert!(back.styles.resolve_para_style("Loop A").0.keep_all_lines && back.styles.resolve_para_style("Loop B").0.keep_all_lines);+ // Pinned where the chains start; explicit and inheriting styles are left as they were.+ assert_eq!(back.styles.para("Root").unwrap().para.keep_all_lines, Some(true));+ assert_eq!(back.styles.para("Child").unwrap().para.keep_all_lines, None);+ assert_eq!(back.styles.para("Under explicit").unwrap().para.keep_all_lines, None);+ // The current format keeps the new default: at start/end of paragraph.+ let now = load(&save(&d).unwrap()).unwrap();+ let p = &now.story(sid).unwrap().paras[0];+ assert!(!now.styles.resolve_para(p).0.keep_all_lines);+ assert!(!designcraft_doc::ParaProps::default().keep_all_lines);+ }++ /// Format 1 wrote paragraph rules, text frame options and numbered lists in full, so their+ /// old defaults (black rules, auto-size from the top centre, lists continuing across stories)+ /// load as saved. New documents take InDesign's.+ #[test]+ fn format_1_rules_frames_and_lists_load_as_saved() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let old_rule = designcraft_doc::Rule { on: true, color: designcraft_doc::color::swatch::BLACK.into(), ..Default::default() };+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "Ruled", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(old_rule.clone());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.auto_size_ref = 1;+ d.settings.lists.push(designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: true });+ let back = load(&save_v1(&d)).unwrap();+ assert_eq!(back.story(sid).unwrap().paras[0].para.rule_above, Some(old_rule));+ assert_eq!(back.item(fid).unwrap().text_frame().unwrap().options.auto_size_ref, 1);+ assert!(back.settings.lists[0].continue_across_stories);+ assert_eq!(designcraft_doc::Rule::default().color, designcraft_doc::TEXT_COLOR);+ assert_eq!(designcraft_doc::TextFrameOptions::default().auto_size_ref, 4);+ assert!(!designcraft_doc::NumberedList::default().continue_across_stories);+ }++ /// Format 1 set drop caps without Align Left Edge: those documents still do where nothing set+ /// it. New documents align the drop cap's left edge.+ #[test]+ fn format_1_drop_caps_stay_unaligned() {+ let mut d = Document::new(&NewDocument::default());+ let st = d.styles_mut();+ st.paragraph.push(para_style("Opener", None, None));+ st.paragraph.push(designcraft_doc::ParagraphStyle {+ para: designcraft_doc::ParaAttrs { drop_cap_align_left: Some(true), ..Default::default() },+ ..para_style("Aligned", None, None)+ });+ let lid = d.default_layer();+ let (_, sid) =+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "One\nTwo\nThree", ParaFormat::default()).unwrap();+ {+ let s = d.story_mut(sid).unwrap();+ for (p, name) in s.paras.iter_mut().zip(["Opener", "Aligned", "Missing"]) {+ p.style = name.into();+ p.para.drop_cap_lines = Some(2);+ p.para.drop_cap_chars = Some(1);+ }+ }+ let back = load(&save_v1(&d)).unwrap();+ let aligned: Vec<bool> = back.story(sid).unwrap().paras.iter().map(|p| back.styles.resolve_para(p).0.drop_cap_align_left).collect();+ assert_eq!(aligned, [false, true, false]);+ let now = load(&save(&d).unwrap()).unwrap();+ assert!(now.styles.resolve_para(&now.story(sid).unwrap().paras[0]).0.drop_cap_align_left);+ }++ /// The object of the item `id` in a document's JSON.+ fn item_json(v: &mut Value, id: u64) -> Option<&mut Value> {+ if v.get("id").and_then(Value::as_u64) == Some(id) && v.get("content").is_some() {+ return Some(v);+ }+ match v {+ Value::Object(m) => m.values_mut().find_map(|c| item_json(c, id)),+ Value::Array(a) => a.iter_mut().find_map(|c| item_json(c, id)),+ _ => None,+ }+ }++ #[test]+ fn frame_level_vertical_text_opens_as_a_vertical_story() {+ // Documents that set Vertical on the frame: the story takes its first frame's direction.+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, "縦書き", ParaFormat::default()).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 72.0, 428.0, 400.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, b).unwrap();+ let (c, other) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(450.0, 72.0, 550.0, 400.0), lid, "横", ParaFormat::default()).unwrap();+ let mut v = serde_json::to_value(&d).unwrap();+ item_json(&mut v, a.0).unwrap()["content"]["options"]["vertical"] = json!(true);+ item_json(&mut v, c.0).unwrap()["content"]["options"]["vertical"] = json!(false);+ let json = serde_json::to_vec(&v).unwrap();+ let mut zipped = Cursor::new(Vec::new());+ {+ let mut z = zip::ZipWriter::new(&mut zipped);+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&json).unwrap();+ z.finish().unwrap();+ }+ for bytes in [json.clone(), zipped.into_inner()] {+ let back = load(&bytes).unwrap();+ assert!(back.stories[&sid].vertical);+ assert!(!back.stories[&other].vertical);+ // Saved again, the direction is the story's.+ let again = load(&save(&back).unwrap()).unwrap();+ assert!(again.stories[&sid].vertical && !again.stories[&other].vertical);+ }+ }++ #[test]+ fn documents_saved_before_glyph_fallback_keep_their_fallback_fonts() {+ let d = Document::new(&NewDocument::default());+ assert!(!d.settings.glyph_fallback);+ assert!(!load(&save(&d).unwrap()).unwrap().settings.glyph_fallback, "saved and read as off");+ let mut on = d.clone();+ on.settings.glyph_fallback = true;+ assert!(load(&save(&on).unwrap()).unwrap().settings.glyph_fallback);+ // Written before the setting existed: drawn from fallback fonts, as they were.+ let mut v = serde_json::to_value(&d).unwrap();+ v["settings"].as_object_mut().unwrap().remove("glyphFallback").unwrap();+ assert!(load(&serde_json::to_vec(&v).unwrap()).unwrap().settings.glyph_fallback);+ }+#[test]fn rejects_garbage_and_newer_versions() {assert!(load(b"nope").is_err());diff --cc crates/idml/src/import.rsindex c96d858f7,3c8824490..e51f1d81b--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -1950,10 -2042,7 +2059,9 @@@ impl<'r> Importer<'r>sid}};- let mut options = e.find("TextFramePreference").map(text_frame_options).unwrap_or_default();+ // Options the frame doesn't set come from its object style chain.+ let prefs: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).filter_map(|s| s.find("TextFramePreference")).collect();+ let mut options = text_frame_options(&prefs);- options.vertical = self.vertical_stories.contains(&story);if let Some(g) = e.find("BaselineFrameGridOption")&& g.get("UseCustomBaselineFrameGrid") == Some("true"){@@@ -2265,15 -2353,8 +2374,10 @@@ fn text_frame_options(prefs: &[&El]) -o.column_width = v;}o.balance_columns = e.get("VerticalBalanceColumns") == Some("true");- if let Some(p) = prefs.iter().find(|p| p.prop("InsetSpacing").is_some()) {- if let Some(l) = p.prop_el("InsetSpacing") {- let v: Vec<f64> = l.find_all("ListItem").filter_map(|i| i.text_content().trim().parse().ok()).collect();- if let [t, l, b, r] = v[..] {- o.inset = [t, l, b, r];- }- } else if let Some(v) = p.num("InsetSpacing") {- o.inset = [v; 4];- }- if let Some(inset) = inset_spacing(e) {++ if let Some(p) = prefs.iter().find(|p| p.prop("InsetSpacing").is_some())++ && let Some(inset) = inset_spacing(p)++ {+ o.inset = inset;}if let Some(v) = e.get("VerticalJustification") {o.vertical_justification = names::vj_in(v);@@@ -2297,18 -2378,32 +2401,44 @@@o}+/// Attribute lookup over several elements: the first that has it.+struct Prefs<'a>(&'a [&'a El]);++impl Prefs<'_> {+ fn get(&self, k: &str) -> Option<&str> {+ self.0.iter().find_map(|e| e.get(k))+ }+ fn num(&self, k: &str) -> Option<f64> {+ self.get(k).and_then(|v| v.trim().parse().ok())+ }+}++ /// A scalar applies to every edge; a list is top, left, bottom, right. Keep the+ /// existing property-element precedence over the legacy scalar attribute, even+ /// when the property is malformed. Finite negative insets remain supported.+ fn inset_spacing(e: &El) -> Option<[f64; 4]> {+ let number = |s: &str| s.trim().parse::<f64>().ok().filter(|v| v.is_finite());+ let Some(property) = e.prop_el("InsetSpacing") else {+ return e.get("InsetSpacing").and_then(number).map(|v| [v; 4]);+ };+ let mut items = property.elements();+ if property.get("type") == Some("list") || property.find("ListItem").is_some() {+ let mut inset = [0.0; 4];+ for edge in &mut inset {+ let item = items.next()?;+ if item.local() != "ListItem" || item.elements().next().is_some() {+ return None;+ }+ *edge = number(&item.text_content())?;+ }+ items.next().is_none().then_some(inset)+ } else if items.next().is_none() {+ number(&property.text_content()).map(|v| [v; 4])+ } else {+ None+ }+ }+fn path_of(pg: &El) -> PathData {let mut subs = Vec::new();for g in pg.find_all("GeometryPathType") {diff --cc crates/idml/src/tests.rsindex e4289d8d3,b636a2ac1..6630ac1ad--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -938,138 -701,159 +1085,288 @@@ fn round_trips_frames_with_pasted_in_itfn vertical_story_orientation_round_trips() {let mut d = Document::new(&NewDocument::default());let lid = d.default_layer();- let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, "縦書き", ParaFormat::default()).unwrap();- d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical = true;+ let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, "縦書き", ParaFormat::default()).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 72.0, 428.0, 400.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, b).unwrap();+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(450.0, 72.0, 550.0, 400.0), lid, "横", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().vertical = true;+ // Orientation and column direction are separate settings of the story.+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ let back = import_idml(&export_idml(&d)).unwrap();+ use designcraft_doc::TextDirection::{LeftToRight, RightToLeft};+ let directions: Vec<_> = back.stories.values().map(|s| (s.frames.len(), s.vertical, s.direction)).collect();+ assert!(directions.contains(&(2, true, RightToLeft)) && directions.contains(&(1, false, LeftToRight)), "{directions:?}");+ let frames: Vec<bool> = back.spreads[0].items.iter().map(|i| back.frame_vertical(i)).collect();+ assert_eq!(frames, [true, true, false]);+ }++ #[test]+ fn cjk_character_attributes_import_from_independent_xml_and_round_trip() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" BunriKinshi="true" Rensuuji="false" TreatIdeographicSpaceAsSpace="true">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" LeadingAki="0.25" TrailingAki="-1" Tsume="20" Jidori="4" LeadingModel="LeadingModelCenter" CharacterAlignment="AlignEmCenter" KentenKind="KentenWhiteCircle"><Content>甲乙</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let doc = import_idml(&fixture_with_story(story)).unwrap();+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ let a = &st.runs().next().unwrap().1.over;+ assert_eq!(a.leading_aki, Some(Some(0.25)));+ assert_eq!(a.trailing_aki, Some(None));+ assert_eq!(a.jidori, Some(4));+ assert_eq!(a.tsume, Some(0.2));+ assert_eq!(a.kenten_character.as_deref(), Some("○"));+ assert_eq!(a.leading_model, Some(designcraft_doc::cjk::LeadingModel::Center));+ assert_eq!(st.paras[0].para.bunri_kinshi, Some(true));+ assert_eq!(st.paras[0].para.rensuuji, Some(false));+ let back = import_idml(&export_idml(&doc)).unwrap();+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ let b = &st2.runs().next().unwrap().1.over;+ assert_eq!(a.leading_aki, b.leading_aki);+ assert_eq!(a.trailing_aki, b.trailing_aki);+ assert_eq!(a.kenten_character, b.kenten_character);+ assert_eq!(a.leading_model, b.leading_model);+ }++ #[test]+ fn automatic_kerning_does_not_import_inactive_numeric_values() {+ for (attributes, expected) in [+ (r#"KerningMethod="$ID/Optical" KerningValue="1e+11""#, Some(designcraft_doc::Kerning::Optical)),+ (r#"KerningMethod="$ID/Metrics" KerningValue="0""#, Some(designcraft_doc::Kerning::Metrics)),+ (r#"KerningValue="-40""#, Some(designcraft_doc::Kerning::Manual(-40.0))),+ (r#"KerningValue="1e+11""#, None),+ ] {+ let story = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" {attributes}><Content>甲乙</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#+ );+ let d = import_idml(&fixture_with_story(&story)).unwrap();+ let s = d.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ assert_eq!(s.runs().next().unwrap().1.over.kerning, expected, "{attributes}");+ }+ }++ #[test]+ fn cjk_composite_fonts_and_custom_kinsoku_are_document_resources() {+ let map = DESIGNMAP.replace("</Document>", r#"+ <KinsokuTable Self="KinsokuTable/Test" Name="Test" CantBeginLineChars="乙" CantEndLineChars="甲" CantBeSeparatedChars="—" HangingPunctuationChars="。"/>+ <CompositeFont Self="CompositeFont/Mixed" Name="Mixed"><CompositeFontEntry Self="cf1" Name="Base" FontStyle="Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>+ <CompositeFontEntry Self="cf2" Name="Digits" CustomCharacters="0123456789" FontStyle="Regular" RelativeSize="80" BaselineShift="10"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry></CompositeFont>+ </Document>"#);+ let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange KinsokuSet=\"KinsokuTable/Test\" ");+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", STYLES),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", &story),+ ]);+ let d = import_idml(&bytes).unwrap();+ let f = &d.styles.composite_fonts[0];+ assert_eq!(f.entry('1').unwrap().family, "Source Sans 3");+ assert_eq!(f.entry('甲').unwrap().family, "Source Serif 4");+ assert_eq!(f.entry('1').unwrap().relative_size, 0.8);+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);+ assert!(+ back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.kinsoku.as_ref().and_then(Option::as_ref).is_some_and(|k| k.no_start == "乙"))+ );+ }++ #[test]+ fn cjk_unsupported_mojikumi_is_preserved_instead_of_silently_dropped() {+ let map = DESIGNMAP.replace("</Document>", r#"<MojikumiTable Self="MojikumiTable/Spacing" Name="Spacing" BasedOnMojikumiSet="SimpChineseDefault"><Properties><OverrideMojikumiAkiList>+ <OverrideMojikumiAkiType TargetMojikumiClass="1" SideMojikumiClass="23" SideIsAfterTarget="false" Minimum="-0.1" Desired="0.25" Maximum="0.5" CompressionPriority="3" AkiDoesNotFloat="true"/>+ </OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#);+ let story =+ STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"MojikumiTable/Spacing\" KinsokuType=\"KinsokuPushOutFirst\" ");+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", STYLES),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", &story),+ ]);+ let d = import_idml(&bytes).unwrap();+ let t = &d.styles.mojikumi_tables[0];+ assert_eq!(t.overrides[0].minimum, -0.1);+ assert!(t.overrides[0].does_not_float);+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);+ assert!(back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.mojikumi.as_deref() == Some("MojikumiTable/Spacing")));+ }++ #[test]+ fn arabic_controls_import_independent_xml_and_round_trip() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" ParagraphDirection="RightToLeftDirection" Kashidas="KashidasOff" ParagraphJustification="NaskhJustification" ParagraphKashidaWidth="2">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" CharacterDirection="LeftToRightDirection" Kashidas="KashidasOff" DiacriticPosition="OpentypePosition" XOffsetDiacritic="150" YOffsetDiacritic="-100" PositionalForm="Medial"><Properties><DigitsType type="enumeration">FarsiDigits</DigitsType></Properties><Content>بَ123</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let d = import_idml(&fixture_with_story(story)).unwrap();+ let st = d.stories.values().find(|s| s.text.contains('ب')).unwrap();+ assert_eq!(st.paras[0].para.kashidas, Some(false));+ assert_eq!(st.paras[0].para.arabic_justification.as_deref(), Some("NaskhJustification"));+ let a = &st.runs().next().unwrap().1.over;+ assert_eq!(a.character_direction, Some(designcraft_doc::arabic::CharacterDirection::LeftToRight));+ assert_eq!(a.allow_kashidas, Some(false));+ assert_eq!(a.diacritic_x_offset, Some(150.0));+ assert_eq!(a.diacritic_y_offset, Some(-100.0));+ assert_eq!(a.digits, Some(designcraft_doc::Digits::Farsi));+ let back = import_idml(&export_idml(&d)).unwrap();+ let b = back.stories.values().find(|s| s.text.contains('ب')).unwrap();+ let attrs = &b.runs().next().unwrap().1.over;+ assert_eq!(attrs.character_direction, a.character_direction);+ assert_eq!(attrs.diacritic_x_offset, a.diacritic_x_offset);+ assert_eq!(attrs.diacritic_y_offset, a.diacritic_y_offset);+ assert_eq!(attrs.allow_kashidas, a.allow_kashidas);+ assert_eq!(attrs.positional_form, a.positional_form);+ assert_eq!(b.paras[0].para.paragraph_kashida_width, Some(Some(2.0)));+ }++ #[test]+ fn arabic_story_and_table_directions_survive_idml_export() {+ let mut d = Document::new(&NewDocument::default());+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), d.default_layer(), "", ParaFormat::default()).unwrap();+ let st = d.story_mut(sid).unwrap();+ st.direction = designcraft_doc::TextDirection::RightToLeft;+ let mut t = designcraft_doc::Table::new(42, 1, 2, 0, 0, 200.0);+ t.options.direction = designcraft_doc::TextDirection::RightToLeft;+ st.insert_table(0, t);let back = import_idml(&export_idml(&d)).unwrap();- let frame = back.spreads[0].items.iter().find_map(|i| i.text_frame()).unwrap();- assert!(frame.options.vertical);+ let st = back.stories.values().find(|st| !st.tables.is_empty()).unwrap();+ assert_eq!(st.direction, designcraft_doc::TextDirection::RightToLeft);+ assert_eq!(st.tables.values().next().unwrap().options.direction, designcraft_doc::TextDirection::RightToLeft);}++#[test]+fn drop_caps_import_and_round_trip() {+ // A style with a drop cap, its character style and a nested style through it; a paragraph+ // overriding it locally.+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">+ <Properties><DropCapStyle type="object">CharacterStyle/Strong</DropCapStyle><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#;+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2" DropCapStyle="CharacterStyle/$ID/[No character style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#;+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", story),+ ]);+ let check = |d: &Document| {+ let st = d.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));+ let ns = st.para.nested_styles.clone().unwrap();+ assert_eq!((ns[0].style.as_str(), &ns[0].until), ("Strong", &designcraft_doc::NestedUntil::Dropcap));+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ };+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ check(&d);+ // The drop cap's character style isn't written to IDML (InDesign sets it through a Dropcap+ // nested style); Align Left Edge and Scale for Descenders are, as DropcapDetail.+ let mut d = d;+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.drop_cap_align_left = Some(false);+ s.para.drop_cap_scale_descenders = Some(true);+ }+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));+ let back = import_idml(&bytes).unwrap();+ let st = back.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), None));+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));+ assert_eq!(st.para.nested_styles.as_ref().map(|n| n[0].until.clone()), Some(designcraft_doc::NestedUntil::Dropcap));+}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}diff --cc crates/pdf/src/tests.rsindex 0fe8019b7,1771c4e4f..5e3dc61cc--- a/crates/pdf/src/tests.rs+++ b/crates/pdf/src/tests.rs@@@ -202,14 -202,138 +202,150 @@@ fn tables_export_cell_text()}}+#[test]+fn drop_cap_text_extracts_in_order() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let para = designcraft_doc::ParaAttrs { drop_cap_lines: Some(3), drop_cap_chars: Some(2), ..Default::default() };+ let text = "Drop caps read in order with the rest of the paragraph, which runs on for a few lines beside the enlarged letters.";+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 236.0, 300.0), lid, text, ParaFormat { para, ..Default::default() }).unwrap();+ let bytes = export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap();+ let flat: String = extract_text(&bytes)[0].split_whitespace().collect::<Vec<_>>().join(" ");+ assert!(flat.starts_with("Drop caps read in order"), "{flat}");+}+++ /// A 4×2 CMYK TIFF: the left half 100% K (text in a scan), the right half C0 M100 Y100 K0.+ fn cmyk_tiff() -> (Vec<u8>, Vec<u8>) {+ let (k, red) = ([0u8, 0, 0, 255], [0u8, 255, 255, 0]);+ let px: Vec<u8> = (0..2).flat_map(|_| [k, k, red, red]).flatten().collect();+ let mut b = Vec::new();+ tiff::encoder::TiffEncoder::new(std::io::Cursor::new(&mut b)).unwrap().write_image::<tiff::encoder::colortype::CMYK8>(4, 2, &px).unwrap();+ (b, px)+ }++ fn place(d: &mut Document, data: Vec<u8>, px: (u32, u32)) {+ let asset = designcraft_doc::AssetId(d.alloc());+ let mime = designcraft_images::mime(&data).into();+ d.assets.insert(+ asset,+ std::sync::Arc::new(designcraft_doc::Asset {+ id: asset,+ name: "scan.tif".into(),+ mime,+ link: None,+ data: data.into(),+ pixels: Some(px),+ page: 0,+ }),+ );+ let lid = d.default_layer();+ let id = ItemId(d.alloc());+ let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(72.0, 72.0, 272.0, 172.0)));+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {+ asset,+ size: (px.0 as f64, px.1 as f64),+ xf: designcraft_geom::Affine::translate((72.0, 72.0)) * designcraft_geom::Affine::scale(50.0),+ auto_fit: designcraft_doc::Fitting::FillProportionally,+ fit_align: 4,+ crop: [0.0; 4],+ });+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ }++ /// Every image XObject in a PDF: its /ColorSpace name (`?` when not a name) and decoded samples.+ fn image_xobjects(bytes: &[u8]) -> Vec<(String, Vec<u8>)> {+ use hayro_syntax::object::Name;+ let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse");+ pdf.objects()+ .into_iter()+ .filter_map(|o| o.into_stream())+ .filter(|s| s.dict().get::<Name>("Subtype").is_some_and(|n| n.as_str() == "Image"))+ .map(|s| {+ let cs = s.dict().get::<Name>("ColorSpace").map_or("?".to_string(), |n| n.as_str().to_string());+ (cs, s.decoded().expect("decode").into_owned())+ })+ .collect()+ }++ /// A placed CMYK TIFF went into PDFs as DeviceRGB (#35): 100% K became RGB black, which the+ /// press separates as four-colour black.+ #[test]+ fn cmyk_tiff_keeps_its_inks() {+ let (tif, px) = cmyk_tiff();+ let mut d = doc_with_text("x");+ place(&mut d, tif, (4, 2));+ for standard in [Standard::None, Standard::PdfX4] {+ let r = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { standard, ..Default::default() }).unwrap();+ assert!(r.warnings.is_empty(), "{standard:?}: {:?}", r.warnings);+ let images = image_xobjects(&r.bytes);+ assert_eq!(images, vec![("DeviceCMYK".to_string(), px.clone())], "{standard:?}");+ assert_eq!(images[0].1[..4], [0, 0, 0, 255], "K only");+ }+ }++ /// What a page draws: each glyph (its text and outline bounds) and each filled path's bounds.+ fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>) {+ use hayro_interpret::font::Glyph;+ use hayro_interpret::{+ BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,+ interpret_page,+ };+ use kurbo::Shape as _;+ #[derive(Default)]+ struct Rec(Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>);+ impl Device<'_> for Rec {+ fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}+ fn set_blend_mode(&mut self, _: BlendMode) {}+ fn draw_path(&mut self, p: &kurbo::BezPath, xf: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {+ self.1.push((xf * p.clone()).bounding_box());+ }+ fn push_clip_path(&mut self, _: &ClipPath) {}+ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}+ fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {+ let text = match g.as_unicode() {+ Some(hayro_cmap::BfString::Char(c)) => c.to_string(),+ Some(hayro_cmap::BfString::String(s)) => s,+ None => String::new(),+ };+ let bounds = match g {+ Glyph::Outline(o) => o.outline().bounding_box(),+ Glyph::Type3(_) => kurbo::Rect::ZERO,+ };+ self.0.push((text, bounds));+ }+ fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {}+ fn pop_clip_path(&mut self) {}+ fn pop_transparency_group(&mut self) {}+ }+ let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse");+ let cache = InterpreterCache::new();+ let page = &pdf.pages()[0];+ let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());+ let mut rec = Rec::default();+ interpret_page(page, &mut ctx, &mut rec);+ (rec.0, rec.1)+ }++ #[test]+ fn missing_glyphs_print_as_boxes() {+ // Source Serif 4 lacks 語: its .notdef box is drawn as a path, not as a .notdef glyph+ // (which PDF/A and PDF/UA forbid).+ let boxes = |paths: &[kurbo::Rect]| paths.iter().filter(|r| r.width() > 1.0 && r.width() < 12.0 && r.height() > 3.0 && r.height() < 12.0).count();+ let d = doc_with_text("a語b");+ assert!(!d.settings.glyph_fallback);+ let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap());+ assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::<Vec<_>>(), ["a", "b"], "{glyphs:?}");+ assert_eq!(boxes(&paths), 1, "{paths:?}");+ let a = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { standard: Standard::PdfA2b, ..Default::default() });+ assert!(a.is_ok(), "PDF/A takes the box: {:?}", a.err());+ // A font whose .notdef is empty: the box DesignCraft draws for it.+ const FAMILY: &str = "DC Test PDF Empty Notdef";+ let font = designcraft_fonts::testing::font_mapping(FAMILY, &[('a', 'a'), ('b', 'b')]).unwrap();+ designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::with_empty_notdef(font).unwrap());+ let mut d = doc_with_text("a語b");+ let sid = *d.stories.keys().next().unwrap();+ d.story_mut(sid).unwrap().format_chars(0.."a語b".len(), |f| f.over.font_family = Some(FAMILY.into()));+ let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap());+ assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::<Vec<_>>(), ["a", "b"], "{glyphs:?}");+ assert_eq!(boxes(&paths), 1, "{paths:?}");+ }