DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #83 (layout parity) into feat/text-editing-and-frames
Brandon Thomas0590f634068a
diff --cc crates/compose/src/lib.rsindex 065257c53,156f55a90..bc4f99232--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -846,15 -908,18 +908,27 @@@ fn compose_with_db(doc: &Document, storlet 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, &bidi_info);+ // The spaces the break trimmed off the end follow the line undrawn, so the caret+ // and the selection reach them; alignment and justification ignore them.+ if pp.direction != designcraft_doc::TextDirection::RightToLeft && !placed.iter().any(|g| g.rtl) {+ let mut x = end_x;+ for g in glyphs.get(e..(g0 + b.next).min(glyphs.len())).unwrap_or(&[]).iter().filter(|g| g.is_space()) {+ placed.push(PlacedGlyph { visible: false, ..place(g, x) });+ x += g.adv;+ }+ }+ 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(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);@@@ -2227,42 -2533,29 +2544,57 @@@ pub fn line_rtl(cs: &ComposedStory, poscaret_line(cs, pos).and_then(|(_, l)| l.glyphs.iter().find(|g| g.len > 0)).is_some_and(|g| g.rtl)}+/// The line of frame `ft` closest to point `p` vertically (within its column).+fn hit_line(ft: &FrameText, p: Point) -> Option<&Line> {+ ft.lines+ .iter()+ .filter(|l| p.x >= l.x0 - 20.0 && p.x <= l.x1 + 20.0 || ft.columns.len() <= 1)+ .min_by(|a, b| line_dist(a, p.y).total_cmp(&line_dist(b, p.y)))+ .or_else(|| ft.lines.first())+}++/// Story byte of the character drawn under point `p` (frame inner space) in frame `fi`: the+/// glyph whose advance spans `p.x` on the closest line, else the one nearest it. For selecting+/// the word (or the spaces) under a double click; [`hit`] finds a caret position instead.+pub fn hit_char(cs: &ComposedStory, fi: usize, p: Point) -> Option<usize> {+ let ft = cs.frames.get(fi)?;+ let Some(l) = hit_line(ft, p) else { return Some(ft.range.start) };+ let dist = |g: &&PlacedGlyph| {+ let (a, b) = (g.x.min(g.x + g.adv), g.x.max(g.x + g.adv));+ if p.x < a {+ a - p.x+ } else if p.x >= b {+ p.x - b+ } else {+ 0.0+ }+ };++ // On a drop cap (it reaches down beside the lines after its own): its character under `p`.++ for dl in &ft.lines {++ let Some(dc) = dl.drop_cap.filter(|dc| dc.rect.contains(p)) else { continue };++ return dl.glyphs.iter().filter(|g| g.len > 0 && g.byte < dc.end).min_by(|a, b| dist(a).total_cmp(&dist(b))).map(|g| g.byte);++ }+ let under = l.glyphs.iter().filter(|g| g.len > 0).min_by(|a, b| dist(a).total_cmp(&dist(b)));+ Some(under.map_or(l.range.start, |g| g.byte))+}+/// Story byte nearest to point `p` (frame inner space) in frame `fi`.pub fn hit(cs: &ComposedStory, fi: usize, p: Point) -> Option<usize> {let ft = cs.frames.get(fi)?;if ft.lines.is_empty() {return Some(ft.range.start);}+ // On a drop cap (it reaches down beside the lines after its own): the nearest caret position in it.+ for l in &ft.lines {+ let Some(dc) = l.drop_cap.filter(|dc| dc.rect.contains(p)) else { continue };+ return l+ .glyphs+ .iter()+ .filter(|g| g.len > 0 && g.byte < dc.end)+ .flat_map(|g| [g.byte, g.byte + g.len])+ .min_by(|a, b| (caret_x(l, *a) - p.x).abs().total_cmp(&(caret_x(l, *b) - p.x).abs()));+ }- // Closest line vertically (within its column).- let l = ft- .lines- .iter()- .filter(|l| p.x >= l.x0 - 20.0 && p.x <= l.x1 + 20.0 || ft.columns.len() <= 1)- .min_by(|a, b| line_dist(a, p.y).total_cmp(&line_dist(b, p.y)))- .or_else(|| ft.lines.first())?;+ let l = hit_line(ft, p)?;if l.glyphs.iter().any(|g| g.rtl) {// Bidi: the caret position drawn nearest the point.return caret_stops(l).into_iter().min_by(|a, b| (a.1 - p.x).abs().total_cmp(&(b.1 - p.x).abs())).map(|s| s.0);diff --cc crates/compose/src/tests.rsindex ec0df8537,b9da78381..3ab7b9118--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -1069,32 -1308,534 +1308,562 @@@ 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_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_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 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]");+ // 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_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 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 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());