DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge origin/main into feat/text-editing-and-frames
Brandon Thomas962234fbdf6a
diff --cc crates/compose/src/lib.rsindex 25361b636,5a3056d8f..065257c53--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -794,17 -845,8 +845,17 @@@ fn compose_with_db(doc: &Document, storlet lx1 = x1 - pp.right_indent;let last = k + 1 == breaks.len();let (mut placed, end_x, ratio) =- layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page);+ layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page, &bidi_info);+ // 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 !placed.iter().any(|g| g.rtl) {++ 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;+ }+ }- ruby::annotate(&styles_tab, &mut placed);+ ruby::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);let range_start = if line_no == 0 { prange.start } else { range_start };diff --cc crates/compose/src/tests.rsindex 1d7588cf8,549e7bccf..ec0df8537--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -1028,28 -1069,811 +1069,837 @@@ fn only_english_text_gets_english_hypheassert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules");}+#[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());+ let old = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.leading_aki = Some(Some(0.25));+ f.over.trailing_aki = Some(Some(0.5));+ });+ let new = compose_story(&d, sid, &ComposeOptions::default());+ let a = &old.frames[0].lines[0];+ let b = &new.frames[0].lines[0];+ assert!((b.end_x - a.end_x - 18.0).abs() < 1e-6);+ assert_eq!(a.glyphs[0].sx, b.glyphs[0].sx);+ assert!((b.glyphs[0].x - a.glyphs[0].x - 3.0).abs() < 1e-6);+ }++ #[test]+ fn cjk_jidori_sets_group_width_and_survives_narrow_frames() {+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {+ let (mut d, sid, _) = doc_with(+ "AB",+ Rect::new(0.0, 0.0, 30.0, 150.0),+ ParaAttrs { composer: Some(composer), glyph_scale_desired: Some(1.2), letter_space_desired: Some(0.2), ..Default::default() },+ );+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.jidori = Some(4));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 1, "an indivisible jidori group must not be emergency-split");+ assert!((lines[0].end_x - lines[0].x0 - 48.0).abs() < 1e-6);+ assert_eq!(lines[0].range, 0..2);+ }+ }++ #[test]+ fn cjk_tsume_removes_sidebearings_without_collapsing_ink() {+ let (mut d, sid, _) = doc_with("HH", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ let old = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.tsume = Some(1.0));+ let new = compose_story(&d, sid, &ComposeOptions::default());+ let a = &old.frames[0].lines[0];+ let b = &new.frames[0].lines[0];+ let g = &b.glyphs[0];+ let outline = designcraft_fonts::FontDb::global().outline(&g.face, g.gid);+ let ink_width = designcraft_geom::Shape::bounding_box(&*outline).width() * g.sx;+ assert!(ink_width > 0.0);+ assert!((b.end_x - b.x0 - 2.0 * ink_width).abs() < 1e-6);+ assert!(b.end_x < a.end_x);+ assert_eq!(a.glyphs[0].sx, g.sx);+ }++ #[test]+ fn cjk_composite_font_selects_entries_before_shaping() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "0123456789".into(), family: "Source Sans 3".into(), relative_size: 0.5, ..Default::default() },+ ],+ });+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = &cs.frames[0].lines[0];+ let a = line.glyphs.iter().find(|g| g.byte == 0).unwrap();+ let n = line.glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert_ne!(a.face.id(), n.face.id());+ assert_eq!(cs.styles[a.style as usize].size, 12.0);+ assert_eq!(cs.styles[n.style as usize].size, 6.0);+ assert!(!cs.styles.iter().any(|s| s.missing_font));+ }++ #[test]+ fn cjk_bunri_does_not_split_double_dash() {+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {+ let (d, sid, _) =+ doc_with("--", Rect::new(0.0, 0.0, 5.0, 100.0), ParaAttrs { composer: Some(composer), bunri_kinshi: Some(true), ..Default::default() });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ }+ }++ #[test]+ fn cjk_custom_kinsoku_disables_selected_breaks() {+ let (mut d, sid, _) = doc_with(+ "甲乙丙丁",+ Rect::new(0.0, 0.0, 25.0, 200.0),+ ParaAttrs {+ composer: Some(designcraft_doc::Composer::SingleLine),+ kinsoku: Some(Some(designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: "乙丙丁".into(), ..Default::default() })),+ ..Default::default()+ },+ );+ d.story_mut(sid).unwrap().format_chars(0.."甲乙丙丁".len(), |f| f.over.size = Some(12.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ }++ #[test]+ fn cjk_center_leading_measures_em_centers_across_different_sizes() {+ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {+ f.over.leading = Some(designcraft_doc::Leading::Points(30.0));+ f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::Center);+ });+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ let center = |l: &Line| {+ let g = &l.glyphs[0];+ let (a, b) = g.face.vertical_metrics();+ l.baseline + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy+ };+ assert!((center(lines[1]) - center(lines[0]) - 30.0).abs() < 1e-6);+ assert!((lines[1].baseline - lines[0].baseline - 30.0).abs() > 0.1);+ }++ #[test]+ fn cjk_em_center_alignment_moves_small_characters() {+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));+ d.story_mut(sid).unwrap().format_chars(1..2, |f| f.over.character_alignment = Some(designcraft_doc::cjk::CharacterAlignment::EmCenter));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = &cs.frames[0].lines[0];+ let center = |g: &PlacedGlyph| {+ let (a, b) = g.face.vertical_metrics();+ g.y + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy+ };+ assert!((center(&line.glyphs[0]) - center(&line.glyphs[1])).abs() < 1e-6);+ }++ #[test]+ fn cjk_hanging_punctuation_uses_frame_edge_without_changing_glyph_size() {+ let k = designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: ",".into(), hanging: ",".into(), ..Default::default() };+ let (mut d, sid, fid) = doc_with(+ "AB,",+ Rect::new(0.0, 0.0, 300.0, 100.0),+ ParaAttrs {+ composer: Some(designcraft_doc::Composer::SingleLine),+ kinsoku: Some(Some(k)),+ kinsoku_hang: Some(designcraft_doc::cjk::KinsokuHang::Regular),+ ..Default::default()+ },+ );+ let initial = compose_story(&d, sid, &ComposeOptions::default());+ let line = &initial.frames[0].lines[0];+ let text_w = line.glyphs.iter().take(2).map(|g| g.adv).sum::<f64>();+ // A fresh frame whose measure fits the letters, but not the comma.+ let frame = d.item_mut(fid).unwrap();+ frame.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, text_w + 1.0, 100.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs).len(), 1);+ assert_eq!(cs.frames[0].lines[0].glyphs.last().unwrap().sx, line.glyphs.last().unwrap().sx);+ }++ #[test]+ fn cjk_fullwidth_space_obeys_the_paragraph_spacing_switch() {+ let text = "A B";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 300.0, 100.0),+ ParaAttrs { word_space_desired: Some(2.0), treat_ideographic_space_as_space: Some(false), ..Default::default() },+ );+ let fixed = compose_story(&d, sid, &ComposeOptions::default());+ d.story_mut(sid).unwrap().paras[0].para.treat_ideographic_space_as_space = Some(true);+ let elastic = compose_story(&d, sid, &ComposeOptions::default());+ let space = fixed.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap().adv;+ assert!((elastic.frames[0].lines[0].end_x - fixed.frames[0].lines[0].end_x - space).abs() < 1e-6);+ }++ #[test]+ fn arabic_bidi_keeps_paragraph_context_across_forced_lines() {+ let text = "مرحبا\u{2028}123 - 456";+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ let mut gs: Vec<_> = lines[1].glyphs.iter().filter(|g| g.len > 0).collect();+ gs.sort_by(|a, b| a.x.total_cmp(&b.x));+ let actual: String = gs.iter().map(|g| text[g.byte..].chars().next().unwrap()).collect();+ let info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));+ let start = text.find('1').unwrap();+ let expected = info.reorder_line(&info.paragraphs[0], start..text.len()).to_string();+ assert_eq!(actual, expected);+ assert_ne!(actual, "123 - 456", "the previous Arabic strong character affects number ordering");+ }++ #[test]+ fn arabic_character_direction_override_survives_line_layout() {+ let text = "abc 123 def";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(4..7, |f| f.over.character_direction = Some(designcraft_doc::arabic::CharacterDirection::RightToLeft));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let line = all_lines(&cs)[0];+ let x = |byte| line.glyphs.iter().find(|g| g.byte == byte).unwrap().x;+ assert!(x(4) > x(5) && x(5) > x(6));+ assert!(x(0) < x(6) && x(4) < x(8));+ }++ #[test]+ fn arabic_fallback_marks_stay_with_bases_and_custom_offsets_move_only_marks() {+ let db = designcraft_fonts::FontDb::global();+ let Some(face) = db.fallback_for('ب', db.face(designcraft_fonts::DEFAULT_FAMILY, "Regular").id(), None) else { return };+ if !face.covers('ُ') {+ return;+ }+ let text = "بُبَ";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert!(plain.iter().all(|g| g.face.id() == face.id()), "fallback must not split Arabic marks into the Latin face");+ assert!(plain.iter().all(|g| g.gid != 0));+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.diacritic_x_offset = Some(200.0);+ f.over.diacritic_y_offset = Some(-100.0);+ });+ let shifted = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ let mut marks = 0;+ for (a, b) in plain.iter().zip(&shifted) {+ assert_eq!(a.gid, b.gid);+ assert_eq!(a.adv, b.adv);+ if face.glyph_is_mark(a.gid) {+ marks += 1;+ assert!((b.x - a.x - 2.4).abs() < 1e-6);+ assert!((b.y - a.y - 1.2).abs() < 1e-6);+ } else {+ assert!((a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6);+ }+ }+ assert!(marks > 0);+ }++ #[test]+ fn arabic_joining_context_crosses_character_style_boundaries() {+ let text = "ببب";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ if plain.iter().any(|g| g.gid == 0) {+ return;+ }+ d.story_mut(sid).unwrap().format_chars(2..4, |f| f.over.fill = Some("Paper".into()));+ let split = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ assert_eq!(plain.iter().map(|g| (g.byte, g.gid)).collect::<Vec<_>>(), split.iter().map(|g| (g.byte, g.gid)).collect::<Vec<_>>());+ }++ #[test]+ fn arabic_character_kashida_switch_prevents_insertion() {+ let text = "بسم الله الرحمن الرحيم الحمد لله رب العالمين";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 160.0, 300.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::RightJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.allow_kashidas = Some(false));+ let off = compose_story(&d, sid, &ComposeOptions::default());+ assert!(all_lines(&off).iter().all(|l| l.glyphs.iter().all(|g| g.len > 0 || g.face.glyph_for('\u{0640}') != g.gid)));+ }++ #[test]+ fn arabic_indic_digit_conversion_retains_original_utf8_ranges() {+ let text = "١٢٣";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.digits = Some(designcraft_doc::Digits::Arabic));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ assert_eq!(gs.iter().map(|g| (g.byte, g.len)).collect::<Vec<_>>(), [(0, 2), (2, 2), (4, 2)]);+ for (g, c) in gs.iter().zip("123".chars()) {+ assert_eq!(g.gid, g.face.glyph_for(c));+ }+ }++ #[test]+ fn arabic_contextual_digits_follow_strong_text_across_style_changes() {+ let text = "ب 12 A 34";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ let arabic_digits = text.find('1').unwrap();+ d.story_mut(sid).unwrap().format_chars(arabic_digits..arabic_digits + 2, |f| f.over.fill = Some("Paper".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ let g = gs.iter().find(|g| g.byte == arabic_digits).unwrap();+ assert_eq!(g.gid, g.face.glyph_for('١'));+ let g = gs.iter().find(|g| g.byte == text.find('3').unwrap()).unwrap();+ assert_eq!(g.gid, g.face.glyph_for('3'));+ }++ #[test]+ fn arabic_story_direction_flows_right_column_first() {+ let text = format!("first{}second", designcraft_doc::story::COLUMN_BREAK);+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert_eq!(lines.len(), 2);+ assert!(lines[0].x0 > lines[1].x0);+ assert!(cs.frames[0].columns[0].x0 > cs.frames[0].columns[1].x0);+ }++ #[test]+ fn arabic_rtl_table_keeps_logical_indices_and_merged_cell_hit_testing() {+ let mut t = designcraft_doc::Table::new(987, 2, 3, 0, 0, 240.0);+ t.options.direction = designcraft_doc::TextDirection::RightToLeft;+ t.cell_mut(0, 0).unwrap().text = designcraft_doc::Story::with_text(StoryId(0), "Right", ParaFormat::default());+ t.cell_mut(0, 2).unwrap().text = designcraft_doc::Story::with_text(StoryId(0), "Left", ParaFormat::default());+ t.merge(designcraft_doc::CellRange::new(1, 0, 1, 1)).unwrap();+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 400.0), t);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let (_, _, right) = table::find_cell(&cs, 987, 0, 0).unwrap();+ let (_, _, left) = table::find_cell(&cs, 987, 0, 2).unwrap();+ assert!(right.rect.x0 > left.rect.x0);+ let (_, _, merged) = table::find_cell(&cs, 987, 1, 0).unwrap();+ assert!((merged.rect.width() - 160.0).abs() < 1e-6);+ assert_eq!(table::hit_cell(&cs, 0, right.rect.center()).map(|(_, r, c, _)| (r, c)), Some((0, 0)));+ }++ #[test]+ fn arabic_kashida_moves_marks_with_their_cluster_and_respects_nonjoiners() {+ let text = "بُسْمِ بُسْمِ";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 180.0, 100.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ let with = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ if with.iter().any(|g| g.gid == 0) {+ return;+ }+ assert!(with.iter().any(|g| g.len == 0 && g.gid == g.face.glyph_for('\u{0640}')));+ d.story_mut(sid).unwrap().paras[0].para.kashidas = Some(false);+ let without = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();+ for (a, b) in with.iter().zip(&without) {+ assert_eq!((a.gid, a.byte), (b.gid, b.byte));+ let first_a = with.iter().find(|g| g.byte == a.byte).unwrap();+ let first_b = without.iter().find(|g| g.byte == b.byte).unwrap();+ assert!(((a.x - first_a.x) - (b.x - first_b.x)).abs() < 1e-6, "marks detached from their cluster");+ }+ let text = "ب\u{200C}ب ب\u{200C}ب";+ let (mut d, sid, _) = doc_with(+ text,+ Rect::new(0.0, 0.0, 180.0, 100.0),+ ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },+ );+ d.settings.glyph_fallback = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].lines[0].glyphs.iter().all(|g| g.gid != g.face.glyph_for('\u{0640}') || g.len > 0));+ }++ #[test]+ fn arabic_explicit_isolated_forms_disable_contextual_joining() {+ let text = "بب";+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 180.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.positional_form = Some("Isolated".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ for g in gs {+ assert_eq!(g.gid, g.face.glyph_for('ب'));+ }+ }++ #[test]+ fn arabic_character_overrides_mirror_brackets_using_final_levels() {+ use designcraft_doc::arabic::CharacterDirection as D;+ for (text, direction, mirrored) in [("(123)", D::RightToLeft, true), ("(ب)", D::LeftToRight, false)] {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.character_direction = Some(direction));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gs = &cs.frames[0].lines[0].glyphs;+ for (byte, ch) in [(0, '('), (text.len() - 1, ')')] {+ let g = gs.iter().find(|g| g.byte == byte).unwrap();+ let expected = if mirrored { unicode_bidi_mirroring::get_mirrored(ch).unwrap() } else { ch };+ assert_eq!(g.gid, g.face.glyph_for(expected), "{text:?} {direction:?} byte {byte}");+ }+ }+ }++ #[test]+ fn language_picks_localized_forms_through_the_word_cache() {+ // Source Serif 4 has a Turkish `locl` form of `i`; the same words in English and Turkish+ // (both shaped word by word through the cache) keep their own forms.+ let text = "in in in in";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 500.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(6..text.len(), |f| f.over.language = Some("Turkish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let gid_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.gid).unwrap();+ assert_eq!(gid_at(0), gid_at(3), "English i");+ assert_eq!(gid_at(6), gid_at(9), "Turkish i");+ assert_ne!(gid_at(0), gid_at(6), "Turkish i takes its localized form");+ // A single word is shaped directly, in its language too.+ let (mut d, sid, _) = doc_with("i", Rect::new(36.0, 36.0, 500.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.language = Some("Turkish".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(all_lines(&cs)[0].glyphs[0].gid, gid_at(6), "Turkish i, shaped on its own");+ }++ #[test]+ fn chinese_and_japanese_take_their_localized_forms() {+ // Noto Sans CJK SC (craft-fonts) draws 直 differently for Japanese (`locl`).+ let Some(noto) = designcraft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC") else { return };+ FontDb::global().add_font(noto.bytes.to_vec());+ let gid = |language: &str| {+ let (mut d, sid, _) = doc_with("直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0.."直".len(), |f| {+ f.over.font_family = Some(noto.family.into());+ f.over.language = Some(language.into());+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let g = &all_lines(&cs)[0].glyphs[0];+ assert_eq!(g.face.family, noto.family);+ g.gid+ };+ let chinese = gid("Chinese: Simplified");+ assert_eq!(chinese, FontDb::global().face(noto.family, noto.style).glyph_for('直'));+ assert_ne!(gid("Japanese"), chinese, "Japanese 直");+ }++ #[test]+ fn cjk_fallback_follows_the_language() {+ use designcraft_fonts::testing::font_with;+ // Stand-ins for Hiragino Mincho ProN (the Japanese chain's first system font) and Songti SC+ // (first in the Simplified Chinese chain); the real ones when installed.+ let db = designcraft_fonts::FontDb::global();+ db.add_font(font_with("Hiragino Mincho ProN", &['直']).unwrap());+ db.add_font(font_with("Songti SC", &['直']).unwrap());+ // (face of the Latin letter, face of the ideograph)+ let faces_of = |language: &str| {+ let (mut d, sid, _) = doc_with("a直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.language = Some(language.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let face_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.face).unwrap();+ (face_at(0), face_at(1))+ };+ assert_eq!(faces_of("Chinese: Simplified").1.family, "Songti SC");+ // Japanese: the craft-fonts faces lead the chain (Mincho first), then the system fonts.+ let japanese = designcraft_fonts::japanese_document_fonts().first().map_or("Hiragino Mincho ProN", |f| f.family);+ assert_eq!(faces_of("Japanese").1.family, japanese);+ // Without a CJK language, the language-blind search.+ let (primary, han) = faces_of("English: USA");+ assert_eq!(Some(han.family.clone()), db.fallback_for('直', primary.id(), None).map(|f| f.family.clone()));+ }++ #[test]+ fn missing_glyphs_are_the_fonts_box_unless_fallback_is_on() {+ use designcraft_fonts::testing::font_with;+ // Some font draws 語 when fallback fonts are allowed (a system CJK font, or this stand-in).+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Missing Glyph Helper", &['語']).unwrap());+ let text = "a語";+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.language = Some("Japanese".into()));+ let glyph_at = |d: &Document, byte: usize| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| (g.face, g.gid, g.adv)).unwrap()+ };+ assert!(!d.settings.glyph_fallback, "new documents draw missing glyphs as InDesign does");+ let (face, gid, adv) = glyph_at(&d, 1);+ assert_eq!((face.family.as_str(), gid), (designcraft_fonts::DEFAULT_FAMILY, 0), "Source Serif 4's .notdef");+ assert!((adv - face.advance(0) * 12.0 / face.upem).abs() < 1e-6, "its advance: {adv}");+ d.settings.glyph_fallback = true;+ let (face, gid, _) = glyph_at(&d, 1);+ assert_ne!(face.family, designcraft_fonts::DEFAULT_FAMILY);+ assert_ne!(gid, 0, "a fallback font draws it");+ }++ #[test]+ fn kenten_missing_from_the_font_are_its_box_unless_fallback_is_on() {+ use designcraft_fonts::testing::font_with;+ // Some font draws the sesame dot when fallback fonts are allowed (a system font, or this one).+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Kenten Helper", &['\u{FE45}']).unwrap());+ let (mut d, sid, _) = doc_with("ab", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.kenten = Some(true));+ let marks = |d: &Document| {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs[plain..].iter().map(|g| (g.face.family.clone(), g.gid)).collect::<Vec<_>>()+ };+ let missing = marks(&d);+ assert_eq!(missing.len(), 2);+ assert!(missing.iter().all(|(family, gid)| family == designcraft_fonts::DEFAULT_FAMILY && *gid == 0), "{missing:?}");+ d.settings.glyph_fallback = true;+ let drawn = marks(&d);+ assert_eq!(drawn.len(), 2);+ assert!(drawn.iter().all(|(family, gid)| family != designcraft_fonts::DEFAULT_FAMILY && *gid != 0), "{drawn:?}");+ }++ #[test]+ fn each_document_shapes_words_in_its_own_fonts() {+ use designcraft_fonts::testing::font_with_glyph;+ const FAMILY: &str = "DocFont Word Cache";+ // Two documents' fonts of one name: the same words, drawn as `X` in one and `O` in the other.+ let root = std::env::temp_dir().join(format!("dc-compose-docfonts-{}", std::process::id()));+ let mut scopes = Vec::new();+ for (name, glyph) in [("x", 'X'), ("o", 'O')] {+ let folder = root.join(name);+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("word.ttf"), font_with_glyph(FAMILY, &['a', 'b', ' '], glyph).unwrap()).unwrap();+ scopes.push((designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope, glyph));+ }+ let text = "ab ab ab ab";+ let mut faces = Vec::new();+ for (scope, glyph) in scopes {+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());+ d.font_scope = scope;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyphs: Vec<&PlacedGlyph> =+ all_lines(&cs).into_iter().flat_map(|l| l.glyphs.iter()).filter(|g| text[g.byte..].starts_with('a')).collect();+ assert_eq!(glyphs.len(), 4);+ let face = glyphs[0].face;+ let drawn = designcraft_fonts::FontDb::global().face(designcraft_fonts::FALLBACK_FAMILY, "Regular").glyph_for(glyph);+ assert!(glyphs.iter().all(|g| g.face == face && g.gid == drawn), "scope {scope}: {glyph}");+ faces.push(face);+ }+ assert!(faces[0] != faces[1] && faces.iter().all(|f| f.family == FAMILY));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn composite_fonts_draw_from_the_documents_fonts() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ use designcraft_fonts::testing::font_with_glyph;+ const FAMILY: &str = "DocFont Composite Member";+ // A composite font whose digits come from a font only the document has.+ let folder = std::env::temp_dir().join(format!("dc-compose-composite-docfont-{}", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("digits.ttf"), font_with_glyph(FAMILY, &['1'], 'X').unwrap()).unwrap();+ let scope = FontDb::global().load_document_fonts(&folder).scope;+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());+ d.font_scope = scope;+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: designcraft_fonts::DEFAULT_FAMILY.into(), ..Default::default() },+ CompositeFontEntry { characters: "0123456789".into(), family: FAMILY.into(), ..Default::default() },+ ],+ });+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let digit = cs.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();+ assert_eq!(digit.face.family, FAMILY);+ assert_ne!(digit.gid, 0);+ assert!(!cs.styles.iter().any(|s| s.missing_font), "the document's font isn't missing");+ let _ = std::fs::remove_dir_all(&folder);+ }++ const KO_WORDS: &str = "한국어 문장은 띄어쓰기 단위로 줄을 바꿉니다 한국어 문장은 띄어쓰기 단위로 줄을 바꿉니다";+ const KO_HANJA: &str = "大韓民國 憲法은 國民의 權利를 保障한다 大韓民國 憲法은 國民의 權利를 保障한다";+ const KO_PUNCT: &str = "가나다라마。바사아자차」카타파하가、나다라마바。사아자차카」타파하가나、다라마바사。아자차카타」파하가나다、";+ /// Syllables for words wider than the frame.+ const KO_LONG: &str = "가나다라마바사아자차카타파하」";++ /// A Korean paragraph in a narrow frame (70 pt), set in a stand-in font covering the samples.+ fn korean_doc(text: &str, language: &str, para: ParaAttrs) -> (Document, StoryId) {+ let chars: Vec<char> = [KO_WORDS, KO_HANJA, KO_PUNCT, KO_LONG].concat().chars().collect();+ let font = designcraft_fonts::testing::font_with("DC Test Korean", &chars).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 106.0, 400.0), para);+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some("DC Test Korean".into());+ f.over.language = Some(language.into());+ });+ (d, sid)+ }++ /// The lines (after the first) that start inside a space-separated word.+ fn lines_starting_mid_word(d: &Document, sid: StoryId, text: &str) -> Vec<String> {+ let cs = compose_story(d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 2, "wraps: {} lines", lines.len());+ lines.iter().skip(1).filter(|l| !text[..l.range.start].ends_with(' ')).map(|l| text[l.range.clone()].to_string()).collect()+ }++ #[test]+ fn korean_breaks_at_spaces() {+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), ..Default::default() };+ // By script: Hangul is set word by word whatever the language.+ for language in ["Korean", "English: USA"] {+ let (d, sid) = korean_doc(KO_WORDS, language, para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_WORDS);+ assert!(mid.is_empty(), "{composer:?} {align:?} {language}: {mid:?}");+ }+ }+ }+ }++ #[test]+ fn korean_breaks_at_spaces_under_a_kinsoku_set() {+ let set = designcraft_doc::cjk::Kinsoku::named("KoreanKinsoku");+ assert!(set.is_some());+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ let para = ParaAttrs { composer: Some(composer), kinsoku: Some(set.clone()), ..Default::default() };+ let (d, sid) = korean_doc(KO_WORDS, "Korean", para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_WORDS);+ assert!(mid.is_empty(), "{composer:?}: {mid:?}");+ let (d, sid) = korean_doc(KO_WORDS, "Korean", ParaAttrs { korean_char_breaks: Some(true), ..para });+ assert!(!lines_starting_mid_word(&d, sid, KO_WORDS).is_empty(), "{composer:?}: breaks between syllables on request");+ }+ }++ #[test]+ fn korean_character_breaks_on_request() {+ let para = ParaAttrs { korean_char_breaks: Some(true), composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_WORDS, "Korean", para);+ assert!(!lines_starting_mid_word(&d, sid, KO_WORDS).is_empty(), "breaks between syllables");+ }++ #[test]+ fn korean_by_its_locale_code_breaks_at_spaces() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_HANJA, "ko_KR", para);+ let mid = lines_starting_mid_word(&d, sid, KO_HANJA);+ assert!(mid.is_empty(), "{mid:?}");+ }++ #[test]+ fn hanja_in_korean_text_breaks_at_spaces() {+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), ..Default::default() };+ let (d, sid) = korean_doc(KO_HANJA, "Korean", para.clone());+ let mid = lines_starting_mid_word(&d, sid, KO_HANJA);+ assert!(mid.is_empty(), "{mid:?}");+ // Han in Japanese text breaks between characters.+ let (d, sid) = korean_doc(KO_HANJA, "Japanese", para);+ assert!(!lines_starting_mid_word(&d, sid, KO_HANJA).is_empty());+ }++ #[test]+ fn korean_lines_keep_kinsoku() {+ // Words of 9 to 14 syllables and a closing bracket: in one of them the bracket is what+ // overflows the frame.+ let syllables: Vec<char> = KO_LONG.chars().collect();+ let long = (9..=14).map(|n| format!("{}」 가나", syllables[..n].iter().collect::<String>()));+ for text in std::iter::once(KO_PUNCT.to_string()).chain(long) {+ let text = text.as_str();+ for char_breaks in [false, true] {+ for composer in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] {+ let para = ParaAttrs { korean_char_breaks: Some(char_breaks), composer: Some(composer), ..Default::default() };+ let (d, sid) = korean_doc(text, "Korean", para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 1, "wraps");+ let texts: Vec<&str> = lines.iter().map(|l| &text[l.range.clone()]).collect();+ assert!(texts.iter().all(|t| !t.starts_with(['、', '。', '」'])), "kinsoku ({char_breaks}, {composer:?}): {texts:?}");+ }+ }+ }+ }++ /// A synthetic font for vertical text: Source Sans 3 glyphs (CJK characters drawn as Latin ones)+ /// with vertical metrics, every glyph one em down the line and 120 units below its vertical+ /// origin, except ヸ (drawn as O): 1.024 em. No vertical forms. Added to the global database once.+ fn vertical_test_font() -> &'static str {+ use designcraft_fonts::testing::{font_mapping, with_vmtx};+ const FAMILY: &str = "DC Test Vertical";+ static ADDED: std::sync::Once = std::sync::Once::new();+ ADDED.call_once(|| {+ let glyphs = [('一', 'X'), ('二', 'X'), ('日', 'X'), ('本', 'X'), ('ま', 'o'), ('ヸ', 'O'), ('、', ','), ('A', 'A'), ('b', 'b')];+ let base = font_mapping(FAMILY, &glyphs).unwrap();+ let scratch = designcraft_fonts::FontDb::with_font_dirs(vec![]);+ scratch.add_font(base.clone());+ let wi = u16::try_from(scratch.face(FAMILY, "Regular").glyph_for('ヸ')).unwrap();+ designcraft_fonts::FontDb::global().add_font(with_vmtx(&base, (1000, 120), &[(wi, 1024, 100)]).unwrap());+ });+ FAMILY+ }++ /// Shippori Mincho (vertical forms, `vpal`) when built with craft-fonts; else `None`, with a note.+ fn shippori() -> Option<&'static str> {+ if !designcraft_fonts::japanese_fonts().any(|f| f.family == "Shippori Mincho") {+ eprintln!("skipped Shippori Mincho: built without craft-fonts (set CRAFT_FONTS_DIR to a checkout)");+ return None;+ }+ Some("Shippori Mincho")+ }++ /// The fonts vertical layout is checked in: the synthetic one, and Shippori Mincho with craft-fonts.+ fn vertical_families() -> Vec<&'static str> {+ std::iter::once(vertical_test_font()).chain(shippori()).collect()+ }++ /// A vertical frame (no inset) with `text` in `family` at 20 pt (and `over`), and its first line+ /// with the frame's first column.+ fn vertical_line(family: &str, text: &str, over: impl Fn(&mut designcraft_doc::CharFormat)) -> (Line, Rect) {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 500.0), lid, text, ParaFormat::default()).unwrap();+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {+ tf.options.inset = [0.0; 4];+ }+ d.story_mut(sid).unwrap().vertical = true;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some(family.into());+ f.over.size = Some(20.0);+ over(f);+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ assert!(ft.vertical);+ let line = ft.lines[0].clone();+ assert!(line.glyphs.iter().all(|g| g.face.family == family), "{family}: {:?}", line.glyphs.iter().map(|g| &g.face.family).collect::<Vec<_>>());+ (line, ft.columns[0])+ }++ /// Text-space bounds of a glyph's ink as drawn in a vertical frame.+ fn vertical_ink(g: &PlacedGlyph, baseline: f64) -> Rect {+ use designcraft_geom::{Affine, Shape};+ let ink = designcraft_fonts::FontDb::global().outline(&g.face, g.gid).bounding_box();+ let mut a = Affine::translate((g.x, baseline + g.y)) * Affine::scale_non_uniform(g.sx, g.sy);+ if let Some(turn) = g.vertical_xf(baseline) {+ a = turn * a;+ }+ a.transform_rect_bbox(ink)+ }++ /// The em box in text space: along the line from x (page down), across from its top (text -y,+ /// page right) to its bottom → (right, left, centre).+ fn em_across(l: &Line, g: &PlacedGlyph) -> (f64, f64, f64) {+ let (top, bottom) = g.face.em_box();+ let right = l.baseline + g.y - top * g.sy;+ let left = l.baseline + g.y - bottom * g.sy;+ (right, left, (right + left) / 2.0)+ }++ #[test]+ fn upright_glyphs_hang_on_the_line_centre() {+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "一", |_| {});+ let ichi = &l.glyphs[0];+ assert!(ichi.upright, "{family}");+ // An ideograph is centred across the line and inside its em along it.+ let (_, _, centre) = em_across(&l, ichi);+ let ink = vertical_ink(ichi, l.baseline);+ assert!(((ink.y0 + ink.y1) / 2.0 - centre).abs() < 0.05 * 20.0, "{family}: {ink:?} {centre}");+ assert!(ink.x0 > ichi.x && ink.x1 < ichi.x + ichi.adv, "{family}: {ink:?}");+ }+ // The synthetic glyph's top is its top side bearing (120 units) below its vertical origin.+ let (l, _) = vertical_line(vertical_test_font(), "一", |_| {});+ let ink = vertical_ink(&l.glyphs[0], l.baseline);+ assert!((ink.x0 - l.glyphs[0].x - 2.4).abs() < 1e-6, "{ink:?} {}", l.glyphs[0].x);+ }++ #[test]+ fn upright_punctuation_takes_its_vertical_form_and_place() {+ // A font with vertical forms: Shippori Mincho.+ let Some(family) = shippori() else { return };+ let (l, _) = vertical_line(family, "一、", |_| {});+ let comma = &l.glyphs[1];+ assert!(comma.upright);+ assert_ne!(comma.gid, comma.face.glyph_for('、'), "vertical form (vert)");+ let (right, _, centre) = em_across(&l, comma);+ // The comma's ink sits in the upper right quarter of its em box on the page.+ let ink = vertical_ink(comma, l.baseline);+ assert!(ink.x0 >= comma.x - 1e-6 && ink.x1 < comma.x + comma.adv / 2.0, "upper half: {ink:?} {} {}", comma.x, comma.adv);+ assert!(ink.y0 >= right - 1e-6 && ink.y1 < centre, "right half: {ink:?} {right} {centre}");+ }++ #[test]+ fn latin_in_vertical_text_turns_as_a_run() {+ // Shippori Mincho's `vrt2` has turned Latin forms; a turned run must not use them.+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "日本Ab", |_| {});+ let latin: Vec<_> = l.glyphs.iter().filter(|g| g.byte >= "日本".len()).collect();+ let face = latin[0].face;+ assert_eq!(latin.iter().map(|g| g.gid).collect::<Vec<_>>(), [face.glyph_for('A'), face.glyph_for('b')], "{family}");+ assert!(latin.iter().all(|g| !g.upright && g.vertical_xf(l.baseline).is_none()), "{family}");+ assert!((latin[0].adv - face.advance(latin[0].gid) * latin[0].sx).abs() < 1e-9, "{family}: horizontal advance");+ }+ }++ #[test]+ fn upright_glyphs_advance_by_their_vertical_metrics() {+ // ヸ is 1.024 em tall in both fonts.+ for family in vertical_families() {+ let (l, _) = vertical_line(family, "一ヸ一", |_| {});+ let g = &l.glyphs;+ assert_eq!(g[1].face.v_advance(g[1].gid), 1024.0, "{family}");+ assert!((g[1].x - g[0].x - 20.0).abs() < 1e-9, "{family}");+ assert!((g[2].x - g[1].x - 20.48).abs() < 1e-9, "{family}: {} {}", g[1].x, g[2].x);+ }+ let Some(family) = shippori() else { return };+ // Shippori's ヸ is an em wide.+ let (l, _) = vertical_line(family, "ヸ", |_| {});+ assert_eq!(l.glyphs[0].face.advance(l.glyphs[0].gid), 1000.0);+ // Proportional vertical metrics (`vpal`): ま takes 0.974 em.+ let (l, _) = vertical_line(family, "まま", |f| f.over.otf_features = Some(vec!["vpal".into()]));+ assert!((l.glyphs[1].x - l.glyphs[0].x - 19.48).abs() < 1e-9, "{:?}", l.glyphs.iter().map(|g| g.x).collect::<Vec<_>>());+ let (l, _) = vertical_line(family, "まま", |_| {});+ assert!((l.glyphs[1].x - l.glyphs[0].x - 20.0).abs() < 1e-9);+ }++ #[test]+ fn vertical_lines_fit_the_em_box() {+ // First baseline at the ascent: an upright line's ascent is its em box top, so the em box+ // touches the frame's right edge. The synthetic font's em box is Source Sans 3's BASE one+ // (0.83 em, -0.17 em); Shippori Mincho's its OS/2 typo metrics (0.88 em, -0.12 em).+ let expected = [(vertical_test_font(), 16.6, 3.4)].into_iter().chain(shippori().map(|f| (f, 17.6, 2.4)));+ for (family, ascent, descent) in expected {+ let (l, col) = vertical_line(family, "一二", |_| {});+ assert!((l.ascent - ascent).abs() < 1e-9 && (l.descent - descent).abs() < 1e-9, "{family}: {} {}", l.ascent, l.descent);+ assert!((l.baseline - col.y0 - ascent).abs() < 1e-9, "{family}: {} {}", l.baseline, col.y0);+ }+ }diff --cc crates/doc/src/edit.rsindex ed6ace82e,188f514d2..7ca89e3e2--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@@ -214,64 -265,12 +214,70 @@@ impl Documentlet st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);st.frames.insert(at, to);+ st.rev += 1;let it = self.item_mut(to).ok_or(DocError::NoItem(to))?;it.content = Content::Text(TextFrame { story: fs, options: TextFrameOptions::default() });- }- if let Some(st) = self.story_mut(fs) {+ return Ok(());+ };+ let mut other = Arc::unwrap_or_clone(self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?);+ // Frames of the other story from `to` on follow along; frames before it are left as an empty new story.+ let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);+ let after = other.frames.split_off(pos_to);+ let before = std::mem::take(&mut other.frames);++ let (vertical, direction) = (other.vertical, other.direction);+ {+ let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;++ // The story keeps its own direction, even when it was empty and takes the other's text.++ let own = (st.vertical, st.direction);+ st.append_story(other);++ (st.vertical, st.direction) = own;+ let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);+ for (k, f) in after.iter().enumerate() {+ st.frames.insert(at + k, *f);+ }st.rev += 1;}+ for f in &after {+ if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {+ t.story = fs;+ }+ }+ if !before.is_empty() {+ let nid = StoryId(self.alloc());+ let mut ns = Story::new(nid);+ ns.frames = before.clone();++ ns.vertical = vertical;++ ns.direction = direction;+ for f in &before {+ if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {+ t.story = nid;+ }+ }+ self.stories.insert(nid, Arc::new(ns));+ }+ Ok(())+ }++ /// [`Document::thread`], except that an empty `from` alone in its story, threaded in front of+ /// the first frame of `to`'s story, joins that story: the story with the text keeps its id+ /// (and whatever refers to it).+ pub fn thread_keeping_story(&mut self, from: ItemId, to: ItemId) -> Result<()> {+ let fs = self.frame_story(from)?;+ let from_empty = fs.is_none_or(|fs| self.story(fs).is_some_and(|s| s.text.is_empty() && s.frames == [from]));+ let ts = self.frame_story(to)?;+ let to_first = ts.and_then(|ts| self.story(ts)).is_some_and(|s| s.frames.first() == Some(&to));+ let (Some(ts), true, true) = (ts, from_empty, to_first && from != to) else { return self.thread(from, to) };+ if let Some(fs) = fs {+ self.stories.remove(&fs);+ }+ let st = self.story_mut(ts).ok_or(DocError::NoStory(ts))?;+ st.frames.insert(0, from);+ st.rev += 1;+ let it = self.item_mut(from).ok_or(DocError::NoItem(from))?;+ match it.text_frame_mut() {+ Some(t) => t.story = ts,+ None => it.content = Content::Text(TextFrame { story: ts, options: TextFrameOptions::default() }),+ }Ok(())}@@@ -353,27 -302,6 +361,30 @@@Ok(())}+ /// Take `frame` out of its thread: the frames before and after it join up and keep the text,+ /// `frame` stays on the page with a new empty story.+ pub fn remove_from_thread(&mut self, frame: ItemId) -> Result<()> {+ let sid = self.item(frame).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(frame))?;- {++ let (vertical, direction) = {+ let st = self.story_mut(sid).ok_or(DocError::NoStory(sid))?;+ if st.frames.len() < 2 {+ return Err(DocError::Invalid(format!("frame {frame} is not threaded to another frame")));+ }+ st.frames.retain(|f| *f != frame);+ st.rev += 1;- }++ (st.vertical, st.direction)++ };+ let nid = StoryId(self.alloc());+ let mut ns = Story::new(nid);+ ns.frames = vec![frame];++ ns.vertical = vertical;++ ns.direction = direction;+ self.stories.insert(nid, Arc::new(ns));+ let t = self.item_mut(frame).and_then(Item::text_frame_mut).ok_or(DocError::NoItem(frame))?;+ t.story = nid;+ Ok(())+ }+/// Next / previous frame in a thread.pub fn next_frame(&self, frame: ItemId) -> Option<ItemId> {let st = self.story(self.item(frame)?.text_frame()?.story)?;diff --cc crates/doc/src/tests.rsindex e248d72eb,9ee28a139..fca520ed8--- a/crates/doc/src/tests.rs+++ b/crates/doc/src/tests.rs@@@ -42,98 -42,58 +42,150 @@@ fn thread_to_empty_frame_converts_it()assert!(d.thread(a, a).is_err());}+#[test]+fn threading_merges_tables_notes_and_endnotes() {+ let mut d = doc();+ let lid = d.default_layer();+ let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "first", ParaFormat::default()).unwrap();+ let (b, sb) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "second", ParaFormat::default()).unwrap();+ for (sid, note) in [(sa, "Note A"), (sb, "Note B")] {+ let st = d.story_mut(sid).unwrap();+ st.insert_note(3, note, ParaFormat::default());+ // Both stories hold a table with id 1.+ let n = st.len();+ st.insert_table(n, crate::table::Table::new(1, 2, 2, 0, 0, 80.0));+ }+ let st = d.story_mut(sb).unwrap();+ st.insert_endnote(2, "End B", ParaFormat::default());+ st.insert(1, &crate::NOTE_MARK.to_string());+ d.thread(a, b).unwrap();+ d.check().unwrap();+ let st = d.story(sa).unwrap();+ assert!(d.story(sb).is_none());+ assert_eq!(st.tables.len(), 2);+ assert_eq!(st.notes.len(), 2);+ assert_eq!(st.notes[1].text.text, "Note B");+ assert_eq!(st.endnotes.len(), 1);+ assert_eq!(st.endnotes[0].text.text, "End B");+ assert_eq!(st.editorial.len(), 1);+}++#[test]+fn empty_frame_threaded_before_a_story_joins_it_at_the_front() {+ let mut d = doc();+ let lid = d.default_layer();+ let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "", ParaFormat::default()).unwrap();+ let (b, sb) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();+ d.thread_keeping_story(a, b).unwrap();+ d.check().unwrap();+ assert!(d.story(sa).is_none());+ let st = d.story(sb).unwrap();+ assert_eq!(st.frames, vec![a, b]);+ assert_eq!(st.text, "Hello");+}++#[test]+fn empty_story_takes_the_threaded_text_without_a_blank_paragraph() {+ let mut d = doc();+ let lid = d.default_layer();+ let (a, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "", ParaFormat::default()).unwrap();+ let (a2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 110.0, 100.0, 200.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, a2).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();+ d.thread(a2, b).unwrap();+ d.check().unwrap();+ let st = d.story(d.item(a).unwrap().text_frame().unwrap().story).unwrap();+ assert_eq!(st.frames, vec![a, a2, b]);+ assert_eq!(st.text, "Hello");+}++#[test]+fn threading_from_an_empty_frame_makes_it_a_text_frame() {+ let mut d = doc();+ let lid = d.default_layer();+ let id = ItemId(d.alloc());+ let it = Item::new(id, lid, Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 200.0, 50.0, 300.0)));+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();+ d.thread(id, b).unwrap();+ d.check().unwrap();+ let st = d.story(d.item(id).unwrap().text_frame().unwrap().story).unwrap();+ assert_eq!(st.frames, vec![id, b]);+ assert_eq!(st.text, "Hello");+}++#[test]+fn removing_a_frame_from_its_thread_keeps_the_text_in_the_others() {+ let mut d = doc();+ let lid = d.default_layer();+ let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "words", ParaFormat::default()).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "", ParaFormat::default()).unwrap();+ let (c, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(210.0, 10.0, 300.0, 100.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, b).unwrap();+ d.thread(b, c).unwrap();+ d.remove_from_thread(b).unwrap();+ d.check().unwrap();+ assert_eq!(d.story(sa).unwrap().frames, vec![a, c]);+ assert_eq!(d.story(sa).unwrap().text, "words");+ let own = d.item(b).unwrap().text_frame().unwrap().story;+ assert_ne!(own, sa);+ assert!(d.story(own).unwrap().text.is_empty());+ // A frame alone in its story has no thread to leave.+ assert!(d.remove_from_thread(b).is_err());+}++ #[test]+ fn frames_keep_their_story_direction_through_threading() {+ let mut d = doc();+ let lid = d.default_layer();+ let r = |x: f64| Rect::new(x, 10.0, x + 50.0, 100.0);+ let vertical = |d: &Document, f: ItemId| d.item(f).is_some_and(|i| d.frame_vertical(i));+ let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), r(0.0), lid, "縦", ParaFormat::default()).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), r(60.0), lid, "", ParaFormat::default()).unwrap();+ d.story_mut(sa).unwrap().vertical = true;+ // A horizontal frame threaded onto a vertical story turns vertical.+ d.thread(a, b).unwrap();+ assert!(vertical(&d, a) && vertical(&d, b));+ // Threading the vertical story's second frame after a horizontal frame: it turns horizontal,+ // and the frame left before it stays vertical.+ let (h, _) = d.add_text_frame(SpreadRef::Doc(0), r(120.0), lid, "横", ParaFormat::default()).unwrap();+ d.thread(h, b).unwrap();+ assert!(vertical(&d, a) && !vertical(&d, b) && !vertical(&d, h));+ // Breaking a vertical thread leaves the frames after the break vertical.+ let (c, _) = d.add_text_frame(SpreadRef::Doc(0), r(180.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, c).unwrap();+ d.unthread_after(a).unwrap();+ assert!(vertical(&d, a) && vertical(&d, c));+ assert_ne!(d.item(c).unwrap().text_frame().unwrap().story, sa);+ d.check().unwrap();+ }++ #[test]+ fn frames_keep_their_column_direction_through_threading() {+ use crate::TextDirection::{LeftToRight, RightToLeft};+ let mut d = doc();+ let lid = d.default_layer();+ let r = |x: f64| Rect::new(x, 10.0, x + 50.0, 100.0);+ let direction = |d: &Document, f: ItemId| d.story(d.item(f).unwrap().text_frame().unwrap().story).unwrap().direction;+ let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), r(0.0), lid, "نص", ParaFormat::default()).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), r(60.0), lid, "", ParaFormat::default()).unwrap();+ d.story_mut(sa).unwrap().direction = RightToLeft;+ d.thread(a, b).unwrap();+ assert_eq!((direction(&d, a), direction(&d, b)), (RightToLeft, RightToLeft));+ // Threading the right-to-left story's second frame after a left-to-right frame: the frame+ // left before it stays right to left.+ let (h, _) = d.add_text_frame(SpreadRef::Doc(0), r(120.0), lid, "abc", ParaFormat::default()).unwrap();+ d.thread(h, b).unwrap();+ assert_eq!((direction(&d, a), direction(&d, b), direction(&d, h)), (RightToLeft, LeftToRight, LeftToRight));+ // Breaking a right-to-left thread leaves the frames after the break right to left.+ let (c, _) = d.add_text_frame(SpreadRef::Doc(0), r(180.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, c).unwrap();+ d.unthread_after(a).unwrap();+ assert_ne!(d.item(c).unwrap().text_frame().unwrap().story, sa);+ assert_eq!((direction(&d, a), direction(&d, c)), (RightToLeft, RightToLeft));+ d.check().unwrap();+ }+#[test]fn removing_last_frame_deletes_story() {let mut d = doc();diff --cc crates/engine/src/cmd/text.rsindex d6c79d0c3,a75d6d473..717b30414--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -682,11 -628,26 +728,21 @@@ fn move_caret(s: &mut Session, p: &Valulet t = st.selection.text.ok_or_else(|| bad("text.move", "no caret"))?;let story = st.doc.text_story(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?;let text = story.text.clone();- let cs = s.cache.get(&st.doc, t.story, None);// In a cell, lines come from the cell's own composition.- let cs = match t.cell {- Some(c) if c.footnote_id().is_some() => compose::find_note(&cs, c.row as u64).map(|(_, n)| n.text.clone()).unwrap_or(cs),- Some(c) => compose::find_cell(&cs, c.table, c.row, c.col).map(|(_, _, pc)| pc.text.clone()).unwrap_or(cs),- None => cs,- };+ let cs = text_composition(s.cache.get(&st.doc, t.story, None), t.cell);let pos = t.focus.min(text.len());+ // Vertical lines run top to bottom and follow each other right to left: Down and Up move along+ // the line (Right and Left of horizontal text), Left and Right to the next and previous line.+ let vertical_text = compose::caret(&cs, pos).and_then(|(fi, ..)| cs.frames.get(fi)).is_some_and(|f| f.vertical);+ let dir = match (vertical_text, dir.as_str()) {+ (true, "down") => "right",+ (true, "up") => "left",+ (true, "left") => "down",+ (true, "right") => "up",+ (_, d) => d,+ };let collapse_to = |left: bool| if left { t.range().start } else { t.range().end };- let new = match dir.as_str() {+ let new = match dir {"left" if !extend && !t.is_caret() => collapse_to(true),"right" if !extend && !t.is_caret() => collapse_to(false),"left" | "right" => {@@@ -957,62 -880,6 +1013,63 @@@ fn selection_attrs(s: &mut Session, _p"paraOverrides": pf.para.count(), "charOverrides": cf.over.count()}))}+fn apply_typing_format(cf: &mut designcraft_doc::CharFormat, f: &TypingFormat) {+ cf.over.merge(&f.attrs);+ for k in &f.cleared {+ let _ = cf.over.set_json(k, &Value::Null);+ }+}++/// Bold (`bold`) or italic from the font family (style linking), per run of the selection: on or+/// off as asked, else the opposite of the first selected character.+fn link_style(s: &mut Session, p: &Value, bold: bool) -> Result<Value> {+ let id = if bold { "type.bold" } else { "type.italic" };+ let cur = selection_attrs(s, &json!({}))?;+ let family = cur["chars"]["fontFamily"].as_str().unwrap_or_default().to_string();+ let style = cur["chars"]["fontStyle"].as_str().unwrap_or_default().to_string();- let db = designcraft_fonts::FontDb::global();++ // The document's own fonts count too.++ let db = designcraft_fonts::FontDb::global().scoped(s.doc()?.doc.font_scope);+ let (weight, italic) = db.traits_of(&family, &style);+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(if bold { weight < 650.0 } else { !italic });+ let (want_bold, want_italic) = if bold { (Some(on), None) } else { (None, Some(on)) };+ let targets = format_targets(s);+ // A caret: the linked style of the format there, for the next typing.+ if let [t] = targets.as_slice()+ && t.range.is_empty()+ {+ let linked = db.linked_style(&family, &style, want_bold, want_italic).ok_or_else(|| bad(id, format!("{family} has no style for that")))?;+ format_chars(s, &json!({"fontStyle": linked}))?;+ return Ok(json!({"on": on, "fontStyle": linked}));+ }+ let mut changed = 0;+ let r = s.edit(|d, _| {+ let styles = d.styles.clone();+ for t in &targets {+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };+ for (pi, pr) in st.para_ranges().into_iter().enumerate() {+ let (a, b) = (pr.start.max(t.range.start), pr.end.min(t.range.end));+ if a >= b {+ continue;+ }+ let Some(pf) = st.paras.get(pi) else { continue };+ let (_, pc) = styles.resolve_para(pf);+ st.format_chars(a..b, |f| {+ let cp = styles.resolve_char(&pc, f);+ if let Some(linked) = db.linked_style(&cp.font_family, &cp.font_style, want_bold, want_italic)+ && linked != cp.font_style+ {+ f.over.font_style = Some(linked);+ changed += 1;+ }+ });+ }+ }+ ok()+ });+ r?;+ Ok(json!({"on": on, "changed": changed}))+}+/// Our own filler text (not Adobe's).pub const PLACEHOLDER: &str = "Ovid ellum quisque arcet velut tempora sint, ne veriora pareant laudemque fieri. Lorem novum strata ponet amicos, \et tamen uti ferrum caelo tempus mollit. Quisque sinat oppida retro, nec tenuere longas animi semper vias. \diff --cc crates/fonts/src/fontdb.rsindex d6072a435,4177f941c..1912a4202--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -554,79 -808,23 +808,33 @@@ impl FontDbself.catalog.read().unwrap_or_else(|e| e.into_inner())}- /// Family names available (loaded plus cataloged system fonts), sorted and deduplicated.+ /// What the document with font scope `scope` sees: its own fonts ahead of the shared ones.+ /// Scope 0 (a document without fonts of its own) or a closed scope sees the shared fonts.+ pub fn scoped(&self, scope: u32) -> ScopedFonts<'_> {+ let own = if scope == 0 { None } else { self.scopes.read().unwrap_or_else(|e| e.into_inner()).get(&scope).cloned() };+ ScopedFonts { db: self, own }+ }++ /// The shared fonts' family names (see [`ScopedFonts::families`]).pub fn families(&self) -> Vec<String> {- let mut v: Vec<String> = self.read_faces().iter().map(|f| f.family.clone()).collect();- #[cfg(not(target_arch = "wasm32"))]- v.extend(self.read_catalog().iter().map(|c| c.family.clone()));- v.sort_by_key(|a| a.to_lowercase());- v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));- v+ self.scoped(0).families()}- /// Style names available for `family` (Regular first, then by weight).+ /// The shared fonts' styles of `family` (see [`ScopedFonts::styles`]).pub fn styles(&self, family: &str) -> Vec<String> {- self.style_traits(family).into_iter().map(|t| t.2).collect()+ self.scoped(0).styles(family)}- /// Weight and italic of a style of `family`: from the font when it is known, else from the- /// style's name.++ /// The shared fonts' weight and italic of a style of `family` (see [`ScopedFonts::traits_of`]).+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {- let base = base_style(style);- self.style_traits(family)- .into_iter()- .find(|t| t.2.eq_ignore_ascii_case(base))- .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))++ self.scoped(0).traits_of(family, style)+ }+- /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked- /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the- /// family has no such style.++ /// Style linking among the shared fonts (see [`ScopedFonts::linked_style`]).+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {- let (weight, cur_italic) = self.traits_of(family, current);- let want_italic = italic.unwrap_or(cur_italic);- let want_weight = match bold {- Some(true) => 700.0,- Some(false) => 400.0,- None => weight,- };- // Width words (Condensed, Extended…) of the current style are kept when the family allows.- const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];- let widths = |s: &str| {- let n = norm(s);- WIDTHS.iter().filter(|w| n.contains(*w)).count()- };- let cur_widths = widths(current);- self.style_traits(family)- .into_iter()- .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))- .min_by(|a, b| {- let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());- let (ka, kb) = (key(a), key(b));- ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))- })- .map(|t| t.2)- }-- /// `(italic, weight, name)` of each style of `family`, Regular first, then by weight.- fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {- let mut v: Vec<(bool, f32, String)> = self- .read_faces()- .iter()- .filter(|f| f.family.eq_ignore_ascii_case(family) && !f.style.contains('{'))- .map(|f| (f.italic, f.weight, f.style.clone()))- .collect();- #[cfg(not(target_arch = "wasm32"))]- for c in self.read_catalog().iter() {- if c.family.eq_ignore_ascii_case(family) && !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {- v.push((style_italic(&c.style), style_weight(&c.style), c.style.clone()));- }- }- v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));- v.dedup_by(|a, b| a.2 == b.2);- v++ self.scoped(0).linked_style(family, current, bold, italic)+ }+/// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or/// every face was already present).pub fn add_font(&self, bytes: Vec<u8>) -> usize {@@@ -717,13 -936,304 +946,349 @@@p.dedup();p};- let mut any = false;+ // The whole family arrives at once (see `insert_faces`).+ let mut faces = Vec::new();for p in paths {if let Ok(data) = std::fs::read(&p) {- any |= self.add_font(data) > 0;+ faces.extend(self.new_faces(data, FontSource::Installed(p)));+ }+ }+ self.insert_faces(faces) > 0+ }++ /// Load the font files (.ttf, .otf, .ttc, .otc; not in subfolders) of a document's `Document+ /// Fonts` folder under a new scope, for that document alone: looked up through+ /// [`FontDb::scoped`], they come before the shared faces of the same family and style, until+ /// [`FontDb::close_scope`]. A file loaded before and unchanged since (same length and+ /// modification time) isn't read again: its faces are shared. The files are untrusted: past+ /// [`MAX_DOCUMENT_FONT_FILES`] (in name order), files over [`MAX_DOCUMENT_FONT_BYTES`] or past+ /// [`MAX_DOCUMENT_FONTS_TOTAL`] in all, and files that aren't fonts are skipped with a note. A+ /// missing folder loads nothing (scope 0).+ #[cfg(not(target_arch = "wasm32"))]+ pub fn load_document_fonts(&self, folder: &std::path::Path) -> DocumentFonts {+ let mut out = DocumentFonts::default();+ let Ok(entries) = std::fs::read_dir(folder) else { return out };+ let mut files: Vec<std::path::PathBuf> = entries+ .flatten()+ .map(|e| e.path())+ .filter(|p| {+ let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());+ matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) && p.is_file()+ })+ .collect();+ files.sort();+ let mut total = 0u64;+ let mut own: Vec<Arc<FontFace>> = Vec::new();+ for (n, path) in files.iter().enumerate() {+ if n == MAX_DOCUMENT_FONT_FILES {+ out.skipped.push(format!("{} more font files not loaded (at most {MAX_DOCUMENT_FONT_FILES} are)", files.len() - n));+ break;+ }+ let name = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());+ // The listed length skips oversized files unread.+ let meta = std::fs::metadata(path).ok();+ let listed = meta.as_ref().map_or(0, |m| m.len());+ let faces = if listed > MAX_DOCUMENT_FONT_BYTES {+ Err(too_large())+ } else if total.saturating_add(listed) > MAX_DOCUMENT_FONTS_TOTAL {+ Err(over_total())+ } else {+ let modified = meta.and_then(|m| m.modified().ok());+ self.document_file(path, listed, modified, MAX_DOCUMENT_FONTS_TOTAL.saturating_sub(total))+ };+ match faces {+ Err(r) => out.skipped.push(format!("{name}: {r}")),+ Ok((faces, len)) => {+ total = total.saturating_add(len);+ // A family and style the folder already gave stays with its first file.+ for f in faces {+ if !own.iter().any(|o| o.family.eq_ignore_ascii_case(&f.family) && o.style.eq_ignore_ascii_case(&f.style)) {+ own.push(f);+ }+ }+ }}}- any+ for s in &out.skipped {+ log::warn!("{}: {s}", folder.display());+ }+ if !own.is_empty() {+ out.scope = NEXT_SCOPE.fetch_add(1, Ordering::Relaxed);+ out.faces = own.len();+ self.scopes.write().unwrap_or_else(|e| e.into_inner()).insert(out.scope, own.into());+ }+ out+ }++ /// The faces of the document font file at `path` (`listed` bytes long, modified at+ /// `modified`): those read before if it hasn't changed since, else read now, within `room`+ /// bytes of the folder's total → (faces, bytes), or why the file is skipped.+ #[cfg(not(target_arch = "wasm32"))]+ fn document_file(+ &self,+ path: &std::path::Path,+ listed: u64,+ modified: Option<std::time::SystemTime>,+ room: u64,+ ) -> Result<(Vec<Arc<FontFace>>, u64), String> {+ use std::io::Read;+ if let Some((len, m, faces)) = self.document_files.lock().unwrap_or_else(|e| e.into_inner()).get(path)+ && (*len, *m) == (listed, modified)+ {+ return Ok((faces.clone(), listed));+ }+ // One byte past the limit catches a file that grew since it was listed.+ let mut data = Vec::new();+ std::fs::File::open(path)+ .and_then(|f| f.take(MAX_DOCUMENT_FONT_BYTES + 1).read_to_end(&mut data))+ .map_err(|e| format!("can't be read ({e})"))?;+ let len = data.len() as u64;+ if len > MAX_DOCUMENT_FONT_BYTES {+ return Err(too_large());+ }+ if listed.max(len) > room {+ return Err(over_total());+ }+ let data = Arc::new(data);+ let faces: Vec<Arc<FontFace>> = enumerate_faces(&data)+ .into_iter()+ .filter_map(|(i, family, style, coords)| {+ make_face(FontBytes::Owned(data.clone()), FontSource::Document(path.to_path_buf()), i, family, style, coords)+ })+ .map(Arc::new)+ .collect();+ if faces.is_empty() {+ return Err("not a font DesignCraft can read".into());+ }+ self.document_files.lock().unwrap_or_else(|e| e.into_inner()).insert(path.to_path_buf(), (listed, modified, faces.clone()));+ Ok((faces, len))+ }++ /// Close a document's font scope: its fonts are no longer found (in it or anywhere). Their+ /// files stay read, for the document opening again.+ pub fn close_scope(&self, scope: u32) {+ self.scopes.write().unwrap_or_else(|e| e.into_inner()).remove(&scope);+ }++ /// The shared fonts' face for `family` + `style` (see [`ScopedFonts::face`]).+ pub fn face(&self, family: &str, style: &str) -> Arc<FontFace> {+ self.scoped(0).face(family, style)+ }++ /// Is `family` among the shared fonts (loaded, or installed on the system)?+ pub fn has_family(&self, family: &str) -> bool {+ self.scoped(0).has_family(family)+ }++ fn is_loaded(&self, family: &str) -> bool {+ self.read_faces().iter().any(|f| f.family.eq_ignore_ascii_case(family))+ }++ /// A shared variable font's axes (see [`ScopedFonts::axes`]).+ pub fn axes(&self, family: &str, style: &str) -> Vec<(String, String, f32, f32, f32)> {+ self.scoped(0).axes(family, style)+ }++ /// A shared face other than `exclude` that covers `c` (see [`ScopedFonts::fallback_for`]).+ pub fn fallback_for(&self, c: char, exclude: u32, language: Option<&str>) -> Option<Arc<FontFace>> {+ self.scoped(0).fallback_for(c, exclude, language)+ }++ /// Load a system font covering `c` (preferred fallback families first, then any cataloged+ /// file under 40 MB). Returns true if one was loaded. Misses are remembered.+ #[cfg(not(target_arch = "wasm32"))]+ fn system_fallback(&self, c: char) -> bool {+ if c.is_control() || c.is_whitespace() {+ return false;+ }+ {+ let sys = self.sys.lock().unwrap_or_else(|e| e.into_inner());+ if !sys.enabled || sys.misses.contains(&c) {+ return false;+ }+ }+ let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c));+ let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();+ for fam in SYSTEM_FALLBACKS {+ if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {+ self.load_cataloged(fam);+ if covered(self) {+ return true;+ }+ }+ }+ let mut paths: Vec<std::path::PathBuf> = self.catalog.read().unwrap_or_else(|e| e.into_inner()).iter().map(|e| e.path.clone()).collect();+ paths.sort();+ paths.dedup();+ for p in paths {+ if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {+ continue;+ }+ let Ok(data) = std::fs::read(&p) else { continue };+ let hit =+ enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));+ if hit && self.add_faces(data, FontSource::Installed(p)) > 0 && covered(self) {+ return true;+ }+ }+ self.sys.lock().unwrap_or_else(|e| e.into_inner()).misses.insert(c);+ false+ }++ /// The box drawn for `face`'s missing glyph (.notdef) when the font's own has no outline, in+ /// font units, y-down: a hollow rectangle across the glyph's advance, cap height tall. `None`+ /// when the font draws its own.+ pub fn missing_box(&self, face: &FontFace) -> Option<BezPath> {+ if !font_outline(face, 0).elements().is_empty() {+ return None;+ }+ let adv = Some(face.advance(0)).filter(|a| a.is_finite() && *a > 0.0).unwrap_or(face.upem * 0.5);+ let top = Some(face.cap_height).filter(|h| h.is_finite() && *h > 0.0).unwrap_or(face.upem * 0.7);+ let outer = kurbo::Rect::new(adv * 0.1, -top, adv * 0.9, 0.0);+ let t = (face.upem * 0.05).min(outer.width() / 4.0).min(top / 4.0);+ let inner = outer.inset(-t);+ let mut p = BezPath::new();+ // The inner rectangle runs the other way round, so filling leaves it empty.+ p.move_to((outer.x0, outer.y0));+ p.line_to((outer.x1, outer.y0));+ p.line_to((outer.x1, outer.y1));+ p.line_to((outer.x0, outer.y1));+ p.close_path();+ p.move_to((inner.x0, inner.y0));+ p.line_to((inner.x0, inner.y1));+ p.line_to((inner.x1, inner.y1));+ p.line_to((inner.x1, inner.y0));+ p.close_path();+ Some(p)+ }++ /// Glyph outline in font units, y-down (flipped), cached per (face, glyph). A `.notdef`+ /// without an outline is drawn as [`FontDb::missing_box`], so a missing character never+ /// disappears.+ pub fn outline(&self, face: &FontFace, gid: u32) -> Arc<BezPath> {+ let key = (face.id, gid);+ if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {+ return p.clone();+ }+ let drawn = font_outline(face, gid);+ let p = Arc::new(if gid == 0 && drawn.elements().is_empty() { self.missing_box(face).unwrap_or(drawn) } else { drawn });+ let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner());+ if cache.len() >= OUTLINE_CACHE_MAX {+ cache.clear();+ }+ cache.insert(key, p.clone());+ p+ }+ }++ /// One document's view of the [`FontDb`] ([`FontDb::scoped`]): the fonts of its `Document Fonts`+ /// folder, then the shared fonts (bundled, installed, added). Other documents' fonts aren't in it.+ #[derive(Clone)]+ pub struct ScopedFonts<'a> {+ db: &'a FontDb,+ /// The document's own faces, in the folder's file order (none without a scope).+ own: Option<Arc<[Arc<FontFace>]>>,+ }++ impl ScopedFonts<'_> {+ fn own(&self) -> &[Arc<FontFace>] {+ self.own.as_deref().unwrap_or(&[])+ }++ /// Family names available (the document's, loaded and cataloged system fonts), sorted and+ /// deduplicated.+ pub fn families(&self) -> Vec<String> {+ let mut v: Vec<String> = self.own().iter().chain(self.db.read_faces().iter()).map(|f| f.family.clone()).collect();+ #[cfg(not(target_arch = "wasm32"))]+ v.extend(self.db.read_catalog().iter().map(|c| c.family.clone()));+ v.sort_by_key(|a| a.to_lowercase());+ v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));+ v+ }++ /// The available families as the font menus list them (see [`ScopedFonts::families`]), each+ /// with its group and native name, unsorted ([`crate::sort_for_menu`] orders them).+ pub fn family_infos(&self) -> Vec<FamilyInfo> {+ let mut out: Vec<FamilyInfo> = Vec::new();+ let mut seen = std::collections::HashSet::new();+ for f in self.own().iter().chain(self.db.read_faces().iter()) {+ if seen.insert(f.family.to_lowercase()) {+ let (group, native) = f.menu_group();+ out.push(FamilyInfo { family: f.family.clone(), group, native: native.map(str::to_string) });+ }+ }+ #[cfg(not(target_arch = "wasm32"))]+ for c in self.db.read_catalog().iter() {+ if seen.insert(c.family.to_lowercase()) {+ out.push(FamilyInfo { family: c.family.clone(), group: c.group, native: c.native.clone() });+ }+ }+ out+ }++ /// Style names available for `family` (Regular first, then by weight).+ pub fn styles(&self, family: &str) -> Vec<String> {++ self.style_traits(family).into_iter().map(|t| t.2).collect()++ }++++ /// Weight and italic of a style of `family`: from the font when it is known, else from the++ /// style's name.++ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {++ let base = base_style(style);++ self.style_traits(family)++ .into_iter()++ .find(|t| t.2.eq_ignore_ascii_case(base))++ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))++ }++++ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked++ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the++ /// family has no such style.++ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {++ let (weight, cur_italic) = self.traits_of(family, current);++ let want_italic = italic.unwrap_or(cur_italic);++ let want_weight = match bold {++ Some(true) => 700.0,++ Some(false) => 400.0,++ None => weight,++ };++ // Width words (Condensed, Extended…) of the current style are kept when the family allows.++ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];++ let widths = |s: &str| {++ let n = norm(s);++ WIDTHS.iter().filter(|w| n.contains(*w)).count()++ };++ let cur_widths = widths(current);++ self.style_traits(family)++ .into_iter()++ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))++ .min_by(|a, b| {++ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());++ let (ka, kb) = (key(a), key(b));++ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))++ })++ .map(|t| t.2)++ }++++ /// `(italic, weight, name)` of each style of `family` (the document's, loaded, or installed),++ /// Regular first, then by weight.++ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {+ let mut v: Vec<(bool, f32, String)> = self+ .own()+ .iter()+ .chain(self.db.read_faces().iter())+ .filter(|f| f.family.eq_ignore_ascii_case(family) && !f.style.contains('{'))+ .map(|f| (f.italic, f.weight, f.style.clone()))+ .collect();+ #[cfg(not(target_arch = "wasm32"))]+ for c in self.db.read_catalog().iter() {+ if c.family.eq_ignore_ascii_case(family) && !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {+ v.push((style_italic(&c.style), style_weight(&c.style), c.style.clone()));+ }+ }+ v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));+ v.dedup_by(|a, b| a.2 == b.2);- v.into_iter().map(|t| t.2).collect()++ v}/// Resolve a family + style to a face, falling back to the closest style of the family, then todiff --cc crates/ui-egui/src/canvas.rsindex 164e953f5,8288dd35c..7a6a64eed--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -328,38 -328,15 +328,45 @@@ pub fn show(app: &mut DesignApp, ui: &m// Cursor.if let Some(p) = resp.hover_pos().filter(|p| screen.contains(*p)) {let space = ui.input(|i| i.key_down(egui::Key::Space)) && !app.session.wants_text();- let c = if space { Cursor::Hand } else { app.session.cursor(xf.to_canvas(p), ui.input(|i| mods(i, false)), app.view_info()) };+ let middle = ui.input(|i| i.pointer.middle_down());+ let c = if middle {+ Cursor::HandGrab+ } else if space {+ Cursor::Hand+ } else {+ app.session.cursor(xf.to_canvas(p), ui.input(|i| mods(i, false)), app.view_info())+ };ui.ctx().set_cursor_icon(cursor_icon(c));+ draw_cursor_badge(&painter, p, c, &t);+ }+}++/// The loaded text cursor's badge beside the system cursor: lines of text, a closed chain+/// (a click threads) or a broken one (a click unthreads). Drawn in code.+fn draw_cursor_badge(painter: &egui::Painter, p: Pos2, c: Cursor, t: &Tokens) {+ if !matches!(c, Cursor::LoadedText | Cursor::ThreadLink | Cursor::Unthread) {+ return;+ }+ let r = Rect::from_min_size(p + vec2(12.0, 12.0), vec2(20.0, 16.0));+ painter.rect_filled(r, 3.0, t.measure_bg);+ let ink = Stroke::new(1.5, t.measure_text);+ let c0 = r.center();+ match c {+ Cursor::LoadedText => {+ for (dy, w) in [(-4.0, 12.0), (0.0, 12.0), (4.0, 8.0)] {+ painter.line_segment([pos2(c0.x - 6.0, c0.y + dy), pos2(c0.x - 6.0 + w, c0.y + dy)], ink);+ }+ }+ _ => {+ let gap = if c == Cursor::Unthread { 2.5 } else { -2.0 };+ for side in [-1.0, 1.0] {+ let link = Rect::from_center_size(pos2(c0.x + side * (3.5 + gap / 2.0), c0.y), vec2(9.0, 6.0));+ painter.rect_stroke(link, 3.0, ink, StrokeKind::Middle);+ }+ if c == Cursor::Unthread {+ painter.line_segment([pos2(c0.x + 2.0, c0.y - 6.0), pos2(c0.x - 2.0, c0.y + 6.0)], ink);+ }+ }}}diff --cc crates/ui-egui/src/lib.rsindex eb2e34975,7b474fa21..ef1d1622a--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -266,9 -263,9 +270,10 @@@ impl Default for UiStatesmart_dimensions: true,smart_spacing: true,snap_zone: 4.0,+ formatting_affects_text: false,task_bar: true,about: false,+ about_tab: 0,pending_urls: Vec::new(),status: String::new(),dialog: None,diff --cc crates/ui-egui/src/menus.rsindex 8d929976a,034577dcf..422ebf01f--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -2006,31 -2018,16 +2028,41 @@@ mod tests}}+ #[test]+ fn formatting_affects_text_sends_swatches_to_the_text() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap();+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());+ app.run("selection.set", json!({"ids": [fid]})).unwrap();+ let text_fill = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();+ st.char_format_at(2).over.fill.clone()+ };+ let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone();+ assert!(!crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "Cyan", None).unwrap();+ assert_eq!(frame_fill(&app), "Cyan");+ assert_eq!(text_fill(&app), None);+ let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap();+ assert_eq!(r["on"], true, "toggles on");+ assert!(crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "Magenta", Some(0.5)).unwrap();+ assert_eq!(frame_fill(&app), "Cyan", "the frame is left alone");+ assert_eq!(text_fill(&app).as_deref(), Some("Magenta"));+ assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("Magenta".to_string(), 0.5)));+ }++ #[test]+ fn transform_menu_items_open_their_dialogs() {+ for id in ["transform.move", "transform.scale", "transform.rotate", "transform.shear"] {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ activate(&mut app, id, &Value::Null);+ let dialog = app.ui.dialog.as_ref().map(|d| d.id.clone());+ assert_eq!(dialog.as_deref(), Some(format!("cmd:{id}").as_str()), "{id} opens its dialog");+ }+ }+#[test]fn snap_preferences_are_a_command() {let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --cc docs/control-protocol.mdindex 76c9308c9,b24894fdd..99d1f5c2d--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -16,9 -26,9 +26,9 @@@ so only enable it while you use it. Tra| `ui.inspect` | — | Tool, UI state, view (zoom/origin), canvas rect, perf || `ui.menu.list` / `ui.tool.list` | — | Menu tree / Tools panel groups || `ui.tool.select` | `{tool}` | Select a tool (`selection`, `type`, `rectangleFrame`, …) |-| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas"}], mods?}` | Drive the active tool through the same code path as the mouse |+| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click); returns the selection, the tool and its cursor at the last event (e.g. `LoadedText`, `ThreadLink`, `Unthread`) || `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) |- | `ui.move` / `ui.click` / `ui.drag` | screen points | Real egui pointer input — reaches every widget, menu and panel |+ | `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle` | Real egui pointer input — reaches every widget, menu and panel || `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state || `ui.dialog.open` | `{id, fields?}` | Open a dialog by id (e.g. `paragraphStyleOptions` with `{name, section}`) || `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel` | `{field, value}` | Fill and confirm the open dialog |