DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #512: Hyphenation: Portuguese text is hyphenated with hyph-utf8's Portuguese patterns
aiongg43019733a8b8
diff --cc crates/compose/Cargo.tomlindex 8089e4faf,b8993bcfb..2225367cc--- a/crates/compose/Cargo.toml+++ b/crates/compose/Cargo.toml@@@ -19,9 -17,8 +19,9 @@@ designcraft-doc = { workspace = truedesigncraft-fonts = { workspace = true }log = { workspace = true }regex = { workspace = true }+fancy-regex = { workspace = true }miniz_oxide = "0.8"- hypher = { version = "0.1.8", default-features = false, features = ["alloc", "spanish"] }+ hypher = { version = "0.1.8", default-features = false, features = ["alloc", "portuguese", "spanish"] }[dev-dependencies]designcraft-fonts = { workspace = true, features = ["testing"] }diff --cc crates/compose/src/tests.rsindex 3304c1208,f5d0113c1..3ba37f944--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -2110,1181 -1389,14 +2110,1198 @@@ fn bottom_baseline_fit_preserves_leadin}#[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());+fn baseline_beyond_bottom_still_oversets_and_threads() {+ let text = "First\u{2028}Second";+ let (mut d, sid, f1) = baseline_fit_doc(text, 20.75);+ let before = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(before.line_count(), 1);+ assert_eq!(before.overset_at, Some("First\u{2028}".len()));+ let lid = d.default_layer();+ let (f2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 50.0, 200.0, 60.0), lid, "", ParaFormat::default()).unwrap();+ let options = d.item(f1).unwrap().text_frame().unwrap().options.clone();+ d.item_mut(f2).unwrap().text_frame_mut().unwrap().options = options;+ d.thread(f1, f2).unwrap();+ let after = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!after.is_overset());+ assert_eq!(after.frames.iter().map(|f| f.lines.len()).collect::<Vec<_>>(), [1, 1]);+ assert_eq!(after.frames[0].lines[0].baseline, before.frames[0].lines[0].baseline);+}++#[test]+fn vertical_text_keeps_its_full_cross_line_extent() {+ let (mut d, sid, fid) = baseline_fit_doc("Map", 200.0);+ let it = d.item_mut(fid).unwrap();+ it.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 200.0));+ d.story_mut(sid).unwrap().vertical = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.is_overset());+ assert_eq!(cs.line_count(), 0);+}++#[test]+fn inline_objects_still_clear_the_bottom_edge() {+ let (mut d, sid, _) = baseline_fit_doc("Text", 10.0);+ let it = designcraft_doc::Item::new(+ ItemId(d.alloc()),+ d.default_layer(),+ designcraft_doc::Shape::Rectangle,+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)),+ );+ d.story_mut(sid).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: -3.0 }));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.is_overset());+ assert_eq!(cs.line_count(), 0);+}++#[test]+fn custom_anchors_do_not_change_bottom_baseline_fitting() {+ let (mut d, sid, _) = baseline_fit_doc("Text", 10.0);+ let it = designcraft_doc::Item::new(+ ItemId(d.alloc()),+ d.default_layer(),+ designcraft_doc::Shape::Rectangle,+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)),+ );+ let pos = designcraft_doc::AnchorPosition::Custom {+ x_relative: Default::default(),+ y_relative: Default::default(),+ x_offset: 0.0,+ y_offset: 0.0,+ object_point: 0,+ ref_point: 0,+ keep_within_column: false,+ };+ d.story_mut(sid).unwrap().insert_object(0, designcraft_doc::AnchoredObject::new(it, pos));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_eq!(cs.line_count(), 1);+ assert_eq!(cs.frames[0].objects.len(), 1);+}++#[test]+fn baseline_shift_keeps_its_metrics_and_glyph_offset_at_bottom() {+ let (mut d, sid, _) = baseline_fit_doc("Map", 10.0);+ let plain = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.baseline_shift = Some(-3.0));+ let shifted = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!plain.is_overset() && !shifted.is_overset());+ let (p, s) = (&plain.frames[0].lines[0], &shifted.frames[0].lines[0]);+ assert_eq!(p.baseline, s.baseline);+ assert!((s.descent - p.descent - 3.0).abs() < 1e-6);+ assert!((s.glyphs[0].y - p.glyphs[0].y - 3.0).abs() < 1e-6);+}++#[test]+fn path_text_keeps_the_original_vertical_fit_limit() {+ // A path's synthetic layout area is not an ordinary text frame: admitting a+ // second line would paint both lines on the same path, regardless of leading.+ for separator in ['\n', designcraft_doc::story::FORCED_LINE_BREAK] {+ for leading in [8.0, 10.0] {+ let text = format!("HELLO{separator}WORLD");+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ let it = d.item_mut(fid).unwrap();+ it.shape = designcraft_doc::Shape::Path;+ it.path = designcraft_geom::shapes::line(Point::ZERO, Point::new(200.0, 0.0));+ it.text_frame_mut().unwrap().options.path =+ Some(designcraft_doc::PathType { start: 0.0, flip: false, align: designcraft_doc::PathAlign::Baseline });+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some("Source Serif 4".into());+ f.over.size = Some(20.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(leading));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(cs.line_count(), 1, "{separator:?}, leading {leading}");+ assert_eq!(cs.overset_at, Some("HELLO".len() + separator.len_utf8()));+ }+ }+}++fn two_keep_frames(text: &str) -> (Document, StoryId, ItemId, ItemId) {+ let (mut d, sid, first) = baseline_fit_doc(text, 48.0);+ d.item_mut(first).unwrap().path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 75.0, 48.0));+ let lid = d.default_layer();+ let (second, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 0.0, 210.0, 69.0), lid, "", ParaFormat::default()).unwrap();+ let options = d.item(first).unwrap().text_frame().unwrap().options.clone();+ d.item_mut(second).unwrap().text_frame_mut().unwrap().options = options;+ d.thread(first, second).unwrap();+ (d, sid, first, second)+}++#[test]+fn keep_chain_spanning_frames_does_not_empty_its_top_column() {+ let a = "One\u{2028}Two\u{2028}Three\u{2028}Four\u{2028}Five\u{2028}Six";+ let b = "Seven\u{2028}Eight\u{2028}Nine\u{2028}Ten";+ let text = format!("{a}\n{b}\nEnd");+ let (mut d, sid, first, second) = two_keep_frames(&text);+ let paras = &mut d.story_mut(sid).unwrap().paras;+ paras[0].para.keep_with_next = Some(2);+ paras[0].para.space_after = Some(2.0);+ paras[1].para.keep_with_next = Some(2);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ // The keep chain cannot fit in either column. Fall back to flowing it, rather+ // than moving a paragraph already at a column top and throwing that column away.+ assert_eq!(cs.frame(first).unwrap().lines.len(), 4);+ assert_eq!(cs.frame(second).unwrap().lines.len(), 6);+ assert_eq!(cs.overset_at, Some(a.len() + b.len() + 2));+}++#[test]+fn satisfiable_keep_chain_still_moves_together_to_the_next_frame() {+ let text = "One\u{2028}Two\nHeading\nSubheading\nBody";+ let (mut d, sid, first, second) = two_keep_frames(text);+ let paras = &mut d.story_mut(sid).unwrap().paras;+ paras[1].para.keep_with_next = Some(1);+ paras[2].para.keep_with_next = Some(1);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_eq!(cs.frame(first).unwrap().lines.len(), 2);+ assert_eq!(cs.frame(second).unwrap().lines.iter().map(|l| l.para).collect::<Vec<_>>(), [1, 2, 3]);+}++/// OS/2 field offsets: sTypoAscender, sTypoDescender, the high half of ulCodePageRange1, sxHeight,+/// sCapHeight.+const TYPO_ASCENDER: usize = 68;+const TYPO_DESCENDER: usize = 70;+const CODE_PAGES_HIGH: usize = 78;+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));+ // 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 em_box_first_baseline_follows_base_then_the_typo_box_or_the_cap_height() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ // [`test_font`] (typo descender -326, cap height 660), with or without its `BASE` table, whose+ // em box bottom (`ideo`) is at -170 units.+ let add = |family: &str, base: bool, fields: &[(usize, i16)]| {+ let mut b = test_font(family, Some(fields));+ if !base {+ 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"BASE").unwrap();+ // Still sorted between its neighbours, so the table directory stays valid.+ b[rec..rec + 4].copy_from_slice(b"BASX");+ }+ db.add_font(b);+ db.face(family, "Regular").declared_em_box()+ };+ // Typo ascender − descender = 1 em in a CJK font (JIS code page, bit 17): the typo ascender is+ // the top.+ let typo = [(TYPO_ASCENDER, 850), (TYPO_DESCENDER, -150)];+ assert_eq!(add("EmBoxTypo 850", false, &[typo[0], typo[1], (CODE_PAGES_HIGH, 1 << 1)]), Some((850.0, -150.0)));+ // In a Latin font the cap height decides: 0.5 em + 660 / 2.+ assert_eq!(add("EmBoxLatn 850", false, &typo), Some((830.0, -170.0)));+ // Otherwise the em box is centred on half the cap height: 0.5 em + 600 / 2.+ assert_eq!(add("EmBoxCapH 600", false, &[(TYPO_ASCENDER, 700), (CAP_HEIGHT, 600)]), Some((800.0, -200.0)));+ // No OS/2 cap height: the H glyph's top, 656.+ assert_eq!(add("EmBoxGlyphH 0", false, &[(TYPO_ASCENDER, 700), (CAP_HEIGHT, 0)]), Some((828.0, -172.0)));+ // A `BASE` em box comes first.+ assert_eq!(add("EmBoxBase 850", true, &[(TYPO_ASCENDER, 850), (TYPO_DESCENDER, -150)]), Some((830.0, -170.0)));+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ let mut first = |family: &str, sizes: [f64; 2], kind: FirstBaseline| {+ let st = d.story_mut(sid).unwrap();+ for (range, size) in [(0..4, sizes[0]), (4..7, sizes[1])] {+ st.format_chars(range, |f| {+ f.over.font_family = Some(family.into());+ f.over.font_style = Some("Regular".into());+ f.over.size = Some(size);+ });+ }+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = kind;+ compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline - 36.0+ };+ let close = |a: f64, b: f64| (a - b).abs() < 0.01;+ let asc = first("EmBoxCapH 600", [10.0; 2], FirstBaseline::Ascent);+ assert!(close(asc, 7.0), "{asc}");+ for (family, top) in [("EmBoxTypo 850", 8.5), ("EmBoxLatn 850", 8.3), ("EmBoxCapH 600", 8.0), ("EmBoxGlyphH 0", 8.28), ("EmBoxBase 850", 8.3)] {+ let emb = first(family, [10.0; 2], FirstBaseline::EmboxHeight);+ assert!(close(emb, top), "{family}: {emb}");+ }+ // A mixed first line takes its largest size.+ let emb = first("EmBoxCapH 600", [10.0, 20.0], FirstBaseline::EmboxHeight);+ assert!(close(emb, 16.0), "{emb}");+}++#[test]+fn em_box_first_baseline_in_a_latin_font_with_a_one_em_typo_box_follows_the_cap_height() {+ use designcraft_doc::FirstBaseline;+ // DejaVu Serif: 2048 units per em, typo ascender 1556 and descender -492 (one em), cap height+ // 1493. Read from the system fonts; the test skips where it isn't installed.+ let Some(bytes) = designcraft_fonts::system_font_dirs().iter().find_map(|dir| {+ ["truetype/dejavu/DejaVuSerif.ttf", "dejavu/DejaVuSerif.ttf", "DejaVuSerif.ttf"].iter().find_map(|p| std::fs::read(dir.join(p)).ok())+ }) else {+ eprintln!("skipped: DejaVu Serif isn't installed");+ return;+ };+ let db = designcraft_fonts::FontDb::global();+ db.add_font(bytes);+ let face = db.face("DejaVu Serif", "Book");+ assert_eq!(face.family, "DejaVu Serif");+ 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();+ let n = st.len();+ st.format_chars(0..n, |f| {+ f.over.font_family = Some("DejaVu Serif".into());+ f.over.font_style = Some("Book".into());+ f.over.size = Some(10.0);+ });+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::EmboxHeight;+ let first = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline - 36.0;+ // 0.5 em + cap height / 2, not the 1556-unit typo ascender (7.60 pt).+ let expected = 5.0 + 1493.0 / 2048.0 * 5.0;+ assert!((first - expected).abs() < 0.01, "{first}, expected {expected}");+}++#[test]+fn em_box_first_baseline_ignores_baseline_shift() {+ use designcraft_doc::FirstBaseline;+ let db = designcraft_fonts::FontDb::global();+ // Source Sans 3's `BASE` em box tops 0.83 em above the baseline.+ db.add_font(test_font("EmBoxShft 830", Some(&[])));+ 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("EmBoxShft 830".into());+ f.over.font_style = Some("Regular".into());+ f.over.size = Some(10.0);+ });+ st.format_chars(4..7, |f| f.over.baseline_shift = Some(1.0));+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::EmboxHeight;+ let frames = compose_story(&d, sid, &ComposeOptions::default()).frames;+ let line = &frames[0].lines[0];+ // The unshifted run's baseline stays 8.3 pt below the frame top; the shifted run is drawn 1 pt+ // higher.+ assert!((line.baseline - 36.0 - 8.3).abs() < 0.01, "{}", line.baseline);+ let ys: Vec<f64> = line.glyphs.iter().map(|g| g.y).collect();+ assert_eq!(ys.len(), 7, "{ys:?}");+ assert!(ys[..3].iter().all(|y| y.abs() < 0.01), "{ys:?}");+ assert!(ys[4..].iter().all(|y| (y + 1.0).abs() < 0.01), "{ys:?}");+}++#[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_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 a_visible_frame_stroke_insets_the_text() {+ use designcraft_doc::{Stroke, StrokeAlign};+ let line = |stroke: Option<(StrokeAlign, &str)>| {+ let (mut d, sid, fid) = doc_with("Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());+ let it = d.item_mut(fid).unwrap();+ if let Some((align, swatch)) = stroke {+ it.stroke = Stroke { weight: 4.0, align, swatch: swatch.into(), ..Stroke::default() };+ }+ it.text_frame_mut().unwrap().options.inset = [4.0; 4];+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];+ (l.baseline, l.x0, l.x1)+ };+ let black = designcraft_color::swatch::BLACK;+ let (b, x0, x1) = line(None);+ // The part of the 4 pt stroke inside the frame: half of it centred, all of it inside, none+ // outside or without a colour; on the left and right as on the top.+ for (stroke, d) in [+ ((StrokeAlign::Center, black), 2.0),+ ((StrokeAlign::Inside, black), 4.0),+ ((StrokeAlign::Outside, black), 0.0),+ ((StrokeAlign::Inside, designcraft_color::swatch::NONE), 0.0),+ ] {+ let (sb, sx0, sx1) = line(Some(stroke));+ assert!((sb - (b + d)).abs() < 1e-6, "{stroke:?}: baseline {sb} vs {b}");+ assert!((sx0 - (x0 + d)).abs() < 1e-6 && (sx1 - (x1 - d)).abs() < 1e-6, "{stroke:?}: {sx0}..{sx1} vs {x0}..{x1}");+ }+}++#[test]+fn list_labels_do_not_raise_the_ascent_first_baseline() {+ use designcraft_doc::{CharAttrs, ListType};+ // The paragraph's own character size (the label's) is 40 pt; its text is 10 pt (Source Sans 3:+ // typo ascender 1 em).+ let line = |text: &str, list: ListType| {+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs { list_type: Some(list), ..Default::default() });+ let st = d.story_mut(sid).unwrap();+ for p in &mut st.paras {+ p.chars = CharAttrs { font_family: Some("Source Sans 3".into()), size: Some(40.0), ..Default::default() };+ }+ st.format_chars(0..text.len(), |f| f.over.size = Some(10.0));+ let l = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();+ (l.baseline, l.ascent, l.leading)+ };+ let (b, asc, lead) = line("Hxg Hxg", ListType::None);+ // 1 em of the 10 pt text below the frame top.+ assert!((b - 46.0).abs() < 0.01, "{b}");+ for list in [ListType::Bullets, ListType::Numbers] {+ let (lb, lasc, llead) = line("Hxg Hxg", list);+ assert!((lb - b).abs() < 1e-6, "{list:?}: {lb} vs {b}");+ // The 40 pt label still sets the line's ascent and leading.+ assert!(lasc > asc + 20.0 && (llead - 48.0).abs() < 1e-6 && (lead - 12.0).abs() < 1e-6, "{list:?}: {lasc} {asc} {llead} {lead}");+ }+ // An empty bulleted paragraph sits like an empty paragraph.+ let (eb, _, _) = line("", ListType::None);+ let (ebl, _, _) = line("", ListType::Bullets);+ assert!((ebl - eb).abs() < 1e-6, "{ebl} vs {eb}");+}++#[test]+fn spaces_count_toward_the_ascent_first_baseline() {+ // 10 pt text with a 40 pt space between its words (Source Sans 3: typo ascender 1 em).+ let (mut d, sid, _) = 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("Source Sans 3".into());+ f.over.size = Some(10.0);+ });+ st.format_chars(3..4, |f| f.over.size = Some(40.0));+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];+ assert!((l.baseline - (36.0 + 40.0)).abs() < 0.01, "{}", l.baseline);+}++#[test]+fn vertical_scale_does_not_move_the_ascent_first_baseline() {+ let db = designcraft_fonts::FontDb::global();+ db.add_font(typo_test_font("TypoAscentVSc", Some(700)));+ let line = |v_scale: f64| {+ 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("TypoAscentVSc".into());+ f.over.size = Some(20.0);+ f.over.v_scale = Some(v_scale);+ });+ 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];+ (l.baseline, l.ascent)+ };+ let ((b100, a100), (b200, a200)) = (line(1.0), line(2.0));+ // The typo ascender of the nominal size (0.7 × 20 pt) at 100 % and at 200 %.+ assert!((b100 - (36.0 + 4.0 + 14.0)).abs() < 0.01, "{b100}");+ assert!((b200 - b100).abs() < 0.01, "{b200} vs {b100}");+ // The line box keeps the scaled ascent.+ assert!((a100 - 20.0).abs() < 0.01 && (a200 - 40.0).abs() < 0.01, "{a100} {a200}");+}++#[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 of the x+ // (0.486 em).+ 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, 486.0), "{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 + 9.72)).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_dir("CapXHeightVrt", true, |o| {+ o.first_baseline = kind;+ 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 tab_beside_a_drop_cap_is_measured_from_the_drop_cap() {+ // The line breaker measures a tab from where the line starts, which beside a drop cap is+ // after the drop cap: measured from the frame edge, the tab looks wider and the line breaks+ // a word early.+ let stop = designcraft_doc::TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let para = ParaAttrs { tabs: Some(vec![stop]), hyphenate: Some(false), ..drop_cap(3, 1) };+ let text = format!("Wort\t{LOREM}");+ let (d, sid, _) = drop_doc(&text, para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let space = |g: &PlacedGlyph| g.len > 0 && text.get(g.byte..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);+ let right = lines[0].glyphs.iter().filter(|g| g.visible && !space(g)).map(|g| g.x + g.adv).fold(0.0, f64::max);+ assert!(right <= lines[0].x1 + 0.01, "line 1 ends at {right}, past {}", lines[0].x1);+ let word: f64 = lines[1].glyphs.iter().filter(|g| g.len > 0).take_while(|g| !space(g)).map(|g| g.adv).sum();+ assert!(right + word + 4.0 > lines[0].x1, "line 2's first word ({word} pt) fits after line 1's end at {right} (edge {})", lines[0].x1);+}++#[test]+fn warichu_on_a_drop_cap_line_leaves_the_drop_cap_alone() {+ let text = format!("WABCDEFGH {LOREM}");+ let (mut d, sid, _) = drop_doc(&text, drop_cap(3, 1));+ let plain = compose_story(&d, sid, &ComposeOptions::default());+ let plain_dc = plain.frames[0].lines[0].glyphs[0].clone();+ // A plain drop cap line has no stacked rows: one selection band, caret on the line.+ let pl = &plain.frames[0].lines[0];+ assert_eq!(highlight_quads(pl, 0, 12, false).len(), 1);+ assert_eq!(caret(&plain, 1).map(|c| (c.2, c.3)), Some((pl.baseline, pl.ascent)));+ d.story_mut(sid).unwrap().format_chars(1..9, |f| {+ f.over.warichu = Some(true);+ f.over.warichu_alignment = Some(designcraft_doc::cjk::WarichuAlignment::Left);+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let dc = &l.glyphs[0];+ assert_eq!((dc.byte, dc.x, dc.y, dc.sy), (0, plain_dc.x, plain_dc.y, plain_dc.sy), "the drop cap is not part of the note");+ let at = |byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).unwrap();+ let (top, bot, after) = (at(1), at(5), at(10));+ assert!(bot.y - top.y > 1.0, "the note is stacked in two rows");+ assert!(top.x >= dc.x + dc.adv - 1e-6, "the note starts after the drop cap");+ assert!((after.x - (at(8).x + at(8).adv + at(9).adv)).abs() < 1e-3, "the line closes up after the note");+ // The caret: in the drop cap as tall as it, on a note row that row's baseline, after the+ // note the parent line's.+ let dc_box = l.drop_cap.unwrap();+ assert_eq!(caret(&cs, 0).map(|c| c.2), Some(dc_box.baseline));+ assert!((caret(&cs, 1).unwrap().2 - (l.baseline + top.y)).abs() < 1e-6);+ assert_eq!(caret(&cs, 10).map(|c| (c.2, c.3)), Some((l.baseline, l.ascent)));+ let click = |g: &PlacedGlyph| hit(&cs, 0, designcraft_geom::Point::new(g.x + g.adv * 0.25, l.baseline + g.y)).unwrap();+ assert_eq!((click(top), click(bot), click(after)), (1, 5, 10));+ // Selecting the drop cap and the note: the drop cap's band and one per row.+ assert_eq!(highlight_quads(l, 0, 9, false).len(), 3);+}++#[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, _) = 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]");+ // The drop cap's style is a leading "through 1 drop cap" nested style: the nested styles start+ // after the drop cap.+ let one = designcraft_doc::NestedStyle { style: "Lead".into(), through: true, count: 1, until: designcraft_doc::NestedUntil::Characters };+ d.story_mut(sid).unwrap().paras[0].para.nested_styles = Some(vec![one]);+ 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(3)), fill(&cs, at(4))), ("Lead Blue".to_string(), "[Black]".to_string()));+ // 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));+ // A double click there is on the drop cap's character, not on line 3's text.+ assert_eq!(hit_char(&cs, 0, Point::new(dc.x + dc.adv * 0.5, y)), Some(0));+ // 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_on_a_baseline_grid_reaches_down_by_grid_steps() {+ // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap reaches down two grid+ // steps, to 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 line with a larger auto leading doesn't move the drop cap: it reaches down `lines − 1`+/// leadings of the text after it, not to where line N is set.+#[test]+fn drop_cap_reaches_down_by_the_text_leading_past_a_line_with_larger_leading() {+ use designcraft_doc::{CharAttrs, Composer, Leading};+ let text = [LOREM; 2].join(" ");+ let para = ParaAttrs { composer: Some(Composer::SingleLine), ..drop_cap(3, 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 = CharAttrs { size: Some(12.0), leading: Some(Leading::Auto), ..Default::default() };+ // A larger word starts line 2, so lines 2 and 3 are set further down than 2 × 14.4 pt.+ let start2 = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[1].range.start;+ d.story_mut(sid).unwrap().format_chars(start2..start2 + 3, |f| f.over.size = Some(20.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines[1].range.start, start2);+ assert!(lines[2].baseline - lines[0].baseline > 2.0 * 14.4 + 5.0, "{} {}", lines[0].baseline, lines[2].baseline);+ let dc = &lines[0].glyphs[0];+ assert!((dc.y - 2.0 * 14.4).abs() < 1e-6, "drop cap baseline {} below line 1", dc.y);+ let b = lines[0].drop_cap.unwrap();+ assert!((b.baseline - (lines[0].baseline + 2.0 * 14.4)).abs() < 1e-6, "{}", b.baseline);+}++/// A space after the drop cap is set at its size on its baseline and doesn't widen the indent: the+/// lines beside it start where its characters end.+#[test]+fn space_after_a_drop_cap_does_not_widen_the_indent() {+ let (d, sid, _) = drop_doc(&format!("In 2003 {LOREM}"), drop_cap(2, 2));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let (i, n) = (&lines[0].glyphs[0], &lines[0].glyphs[1]);+ assert_eq!((i.byte, n.byte), (0, 1));+ let end = n.x + n.adv;+ for l in &lines[..2] {+ assert!((text_x(l, 3) - end).abs() < 1e-6, "{} vs {end}", text_x(l, 3));+ }+ let space = lines[0].glyphs.iter().find(|g| g.byte == 2).unwrap();+ assert!((space.sy - n.sy).abs() < 1e-9 && (space.y - n.y).abs() < 1e-9, "the space is set like the drop cap");+ assert_eq!(lines[0].drop_cap.unwrap().end, 3);+}++/// A one-line drop cap keeps its characters' own size (a smaller verse number stays smaller), and+/// the tabs in it advance to the paragraph's tab stops.+#[test]+fn one_line_drop_cap_keeps_its_size_and_sets_its_tabs() {+ let stop = |position, align| designcraft_doc::TabStop { position, align, leader: String::new(), align_on: String::new() };+ let para = ParaAttrs { tabs: Some(vec![stop(30.0, TabAlign::Right), stop(40.0, TabAlign::Left)]), ..drop_cap(1, 3) };+ let (mut d, sid, _) = drop_doc(&format!("\t7\t{LOREM}"), para);+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.size = Some(8.0));+ 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();+ let (seven, body) = (at(1), at(3));+ assert!((seven.sy / body.sy - 0.8).abs() < 1e-9, "{} vs {}", seven.sy, body.sy);+ assert!(seven.y.abs() < 1e-9);+ assert!((seven.x + seven.adv - 30.0).abs() < 1e-6, "the number ends at the right tab: {}", seven.x + seven.adv);+ assert!((text_x(l, 3) - 40.0).abs() < 1e-6, "the text starts at the left tab: {}", text_x(l, 3));+}++/// Right to left, the tabs in a drop cap advance to tab stops measured from the column's right+/// edge.+#[test]+fn right_to_left_drop_cap_sets_its_tabs_from_the_right_edge() {+ let stop = |position, align| designcraft_doc::TabStop { position, align, leader: String::new(), align_on: String::new() };+ let para = ParaAttrs {+ direction: Some(designcraft_doc::TextDirection::RightToLeft),+ align: Some(Align::Right),+ tabs: Some(vec![stop(30.0, TabAlign::Right), stop(40.0, TabAlign::Left)]),+ ..drop_cap(1, 3)+ };+ let (d, sid, _) = drop_doc(&format!("\t7\t{LOREM}"), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = &cs.frames[0].lines[0];+ let seven = l.glyphs.iter().find(|g| g.byte == 1).unwrap();+ // The 300 pt column's right edge is at 300: the number's far (left) end is 30 pt from it.+ assert!((seven.x - 270.0).abs() < 1e-6, "the number ends at the right tab: {}", seven.x);+ // The text beside it starts at the left tab, 40 pt from the edge.+ let right = l.glyphs.iter().filter(|g| g.byte >= 3 && g.visible).map(|g| g.x + g.adv).fold(f64::NEG_INFINITY, f64::max);+ assert!(right <= 260.0 + 1e-6 && right > 255.0, "text ends at {right}");+}++/// 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 caret_follows_spaces_typed_at_the_end() {+ let x_at_end = |text: &str| {+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let end_x = cs.frames[0].lines[0].end_x;+ (caret(&cs, text.len()).unwrap().1, end_x)+ };+ let (word, word_end) = x_at_end("Word");+ let (one, one_end) = x_at_end("Word ");+ let (two, _) = x_at_end("Word ");+ assert!(one > word + 1.0 && two > one + 1.0, "{word} {one} {two}");+ // The spaces don't count for the line's own length (alignment, justification).+ assert!((one_end - word_end).abs() < 1e-9);+ // Wrapped lines keep their spaces too: a caret between two spaces at a line end sits after+ // the first one.+ let text = "Lorem ipsum dolor sit amet consectetur";+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 140.0, 100.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l0 = &cs.frames[0].lines[0];+ if l0.range.end == text.find("consectetur").unwrap() {+ let mid = text.find(" ").unwrap() + 1;+ assert!(caret(&cs, mid).unwrap().1 > l0.end_x, "between the trailing spaces");+ }+}++#[test]+fn colour_change_keeps_kerning_and_ligatures_keep_colour() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "ayay", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.font_style = Some("Bold".into()));+ let line = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();+ let xs = |l: &Line| l.glyphs.iter().map(|g| (g.x, g.adv)).collect::<Vec<_>>();+ let kerned = line(&d);+ // The font kerns "ay" (otherwise this test proves nothing).+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::None));+ assert_ne!(xs(&line(&d)), xs(&kerned), "Source Serif 4 Bold kerns a–y");+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::Metrics));+ // Colour the first "a": positions are unchanged, only its style differs.+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.fill = Some("Cyan".into()));+ let coloured = line(&d);+ assert_eq!(xs(&coloured), xs(&kerned), "a colour change must not change spacing");+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let fill = |l: &Line, i: usize| cs.styles[l.glyphs[i].style as usize].fill.clone();+ assert_eq!(fill(&coloured, 0), "Cyan");+ assert_ne!(fill(&coloured, 1), "Cyan");++ // A ligature never swallows a differently coloured letter: the "i" of "fi" keeps its colour.+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 300.0, 400.0, 400.0), lid, "fifi", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(1..2, |f| f.over.fill = Some("Cyan".into()));+ 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.len > 0 && g.byte <= b && b < g.byte + g.len).map(|g| cs.styles[g.style as usize].fill.clone());+ assert_eq!(at(1).as_deref(), Some("Cyan"));+ assert_ne!(at(2).as_deref(), Some("Cyan"));+}++/// The emphasis mark drawn over the text only paints: a change of kenten character keeps the+/// kerning across it.+#[test]+fn kenten_character_change_keeps_kerning() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "ayay", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0..4, |f| {+ f.over.font_style = Some("Bold".into());+ f.over.kenten = Some(true);+ });+ let xs = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs.iter().filter(|g| g.len > 0).map(|g| (g.byte, g.x, g.adv)).collect::<Vec<_>>()+ };+ let kerned = xs(&d);+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::None));+ assert_ne!(xs(&d), kerned, "Source Serif 4 Bold kerns a–y");+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::Metrics));+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.kenten_character = Some("●".into()));+ assert_eq!(xs(&d), kerned, "a kenten character change must not change spacing");+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let mark = |b: usize| {+ cs.frames[0].lines[0]+ .glyphs+ .iter()+ .find(|g| g.len > 0 && g.byte == b)+ .and_then(|g| cs.styles[g.style as usize].kenten_mark.as_ref().map(|m| m.text.clone()))+ };+ // The default kind (sesame dot) draws a stored character, else its own mark.+ assert_eq!((mark(0).as_deref(), mark(1).as_deref()), (Some("●"), Some("\u{FE45}")));+}++#[test]+fn empty_paragraph_takes_its_marks_format() {+ // Paragraph style text is 12 pt (auto leading 14.4); every character, including the empty+ // paragraph's mark, is 6 pt with 8 pt leading: the empty line must advance 8, not 14.4.+ let text = "One\n\nTwo";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.size = Some(6.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(8.0));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 3);+ assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);+ assert!((lines[2].baseline - lines[1].baseline - 8.0).abs() < 1e-6, "{} {}", lines[1].baseline, lines[2].baseline);+}++#[test]+fn empty_paragraph_uses_its_own_mark_not_the_previous_one() {+ // "One\n" is 20 pt; the empty paragraph's mark (byte 4) and "Two" are 6 pt with 8 pt leading.+ // The format run boundary sits exactly at the empty paragraph's start: its line must take the+ // 8 pt leading of its own mark, not the previous paragraph's 20 pt (auto 24) mark.+ let text = "One\n\nTwo";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ st.format_chars(0..4, |f| f.over.size = Some(20.0));+ st.format_chars(4..text.len(), |f| {+ f.over.size = Some(6.0);+ f.over.leading = Some(designcraft_doc::Leading::Points(8.0));+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 3);+ assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);+}++#[test]+fn spanish_text_gets_spanish_hyphenation() {+ let text = "La transición democrática fue una construcción colectiva extraordinariamente compleja y desesperadamente necesaria.";+ let narrow = Rect::new(36.0, 36.0, 120.0, 700.0);+ let (mut d, sid, _) = doc_with(text, narrow, ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ let n = st.len();+ st.format_chars(0..n, |f| f.over.language = Some("Spanish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ let hy: Vec<&str> = lines.iter().filter(|l| l.hyphenated).map(|l| text[l.range.clone()].trim_end()).collect();+ assert!(!hy.is_empty(), "Spanish hyphenates");+ for l in &hy {+ let last: String = l.chars().rev().take_while(|c| c.is_alphabetic()).collect::<Vec<_>>().into_iter().rev().collect();+ let whole = text[text.find(l).unwrap() + l.len() - last.len()..].split(|c: char| !c.is_alphabetic()).next().unwrap();+ let es = hyphen::Lang::for_language("Spanish").unwrap();+ let pts = hyphen::hyphen_points_in(whole, &hyphen::Limits::default(), es);+ assert!(pts.contains(&last.chars().count()), "break {last}- in {whole} is a Bezos point");+ }+}+++#[test]++fn portuguese_text_gets_portuguese_hyphenation() {++ let text = "matemática matemática matemática matemática matemática matemática";++ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 76.0, 700.0), ParaAttrs::default());++ let st = d.story_mut(sid).unwrap();++ let n = st.len();++ st.format_chars(0..n, |f| f.over.language = Some("Portuguese: Brazilian".into()));++ let cs = compose_story(&d, sid, &ComposeOptions::default());++ let breaks: Vec<&str> = all_lines(&cs).into_iter().filter(|l| l.hyphenated).map(|l| text[l.range.clone()].trim_end()).collect();++ assert!(!breaks.is_empty(), "Portuguese text is hyphenated");++ // Portuguese syllables: ma-te-má-tica.++ for b in breaks {++ let tail = b.rsplit(' ').next().unwrap_or(b);++ assert!(["ma", "mate", "matemá"].contains(&tail), "{b:?}");++ }++}+++#[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);