GitCorner

Code

ossartcraftvectorcraft๐ŸŒ
2bc41aeb8602
use super::*;
use vectorcraft_engine::Session;

#[test]
fn scaled_dimensions_do_not_show_false_mixed_values_from_roundoff() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "Axis", "size": 12})).unwrap()["id"].clone();
    app.run("object.scale", json!({"sx": 120, "sy": 110})).unwrap();
    let b = app.run("text.create", json!({"x": 20, "y": 90, "text": "Label", "size": 24})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    app.run("text.setStyle", json!({"size": 7, "leading": 9})).unwrap();
    app.run("text.setFormat", json!({"hScale": 130, "baselineShift": 3})).unwrap();
    for (actual, expected) in [
        (shared_effective(&app, |s| s.size), 7.0),
        (shared_effective(&app, CharStyle::effective_leading), 9.0),
        (shared_effective(&app, |s| s.h_scale), 130.0),
        (shared_effective(&app, |s| s.baseline_shift), 3.0),
    ] {
        assert!((actual.expect("equal dimensions must not be mixed") - expected).abs() < 1e-8);
    }
}

/// A final empty paragraph counts: with the object selected, its Auto Leading differing from
/// the paragraph before it shows Leading as mixed.
#[test]
fn leading_field_counts_the_final_empty_paragraph() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "One\n", "size": 10})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    assert!((shared_leading(&app).unwrap() - 12.0).abs() < 1e-9);
    app.run("text.setFormat", json!({"autoLeading": 200, "start": 4, "end": 4})).unwrap();
    assert_eq!(shared_leading(&app), None, "the empty last paragraph differs");
}

/// Auto leading shows the leading the paragraph's Justification โ€บ Auto Leading sets.
#[test]
fn leading_field_shows_the_paragraph_auto_leading() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "One\nTwo", "size": 10})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    assert!((shared_leading(&app).unwrap() - 12.0).abs() < 1e-9);
    app.run("text.setFormat", json!({"autoLeading": 200, "start": 5, "end": 5})).unwrap();
    assert_eq!(shared_leading(&app), None, "the paragraphs differ");
    assert_eq!(shared(&app, |s| s.leading.is_none()), Some(true), "still Auto");
    app.run("text.setFormat", json!({"autoLeading": 200})).unwrap();
    assert!((shared_leading(&app).unwrap() - 20.0).abs() < 1e-9);
    app.run("text.setStyle", json!({"leading": 15})).unwrap();
    assert!((shared_leading(&app).unwrap() - 15.0).abs() < 1e-9, "a set leading is its own");
}

#[test]
fn scaled_collapsed_text_keeps_nondimensional_controls_available() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.run("text.create", json!({"x": 20, "y": 50, "text": "Axis", "size": 12})).unwrap();
    app.run("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})).unwrap();
    assert!(text_style(&app).is_some());
    assert_eq!(shared(&app, |s| s.tracking), Some(0.0));
    assert_eq!(shared_effective(&app, |s| s.size), None);
    app.run("text.setStyle", json!({"tracking": 40})).unwrap();
    app.run("text.setFormat", json!({"leftIndent": 4})).unwrap();
    assert_eq!(shared(&app, |s| s.tracking), Some(40.0));
    assert_eq!(text_style(&app).unwrap().1.left_indent, 4.0);
    let ctx = egui::Context::default();
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show);
    assert!(!texts.iter().any(|(s, _)| s == "No text selected"));
}

#[test]
fn scaled_character_fields_show_document_sizes_and_mixed_group_values() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "Axis", "size": 12})).unwrap()["id"].clone();
    app.run("object.scale", json!({"sx": 200})).unwrap();
    assert_eq!(shared_effective(&app, |s| s.size), Some(24.0));
    assert_eq!(text_style(&app).unwrap().0.size, 12.0, "style definitions keep stored attributes");
    let b = app.run("text.create", json!({"x": 20, "y": 90, "text": "Label", "size": 24})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    app.run("object.group", json!({})).unwrap();
    assert_eq!(shared_effective(&app, |s| s.size), Some(24.0), "different local sizes, same displayed size");
    app.run("object.scale", json!({"sx": 200, "sy": 100})).unwrap();
    assert_eq!(shared_effective(&app, |s| s.h_scale), Some(200.0));
    app.run("text.setStyle", json!({"size": 10})).unwrap();
    assert_eq!(shared_effective(&app, |s| s.size), Some(10.0));
    app.run("text.setFormat", json!({"hScale": 100})).unwrap();
    assert_eq!(shared_effective(&app, |s| s.h_scale), Some(100.0));
}

/// The Leading field shows the Auto leading the characters are set with, their paragraph's Auto
/// Leading share (120% by default) of their em size: 20 pt type measuring a 0.7 em cap height
/// is set at 20 / 0.7 pt. Paragraphs whose Auto leading differs show a blank field, and an
/// explicit leading shows as it is.
#[test]
fn leading_shows_the_auto_leading_of_the_em_size() {
    use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font};
    vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 20, "font": HEIGHT_FAMILY})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let near = |l: Option<f64>, want: f64| l.is_some_and(|l| (l - want).abs() < 1e-9);
    assert!(near(shared_leading(&app), 24.0), "{:?}", shared_leading(&app));
    app.run("text.setFormat", json!({"fontHeightReference": "capHeight"})).unwrap();
    let cap = f64::from(HEIGHT_CAP) / 1000.0;
    assert!(near(shared_leading(&app), 1.2 * 20.0 / cap), "{:?}", shared_leading(&app));
    app.run("text.setFormat", json!({"autoLeading": 150})).unwrap();
    assert!(near(shared_leading(&app), 1.5 * 20.0 / cap), "{:?}", shared_leading(&app));
    // The second paragraph ends in a two-byte character.
    let two = app.run("text.create", json!({"x": 20, "y": 120, "text": "Hx\nHรฉ", "size": 20, "font": HEIGHT_FAMILY})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [two]})).unwrap();
    assert!(near(shared_leading(&app), 24.0), "{:?}", shared_leading(&app));
    app.run("text.setFormat", json!({"id": two, "start": 3, "end": 6, "autoLeading": 150})).unwrap();
    assert_eq!(shared_leading(&app), None, "the second paragraph's Auto leading is 30 pt");
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.run("text.setStyle", json!({"leading": 30})).unwrap();
    assert!(near(shared_leading(&app), 30.0), "{:?}", shared_leading(&app));
}

/// An inline graphic keeps its size whatever the font height reference, so the Leading field
/// shows 120% of that size for it: blank for 20 pt Cap Height type with a graphic in it, and
/// 24 pt for the graphic alone.
#[test]
fn leading_of_an_inline_graphic_follows_its_own_size() {
    use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
    vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.run("shape.ellipse", json!({"x": 200, "y": 150, "width": 10, "height": 10})).unwrap();
    app.run("symbol.new", json!({"name": "Dot"})).unwrap();
    app.run("edit.clear", json!({})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 20, "font": HEIGHT_FAMILY})).unwrap()["id"].clone();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.run("text.insertInline", json!({"id": id, "at": 2, "symbol": "Dot"})).unwrap();
    app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 5, "fontHeightReference": "capHeight"})).unwrap();
    app.session.set_tool_option("select", &json!({"start": 0, "end": 5}));
    assert_eq!(shared_leading(&app), None, "the type is set with 34.3 pt Auto leading and the graphic with 24 pt");
    app.session.set_tool_option("select", &json!({"start": 2, "end": 5}));
    assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((2, 5)));
    let shown = shared_leading(&app);
    assert!(shown.is_some_and(|l| (l - 24.0).abs() < 1e-9), "{shown:?}");
}

/// A selected text object that ends in a line break has an empty last paragraph, which the
/// Leading field takes in; a Type tool selection of all the text does not.
#[test]
fn leading_of_a_whole_object_takes_in_the_empty_last_paragraph() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Ab\n", "size": 20})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let near = |l: Option<f64>, want: f64| l.is_some_and(|l| (l - want).abs() < 1e-9);
    assert!(near(shared_leading(&app), 24.0), "{:?}", shared_leading(&app));
    app.run("text.setFormat", json!({"id": id, "start": 3, "end": 3, "autoLeading": 150})).unwrap();
    assert_eq!(shared_leading(&app), None, "the empty last paragraph's Auto leading is 30 pt");
    app.session.select_tool("type", Default::default()).unwrap();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 0, "end": 3}));
    assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((0, 3)));
    assert!(near(shared_leading(&app), 24.0), "a line break belongs to the paragraph it ends: {:?}", shared_leading(&app));
}

/// With the Type tool, the Leading field shows the Auto leading of the paragraphs the selection
/// covers (a line break belongs to the paragraph it ends), and at a caret that of the caret's
/// paragraph.
#[test]
fn leading_follows_the_paragraphs_the_type_tool_selection_covers() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    // รฉ is two bytes, 4..6.
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Ab\nCรฉ", "size": 20})).unwrap()["id"].clone();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.run("text.setFormat", json!({"id": id, "start": 3, "end": 6, "autoLeading": 150})).unwrap();
    let ranges = [((0, 2), Some(24.0)), ((0, 3), Some(24.0)), ((3, 6), Some(30.0)), ((1, 4), None), ((1, 6), None), ((4, 4), Some(30.0))];
    for ((start, end), want) in ranges {
        app.session.set_tool_option("select", &json!({"start": start, "end": end}));
        assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((start, end)));
        let shown = shared_leading(&app);
        assert_eq!(shown.is_some(), want.is_some(), "{start}..{end}: {shown:?}");
        assert!(shown.zip(want).is_none_or(|(l, w)| (l - w).abs() < 1e-9), "{start}..{end}: {shown:?}");
    }
}

#[test]
fn scaled_range_fields_follow_the_type_tool_selection() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Axis label", "size": 12})).unwrap()["id"].clone();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    assert!(text_editing(&app).is_some());
    app.run("object.scale", json!({"sx": 200})).unwrap();
    app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 4, "size": 10})).unwrap();
    app.session.set_tool_option("selectAll", &json!(true));
    assert_eq!(shared_effective(&app, |s| s.size), None);
    app.session.set_tool_option("select", &json!({"start": 0, "end": 4}));
    assert_eq!(shared_effective(&app, |s| s.size), Some(10.0));
    assert_eq!(text_style(&app).unwrap().0.size, 5.0);
}

/// The Kerning field at a caret kerns that pair, not the whole text (#2217).
#[test]
fn kerning_at_a_caret_sets_the_pair_not_the_whole_text() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AVAX", "size": 12})).unwrap()["id"].clone();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
    set_kerning(&mut app, json!(-50));
    let kerning = |app: &VectorcraftApp, at: usize| {
        let st = app.session.active().unwrap();
        let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id.as_u64().unwrap())).map(|n| &n.kind) else { panic!("text") };
        vectorcraft_text::edit::style_at(&t.runs, at + 1).kerning // the character at `at`
    };
    assert_eq!(kerning(&app, 1), Some(-50.0), "the character before the caret");
    assert_eq!(kerning(&app, 3), None, "the rest is untouched");
    assert_eq!(kerning(&app, 0), None);
    // A selected range still takes it whole.
    app.session.set_tool_option("select", &json!({"start": 2, "end": 4}));
    set_kerning(&mut app, json!(30));
    assert_eq!((kerning(&app, 1), kerning(&app, 2), kerning(&app, 3)), (Some(-50.0), Some(30.0), Some(30.0)));
}

#[test]
fn character_kerning_setter_and_automatic_pair_value() {
    let german = crate::i18n::Lang::from_code("de").unwrap();
    assert!(crate::i18n::has(german, "Optical"));
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    app.run("text.create", json!({"x": 20, "y": 50, "text": "III", "size": 100, "font": "JetBrains Mono"})).unwrap();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 1, "end": 1}));
    set_kerning(&mut app, json!("optical"));
    assert!(text_style(&app).unwrap().0.optical_kerning);
    let ctx = egui::Context::default();
    let mut shown = None;
    ctx.run_ui(Default::default(), |ui| {
        shown = caret_kerning(&app, ui);
    })
    .textures_delta
    .clear();
    let (value, automatic) = shown.unwrap();
    assert!(automatic && value != 0.0);
    set_kerning(&mut app, json!(50));
    ctx.run_ui(Default::default(), |ui| {
        shown = caret_kerning(&app, ui);
    })
    .textures_delta
    .clear();
    assert_eq!(shown, Some((50.0, false)));
    app.session.set_tool_option("select", &json!({"start": 0, "end": 2}));
    assert_eq!(shared(&app, |s| (s.optical_kerning, s.kerning)), None, "a mixed range shows a blank Kerning field");
}

/// The Kerning menu lists Auto and Optical for a selection that mixes kerning modes, with
/// neither checked, so one mode can be set on all of it.
#[test]
fn kerning_menu_lists_auto_and_optical_for_mixed_modes() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AV", "size": 12})).unwrap()["id"].clone();
    let b = app.run("text.create", json!({"x": 20, "y": 90, "text": "AV", "size": 12})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [b.clone()]})).unwrap();
    app.run("text.setFormat", json!({"kerning": "optical"})).unwrap();
    app.run("select.set", json!({"ids": [a.clone()]})).unwrap();
    assert_eq!(kerning_methods(shared(&app, |s| (s.optical_kerning, s.kerning))), (Some(true), Some(false)), "Auto");
    app.run("select.set", json!({"ids": [b.clone()]})).unwrap();
    assert_eq!(kerning_methods(shared(&app, |s| (s.optical_kerning, s.kerning))), (Some(false), Some(true)), "Optical");
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    let mode = shared(&app, |s| (s.optical_kerning, s.kerning));
    assert_eq!(mode, None, "the selection mixes Auto and Optical");
    assert_eq!(kerning_methods(mode), (Some(false), Some(false)), "both entries are listed, neither checked");
}

/// A number typed into the Kerning field after Optical keeps the Optical flag on the type, and
/// the manual value sets the spacing; the menu then checks neither Auto nor Optical.
#[test]
fn kerning_menu_checks_neither_method_for_a_manual_value_after_optical() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AV", "size": 12})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [a]})).unwrap();
    app.run("text.setFormat", json!({"kerning": "optical"})).unwrap();
    app.run("text.setFormat", json!({"kerning": 50})).unwrap();
    let mode = shared(&app, |s| (s.optical_kerning, s.kerning));
    assert_eq!(mode, Some((true, Some(50.0))), "the manual value keeps the Optical flag");
    assert_eq!(kerning_methods(mode), (Some(false), Some(false)), "a manual value checks neither method");
}

/// Highlight Kerning and Highlight Tracking show the Character panel and give its field the
/// keyboard focus with the value selected: what is typed replaces it, and Enter applies it.
/// Highlight Font Name opens the font family menu with its search field focused. Without
/// selected type the panel shows and nothing takes the focus.
#[test]
fn highlight_commands_focus_the_font_kerning_and_tracking_fields() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AVAX", "size": 12})).unwrap()["id"].clone();
    let ctx = egui::Context::default();
    let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
        let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui));
        out.textures_delta.clear();
    };
    let typed = |text: &str| {
        let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
        vec![egui::Event::Text(text.into()), enter]
    };
    let spacing = |app: &VectorcraftApp| text_style(app).map(|(s, _)| (s.kerning, s.tracking)).unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    assert_eq!(app.run("type.highlightKerning", json!({})).unwrap(), json!({"field": "kerning"}));
    assert!(crate::panel_docking::showing(&app.ui, "character"), "the panel shows");
    frame(&mut app, vec![]);
    assert_eq!(app.character_focus, None, "the Kerning field took the focus");
    frame(&mut app, typed("-40"));
    assert_eq!(spacing(&app), (Some(-40.0), 0.0), "typing replaced the kerning");
    app.run("type.highlightTracking", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, typed("75"));
    assert_eq!(spacing(&app), (Some(-40.0), 75.0), "typing replaced the tracking");
    // Highlighting a field again while it holds typed text that is not applied selects all of it.
    app.run("type.highlightKerning", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, vec![egui::Event::Text("12345".into())]);
    app.run("type.highlightKerning", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, typed("-20"));
    assert_eq!(spacing(&app), (Some(-20.0), 75.0), "typing replaced the text typed before");
    ctx.memory_mut(|m| m.stop_text_input());
    app.run("type.highlightFontName", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, vec![]);
    assert!(egui::Popup::is_any_open(&ctx), "the font family menu is open");
    assert!(ctx.memory(|m| m.focused()).is_some(), "its search field has the focus");
    // No type selected: the panel shows, the command fails and nothing is armed.
    app.run("select.none", json!({})).unwrap();
    assert!(app.run("type.highlightKerning", json!({})).is_err());
    assert_eq!(app.character_focus, None);
}

/// Type โ€บ Size โ€บ Otherโ€ฆ (Highlight Font Size) shows the Character panel and gives its Font Size
/// field the keyboard focus with the value selected: what is typed replaces it, Enter applies it
/// as one undo step, and a selection of different sizes takes the one size typed into the blank
/// field. Without selected type the panel shows, the command fails and nothing takes the focus.
#[test]
fn highlight_font_size_focuses_the_font_size_field() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AVAX", "size": 12})).unwrap()["id"].clone();
    let b = app.run("text.create", json!({"x": 20, "y": 120, "text": "Wave", "size": 20})).unwrap()["id"].clone();
    let ctx = egui::Context::default();
    let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
        let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui));
        out.textures_delta.clear();
    };
    let typed = |text: &str| {
        let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
        vec![egui::Event::Text(text.into()), enter]
    };
    let size = |app: &VectorcraftApp| shared(app, |s| s.size);
    app.run("select.set", json!({"ids": [a.clone()]})).unwrap();
    assert_eq!(app.run("type.highlightFontSize", json!({})).unwrap(), json!({"field": "fontSize"}));
    assert!(crate::panel_docking::showing(&app.ui, "character"), "the panel shows");
    frame(&mut app, vec![]);
    assert_eq!(app.character_focus, None, "the Font Size field took the focus");
    frame(&mut app, typed("33"));
    assert_eq!(size(&app), Some(33.0), "typing replaced the size");
    app.run("edit.undo", json!({})).unwrap();
    assert_eq!(size(&app), Some(12.0), "one undo step restores the size");
    // Choosing Other again while the field holds typed text that is not applied selects all of it.
    app.run("type.highlightFontSize", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, vec![egui::Event::Text("999".into())]);
    app.run("type.highlightFontSize", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, typed("18"));
    assert_eq!(size(&app), Some(18.0), "typing replaced the text typed before");
    ctx.memory_mut(|m| m.stop_text_input());
    // Different sizes: the field is blank, and the size typed applies to every selected object.
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    assert_eq!(size(&app), None);
    app.run("type.highlightFontSize", json!({})).unwrap();
    frame(&mut app, vec![]);
    frame(&mut app, typed("16"));
    assert_eq!(size(&app), Some(16.0), "both objects take the size typed");
    // No type selected: the panel shows, the command fails and nothing is armed.
    app.run("select.none", json!({})).unwrap();
    assert!(app.run("type.highlightFontSize", json!({})).is_err());
    assert_eq!(app.character_focus, None);
}

/// A variable font gets the Variable Font button, which opens one slider per axis named as the
/// font names it; a drag along one sets that axis of the selected type in one undo step.
#[test]
fn variable_fonts_get_a_slider_per_axis() {
    use vectorcraft_text::test_fonts::{TWO_AXIS_FAMILY, two_axis_font};
    let db = vectorcraft_text::FontDb::global();
    db.add_font(two_axis_font().unwrap());
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let plain = app.run("text.create", json!({"x": 20, "y": 50, "text": "Static"})).unwrap()["id"].clone();
    let id = app.run("text.create", json!({"x": 20, "y": 120, "text": "lIn", "font": TWO_AXIS_FAMILY})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [plain]})).unwrap();
    assert!(!crate::tests_labels::painted_text(&mut app, show).contains("Variable Font"), "a static font");
    app.run("select.set", json!({"ids": [id]})).unwrap();
    assert!(crate::tests_labels::painted_text(&mut app, show).contains("Variable Font"));
    let face = db.face(TWO_AXIS_FAMILY, "Regular").unwrap();
    let text = crate::tests_labels::painted_text(&mut app, |app, ui| axis_sliders(app, ui, &face));
    assert!(text.contains("Weight\n") && text.contains("Width\n") && text.contains("400") && text.contains("100"), "{text}");
    // The labels are the font's names in every interface language, not catalog words (ja
    // translates the interface's Weight as the stroke weight).
    let ja = crate::i18n::Lang::from_code("ja").unwrap();
    crate::i18n::set_current(ja);
    let text = crate::tests_labels::painted_text(&mut app, |app, ui| axis_sliders(app, ui, &face));
    crate::i18n::set_current(crate::i18n::Lang::EN);
    let weight = crate::i18n::tr(ja, "Weight");
    assert!(text.contains("Weight\n") && text.contains("Width\n") && (weight == "Weight" || !text.contains(weight)), "{text}");
    // Screen readers name each slider by its axis.
    let tree = crate::widgets::accessibility_tests::tree(|ui| axis_sliders(&mut app, ui, &face));
    for name in ["Weight", "Width"] {
        assert!(tree.iter().any(|n| n.role() == egui::accesskit::Role::Slider && n.label() == Some(name)), "{name}");
    }
    // ...with the number its field shows, on the axis's range.
    use crate::widgets::accessibility_tests::slider_value;
    let wght = face.axes().into_iter().find(|a| &a.tag == b"wght").unwrap();
    let range = (Some(f64::from(wght.min)), Some(f64::from(wght.max)));
    assert_eq!(slider_value(&tree, "Weight"), (Some(400.0), range.0, range.1, Some("400".into())));
    // Drag the Weight slider from its start to past its end.
    let ctx = egui::Context::default();
    let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
        let mut slider = None;
        let input = egui::RawInput { events, ..Default::default() };
        ctx.run_ui(input, |ui| {
            axis_sliders(app, ui, &face);
            slider = ctx.read_response(ui.scope_id().with(("ch-axis", *b"wght"))).map(|r| r.rect);
        })
        .textures_delta
        .clear();
        slider
    };
    frame(&mut app, vec![]);
    let r = frame(&mut app, vec![]).expect("the Weight slider is drawn");
    let none = egui::Modifiers::NONE;
    let (from, to) = (egui::pos2(r.left() + 4.0, r.center().y), egui::pos2(r.right() + 20.0, r.center().y));
    let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: none };
    frame(&mut app, vec![egui::Event::PointerMoved(from), button(from, true)]);
    for i in 1..=4 {
        frame(&mut app, vec![egui::Event::PointerMoved(from + (to - from) * i as f32 / 4.0)]);
    }
    frame(&mut app, vec![button(to, false)]);
    frame(&mut app, vec![]);
    let axes = |app: &VectorcraftApp| shared(app, |s| s.font_axes.clone()).unwrap();
    assert_eq!(axes(&app).into_iter().collect::<Vec<_>>(), [("wght".to_string(), 700.0)]);
    app.run("edit.undo", json!({})).unwrap();
    assert!(axes(&app).is_empty(), "one undo step");
    // Regular and Bold selected: the weights differ and the field is blank; the widths agree.
    let bold = app.run("text.create", json!({"x": 20, "y": 160, "text": "lIn", "font": TWO_AXIS_FAMILY, "style": "Bold"})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id, bold]})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, |app, ui| axis_sliders(app, ui, &face));
    assert!(!text.contains("400") && !text.contains("700") && text.contains("100"), "{text}");
    let tree = crate::widgets::accessibility_tests::tree(|ui| axis_sliders(&mut app, ui, &face));
    assert_eq!(slider_value(&tree, "Weight"), (None, None, None, None), "a blank field: no value");
    assert_eq!(slider_value(&tree, "Width").0, Some(100.0));
    // Reset Panel leaves the settings, as it leaves the font and style.
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.run("text.setFormat", json!({"fontAxes": {"wght": 650}})).unwrap();
    reset_panel(&mut app);
    assert_eq!(axes(&app).into_iter().collect::<Vec<_>>(), [("wght".to_string(), 650.0)]);
}

/// Bold and Italic pick the family's own faces by name, and toggle back (#724).
#[test]
fn bold_and_italic_pick_the_familys_own_faces() {
    let styles: Vec<String> =
        ["Light", "Narrow", "Regular", "Italic", "Narrow Italic", "SemiBold", "Bold", "Bold Condensed", "Narrow Bold", "Bold Italic", "Black"]
            .iter()
            .map(|s| s.to_string())
            .collect();
    assert_eq!(pick_face(&styles, true, false, "Regular"), Some("Bold"), "not Bold Condensed, Narrow Bold or SemiBold");
    assert_eq!(pick_face(&styles, true, true, "Italic"), Some("Bold Italic"));
    assert_eq!(pick_face(&styles, false, true, "Regular"), Some("Italic"));
    assert_eq!(pick_face(&styles, false, false, "Italic"), Some("Regular"), "upright again, not Narrow");
    assert_eq!(pick_face(&styles, true, false, "Narrow"), Some("Narrow Bold"), "a Narrow face stays Narrow");
    assert_eq!(pick_face(&styles, false, true, "Narrow"), Some("Narrow Italic"));
    let oblique: Vec<String> = ["Book", "Oblique", "Bold-Oblique"].iter().map(|s| s.to_string()).collect();
    assert_eq!(pick_face(&oblique, true, true, "Oblique"), Some("Bold-Oblique"));
    assert_eq!(pick_face(&oblique, false, false, "Oblique"), None, "Book has a weight word: no regular face");
    assert_eq!(face_of("Bold Italic"), (true, false, true, vec![]));
    assert_eq!(face_of("SemiBold"), (false, false, false, vec![]));
    assert_eq!(face_of("Narrow Italic"), (false, true, true, vec!["narrow".to_string()]));
    // No type selected: a message, nothing changed.
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    assert!(toggle_face(&mut app, Face::Bold).is_err());
    assert!(!crate::menus::enabled(&app, "type.bold"));
}

/// From one frame of the panel: a point inside each of the Small Caps, Superscript and
/// Subscript buttons, and which of them are drawn on.
fn script_buttons(ctx: &egui::Context, app: &mut VectorcraftApp) -> ([egui::Pos2; 3], [bool; 3]) {
    let (points, on) = style_buttons(ctx, app);
    ([points[1], points[2], points[3]], [on[1], on[2], on[3]])
}

/// From one frame of the panel: a point inside each of the All Caps, Small Caps, Superscript,
/// Subscript, Underline and Strikethrough buttons, and which of them are drawn on. The two buttons
/// with a "1" are Superscript (the "1" up) and Subscript; the others sit one button apart from them
/// in that order.
fn style_buttons(ctx: &egui::Context, app: &mut VectorcraftApp) -> ([egui::Pos2; 6], [bool; 6]) {
    let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
    out.textures_delta.clear();
    fn walk(s: &egui::Shape, on: egui::Color32, ones: &mut Vec<egui::Pos2>, lit: &mut Vec<egui::Rect>) {
        match s {
            egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, on, ones, lit)),
            egui::Shape::Text(t) if t.galley.text() == "1" => ones.push(t.visual_bounding_rect().center()),
            egui::Shape::Rect(r) if r.fill == on && r.rect.size() == vec2(30.0, 26.0) => lit.push(r.rect),
            _ => {}
        }
    }
    let (mut ones, mut lit) = (vec![], vec![]);
    for c in &out.shapes {
        walk(&c.shape, Tokens::get(ctx).tool_active, &mut ones, &mut lit);
    }
    let [sup, sub] = ones[..] else { panic!("two script buttons: {ones:?}") };
    assert!(sup.x < sub.x && sup.y < sub.y, "Superscript, then Subscript: {ones:?}");
    // Each "1" is drawn 6 points right of its button's center and 5 points above or below it.
    let y = (sup.y + sub.y) / 2.0;
    let (sup, sub) = (egui::pos2(sup.x - 6.0, y), egui::pos2(sub.x - 6.0, y));
    let step = vec2(sub.x - sup.x, 0.0);
    let points = [sup - step * 2.0, sup - step, sup, sub, sub + step, sub + step * 2.0];
    (points, points.map(|p| lit.iter().any(|r| r.contains(p))))
}

/// Each run's (small caps, position).
fn scripts(app: &VectorcraftApp, id: &Value) -> Vec<(Option<f64>, &'static str)> {
    match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| (r.style.small_caps, r.style.position.id())).collect(),
        _ => panic!("text"),
    }
}

/// The Small Caps, Superscript and Subscript buttons set the selected type's small caps and
/// position, with one undo step for each click, and show them; Superscript and Subscript turn
/// each other off. While the Type tool edits, they set and show the selected characters.
#[test]
fn small_caps_superscript_and_subscript_buttons_set_and_show_the_text() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "E=mc2", "size": 12})).unwrap()["id"].clone();
    let ctx = egui::Context::default();
    let (at, lit) = script_buttons(&ctx, &mut app);
    assert_eq!(lit, [false; 3]);
    let small = Some(app.session.active().unwrap().doc.setup.small_caps_size);
    for (button, runs, shown) in [
        (0, (small, "normal"), [true, false, false]),
        (1, (small, "superscript"), [true, true, false]),
        (2, (small, "subscript"), [true, false, true]),
        (2, (small, "normal"), [true, false, false]),
        (1, (small, "superscript"), [true, true, false]),
        (1, (small, "normal"), [true, false, false]),
        (0, (None, "normal"), [false; 3]),
    ] {
        let undo = app.session.active().unwrap().history.undo.len();
        super::super::tests_appearance::click(&ctx, &mut app, at[button], show);
        assert_eq!(scripts(&app, &id), [runs], "button {button}");
        assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "button {button}");
        assert_eq!(script_buttons(&ctx, &mut app).1, shown, "button {button}");
    }
    // The Type tool's selection: "2" alone.
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 4, "end": 5}));
    assert!(text_editing(&app).is_some());
    super::super::tests_appearance::click(&ctx, &mut app, at[1], show);
    assert_eq!(scripts(&app, &id), [(None, "normal"), (None, "superscript")]);
    assert_eq!(script_buttons(&ctx, &mut app).1, [false, true, false]);
    app.session.set_tool_option("select", &json!({"start": 0, "end": 4}));
    assert_eq!(script_buttons(&ctx, &mut app).1, [false; 3]);
}

/// Superscript and Subscript decide from the characters they change. At a Type tool caret they
/// change every character of the text, so text that is only partly superscript turns superscript
/// everywhere, with the caret after a superscript character too, and the button there shows off.
/// Superscripts in different proportions count as superscript, so a press turns them off.
#[test]
fn superscript_and_subscript_decide_from_the_characters_they_change() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "x2", "size": 12})).unwrap()["id"].clone();
    app.run("text.setRangeStyle", json!({"id": id, "start": 1, "end": 2, "position": "superscript"})).unwrap();
    app.run("select.set", json!({"ids": [id.clone()]})).unwrap();
    app.select_tool("type");
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
    assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((2, 2)));
    let ctx = egui::Context::default();
    assert_eq!(script_buttons(&ctx, &mut app).1, [false; 3], "the text is not all superscript");
    assert_eq!(app.run("type.superscript", json!({})).unwrap(), json!("superscript"));
    assert!(scripts(&app, &id).iter().all(|(_, p)| *p == "superscript"), "{:?}", scripts(&app, &id));
    app.run("type.superscript", json!({})).unwrap();
    assert!(scripts(&app, &id).iter().all(|(_, p)| *p == "normal"), "{:?}", scripts(&app, &id));

    // A file whose two superscript runs have different proportions.
    app.select_tool("selection");
    app.run("text.setRangeStyle", json!({"id": id, "position": "superscript"})).unwrap();
    app.run("text.setRangeStyle", json!({"id": id, "start": 1, "end": 2, "underline": true})).unwrap();
    let mut d = (*app.session.active().unwrap().doc).clone();
    if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(id.as_u64().unwrap())).map(|n| &mut n.kind) {
        assert_eq!(t.runs.len(), 2);
        t.runs[0].style.position = vectorcraft_doc::CharPosition::Superscript(vectorcraft_doc::ScriptMetrics { size: 50.0, position: 40.0 });
    }
    let data = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d));
    app.run("document.open", json!({"name": "scripts.vectorcraft", "dataBase64": data})).unwrap();
    app.run("select.set", json!({"ids": [id.clone()]})).unwrap();
    let runs = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.position).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    let before = runs(&app);
    assert!(before.len() == 2 && before[0] != before[1] && before.iter().all(|p| p.id() == "superscript"), "{before:?}");
    assert_eq!(script_buttons(&ctx, &mut app).1, [false, true, false], "the button shows superscript");
    assert_eq!(app.run("type.superscript", json!({})).unwrap(), json!("normal"));
    assert!(scripts(&app, &id).iter().all(|(_, p)| *p == "normal"), "{:?}", scripts(&app, &id));
}

/// With Real-time Drawing off, Superscript, Subscript and Underline decide from the text with the
/// typing applied: after a Backspace not yet applied takes out the one plain character, the rest
/// is all superscript (or underlined), so a press turns it off.
#[test]
fn superscript_and_underline_decide_from_the_text_with_the_typing_applied() {
    for (command, set, off) in
        [("type.superscript", json!({"position": "superscript"}), json!("normal")), ("type.underline", json!({"underline": true}), json!(false))]
    {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
        app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
        let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "x2", "size": 12})).unwrap()["id"].clone();
        let mut range = set.clone();
        range["id"] = id.clone();
        range["start"] = json!(1);
        range["end"] = json!(2);
        app.run("text.setRangeStyle", range).unwrap();
        app.run("select.set", json!({"ids": [id.clone()]})).unwrap();
        app.select_tool("type");
        app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
        app.session.set_tool_option("select", &json!({"start": 1, "end": 1}));
        let ctx = egui::Context::default();
        let backspace =
            |pressed| egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
        let raw = egui::RawInput { events: vec![backspace(true), backspace(false)], ..Default::default() };
        ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())).textures_delta.clear();
        assert_eq!(app.session.tool_options()["typing"], json!(true), "{command}");
        let node = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind {
            NodeKind::Text(t) => (t.plain_text(), t.runs.iter().map(|r| (r.style.position.id(), r.style.underline)).collect::<Vec<_>>()),
            _ => panic!("text"),
        };
        assert_eq!(node(&app).0, "x2", "{command}: the Backspace is not applied yet");
        assert_eq!(app.run(command, json!({})).unwrap(), off, "{command}");
        assert_eq!(node(&app), ("2".to_string(), vec![("normal", false)]), "{command}");
    }
}

/// The panel menu's Small Caps, Superscript and Subscript set the selected type's small caps
/// and position and show a check mark when on; Superscript and Subscript turn each other off.
#[test]
fn small_caps_superscript_and_subscript_menu_items_set_and_check_the_text() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "E=mc2", "size": 12})).unwrap()["id"].clone();
    let ctx = egui::Context::default();
    let checked = |app: &mut VectorcraftApp| {
        let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu);
        ["Small Caps", "Superscript", "Subscript"].map(|l| texts.iter().any(|(t, _)| *t == format!("โœ“ {l}")))
    };
    assert_eq!(checked(&mut app), [false; 3]);
    let small = Some(app.session.active().unwrap().doc.setup.small_caps_size);
    for (item, runs, shown) in [
        ("Small Caps", (small, "normal"), [true, false, false]),
        ("Superscript", (small, "superscript"), [true, true, false]),
        ("Subscript", (small, "subscript"), [true, false, true]),
        ("Subscript", (small, "normal"), [true, false, false]),
        ("Small Caps", (None, "normal"), [false; 3]),
    ] {
        let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
        let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == item).unwrap_or_else(|| panic!("{item}: {texts:?}")).1;
        super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
        assert_eq!(scripts(&app, &id), [runs], "{item}");
        assert_eq!(checked(&mut app), shown, "{item}");
    }
}

/// The Anti-aliasing Method dropdown under Character Rotation shows the method of the selected
/// type, blank where the selected objects differ, and a pick sets it for the whole object, also
/// while the Type tool has part of its text selected. Reset Panel sets Sharp.
#[test]
fn the_anti_aliasing_method_dropdown_shows_and_sets_the_types_method() {
    use super::super::tests_appearance::{click, frame_events, text_rect};
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hamburg", "size": 12})).unwrap()["id"].as_u64().unwrap();
    let method = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.anti_alias,
        _ => panic!("text"),
    };
    let ctx = egui::Context::default();
    let texts = |app: &mut VectorcraftApp| frame_events(&ctx, app, vec![], show);
    let shown = |app: &mut VectorcraftApp| {
        texts(app).into_iter().map(|(t, _)| t).filter(|t| ["None", "Sharp", "Crisp", "Strong"].contains(&t.as_str())).collect::<Vec<_>>()
    };
    assert_eq!(shown(&mut app), ["Sharp"]);
    // Open the dropdown and pick Crisp.
    let at = text_rect(&texts(&mut app), "Sharp").center();
    click(&ctx, &mut app, at, show);
    let listed = texts(&mut app);
    let crisp = text_rect(&listed, "Crisp").center();
    click(&ctx, &mut app, crisp, show);
    assert_eq!(method(&app, a), TypeAntiAlias::Crisp);
    assert_eq!(shown(&mut app), ["Crisp"]);
    // Another object with Sharp selected as well: blank.
    let b = app.run("text.create", json!({"x": 20, "y": 120, "text": "Bremen", "size": 12})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    assert!(shown(&mut app).is_empty(), "the methods differ");
    // The Type tool with two letters selected: the whole object takes the method.
    app.run("select.set", json!({"ids": [a]})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 1, "end": 3}));
    assert!(text_editing(&app).is_some());
    set_anti_alias(&mut app, TypeAntiAlias::Strong);
    assert_eq!(method(&app, a), TypeAntiAlias::Strong);
    assert_eq!(method(&app, b), TypeAntiAlias::Sharp, "the other selected type is unchanged while editing");
    assert_eq!(shared_anti_alias(&app), Some(TypeAntiAlias::Strong));
    // Reset Panel sets Sharp, with the characters' attributes, in one undo step.
    range_style(&mut app, json!({"tracking": 50}));
    let tracking = |app: &VectorcraftApp| shared(app, |s| s.tracking);
    assert_eq!(tracking(&app), Some(50.0));
    reset_panel(&mut app);
    assert_eq!((method(&app, a), tracking(&app)), (TypeAntiAlias::Sharp, Some(0.0)));
    app.run("edit.undo", json!({})).unwrap();
    assert_eq!((method(&app, a), tracking(&app)), (TypeAntiAlias::Strong, Some(50.0)), "one undo step");
}

/// The Sharp method is named by its own `antiAlias` catalog row, not by the plain "Sharp" row
/// that names the Contour tool's corner.
#[test]
fn the_sharp_method_takes_its_own_translation() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    app.run("text.create", json!({"x": 20, "y": 50, "text": "Hamburg", "size": 12})).unwrap();
    let de = crate::i18n::Lang::from_code("de").unwrap();
    let (method, corner) = (crate::i18n::tr_ctx(de, "antiAlias", "Sharp"), crate::i18n::tr(de, "Sharp"));
    assert_ne!(method, corner, "the catalog names the two differently");
    crate::i18n::set_current(de);
    let text = crate::tests_labels::painted_text(&mut app, show);
    crate::i18n::set_current(crate::i18n::Lang::EN);
    assert!(text.contains(method) && !text.contains(corner), "{text}");
}

/// Reset Panel closes only the undo group it opens: in an undo group that is already open,
/// the reset is part of that group's step, and an undo group open in another document stays
/// open, with that document's later edits part of its step.
#[test]
fn reset_panel_closes_only_its_own_undo_group() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "A"})).unwrap()["id"].clone();
    let steps = |st: &vectorcraft_engine::DocState| (st.history.undo.len(), st.history.undo.last().map(|e| e.label.clone()));
    // An undo group open in the same document (MCP `command_batch` with `atomic`).
    app.run("edit.undoGroup.begin", json!({"label": "Batch"})).unwrap();
    app.run("text.setFormat", json!({"id": a, "antiAlias": "crisp"})).unwrap();
    reset_panel(&mut app);
    assert!(app.session.active().unwrap().undo_group.is_some(), "the batch's undo group stays open");
    app.run("text.setFormat", json!({"id": a, "antiAlias": "strong"})).unwrap();
    app.run("edit.undoGroup.end", json!({})).unwrap();
    let a_steps = steps(app.session.active().unwrap());
    assert_eq!(a_steps.1, Some("Batch".to_string()), "the reset is part of the Batch step");
    // An undo group open in another document. The second document is open before the group
    // begins, so switching to it opens no group there.
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    assert_eq!(app.session.active_index(), Some(1));
    let b = app.run("text.create", json!({"x": 20, "y": 50, "text": "B"})).unwrap()["id"].clone();
    // A reset that changes nothing records no step, so B starts away from the panel's defaults.
    app.run("text.setFormat", json!({"id": b, "antiAlias": "crisp"})).unwrap();
    app.session.set_active(0);
    app.run("edit.undoGroup.begin", json!({"label": "Batch"})).unwrap();
    app.run("text.setFormat", json!({"id": a, "antiAlias": "none"})).unwrap();
    let a_steps = steps(app.session.active().unwrap());
    app.session.set_active(1);
    assert!(app.session.active().unwrap().undo_group.is_none());
    app.run("select.set", json!({"ids": [b]})).unwrap();
    let b_steps = steps(app.session.active().unwrap()).0;
    reset_panel(&mut app);
    assert_eq!(steps(app.session.active().unwrap()), (b_steps + 1, Some("Reset Panel".to_string())));
    assert!(app.session.active().unwrap().undo_group.is_none());
    assert!(app.session.documents()[0].undo_group.is_some(), "the other document's undo group stays open");
    app.session.set_active(0);
    app.run("text.setFormat", json!({"id": a, "antiAlias": "crisp"})).unwrap();
    app.run("edit.undoGroup.end", json!({})).unwrap();
    assert_eq!(steps(app.session.active().unwrap()), a_steps, "the later edit is part of the Batch step");
}

/// Character panel menu โ€บ System Layout is off for a new document, and a click turns whole-point
/// spacing on and back off for every text object.
#[test]
fn system_layout_menu_item_toggles_the_document() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hi", "size": 13})).unwrap()["id"].as_u64().unwrap();
    let ctx = egui::Context::default();
    let on = |app: &VectorcraftApp| {
        let st = app.session.active().unwrap();
        let object = match &st.doc.node(NodeId(id)).unwrap().kind {
            NodeKind::Text(t) => t.system_layout,
            _ => panic!("text"),
        };
        (st.doc.setup.system_layout, object)
    };
    let row = |app: &mut VectorcraftApp| {
        let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu);
        texts.into_iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "System Layout")
    };
    assert_eq!(on(&app), (false, false));
    assert!(row(&mut app).is_some_and(|(t, _)| !t.starts_with('โœ“')));
    let at = row(&mut app).unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert_eq!(on(&app), (true, true));
    assert!(row(&mut app).is_some_and(|(t, _)| t.starts_with('โœ“')));
    let at = row(&mut app).unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert_eq!(on(&app), (false, false));
    assert!(row(&mut app).is_some_and(|(t, _)| !t.starts_with('โœ“')));
}

/// Character panel menu โ€บ Fractional Widths is on for new type, and a click turns it off and
/// back on for the whole type object.
#[test]
fn fractional_widths_menu_item_toggles_the_type_object() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hi", "size": 13})).unwrap()["id"].as_u64().unwrap();
    let ctx = egui::Context::default();
    let flag = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.fractional_widths,
        _ => panic!("text"),
    };
    let row = |app: &mut VectorcraftApp| {
        let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu);
        texts.into_iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "Fractional Widths")
    };
    assert!(flag(&app));
    assert!(row(&mut app).is_some_and(|(t, _)| t.starts_with('โœ“')));
    let at = row(&mut app).unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(!flag(&app));
    assert!(row(&mut app).is_some_and(|(t, _)| !t.starts_with('โœ“')));
    let at = row(&mut app).unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(flag(&app));
    assert!(row(&mut app).is_some_and(|(t, _)| t.starts_with('โœ“')));
}

/// Character Alignment and Proportional Metrics are in the panel menu with the East Asian
/// options only (as Mojikumi Set and Top-to-Top Leading are in the Paragraph panel).
#[test]
fn character_alignment_shows_with_the_east_asian_options() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "้›…ๆฅฝ"})).unwrap()["id"].clone();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let shown = |app: &mut VectorcraftApp| {
        let text = crate::tests_labels::painted_text(app, menu);
        (text.contains("Character Alignment"), text.contains("Proportional Metrics"))
    };
    assert_eq!(shown(&mut app), (false, false));
    app.session.prefs.show_east_asian_options = true;
    assert_eq!(shown(&mut app), (true, true));
}

/// Insert Aki Left and Right are fields of the panel with the East Asian options only, and show
/// the selected characters' values, blank where they differ. A value typed past 1000 sets 1000.
#[test]
fn insert_aki_fields_show_with_the_east_asian_options() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "๏ผˆๆ—ฅๆœฌ๏ผ‰"})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.run("text.setFormat", json!({"akiLeft": 250, "akiRight": 750})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(!text.contains("โ†”A") && !text.contains("750"), "{text}");
    app.session.prefs.show_east_asian_options = true;
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(text.contains("โ†”A") && text.contains("Aโ†”") && text.contains("250") && text.contains("750"), "{text}");
    // Only the first character has 750 after it: the Right field is blank.
    app.run("text.setRangeStyle", json!({"id": id, "start": 3, "end": 12, "akiRight": 0})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(text.contains("250") && !text.contains("750"), "{text}");
    use super::super::tests_appearance::{click, frame_events, text_rect};
    let ctx = egui::Context::default();
    let texts = frame_events(&ctx, &mut app, vec![], show);
    click(&ctx, &mut app, text_rect(&texts, "250").center(), show);
    let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
    frame_events(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)], show);
    frame_events(&ctx, &mut app, vec![egui::Event::Text("1500".into())], show);
    frame_events(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], show);
    frame_events(&ctx, &mut app, vec![], show);
    let left = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.aki_left).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    assert!(left(&app).iter().all(|v| *v == 1000.0), "{:?}", left(&app));
}

/// Adjust Horizontal and Vertical Diacritic Position are fields of the panel with the Middle
/// Eastern options only, and show the selected characters' values, blank where they differ. A value
/// typed past -1000 sets -1000. Bad values sent to the commands are errors that change nothing.
#[test]
fn diacritic_position_fields_show_with_the_middle_eastern_options() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "ุจูŽุจูŽ"})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.run("text.setFormat", json!({"diacriticHorizontal": 125, "diacriticVertical": -375})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(!text.contains("ยดโ†”") && !text.contains("-375"), "{text}");
    app.session.prefs.show_indic_options = true;
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(text.contains("ยดโ†”") && text.contains("ยดโ†•") && text.contains("125") && text.contains("-375"), "{text}");
    let undo = app.session.active().unwrap().history.undo.len();
    let doc = app.session.active().unwrap().doc.clone();
    for (cmd, params) in [
        ("text.setFormat", json!({"diacriticHorizontal": 1000.5})),
        ("text.setFormat", json!({"diacriticVertical": "up"})),
        ("text.setRangeStyle", json!({"id": id, "start": 0, "end": 2, "diacriticVertical": -1001})),
        ("text.setRangeStyle", json!({"id": id, "start": 0, "end": 2, "diacriticHorizontal": true})),
    ] {
        let error = app.run(cmd, params.clone()).unwrap_err().to_string();
        assert!(error.contains("`diacritic"), "{cmd} {params}: {error}");
    }
    assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
    assert!(app.session.active().unwrap().doc == doc);
    // Setting the value the characters already have records no undo step.
    app.run("text.setFormat", json!({"diacriticVertical": -375})).unwrap();
    assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
    // Only the first letter and its fatha have -375: the Vertical field is blank.
    app.run("text.setRangeStyle", json!({"id": id, "start": 4, "end": 8, "diacriticVertical": 0})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(text.contains("125") && !text.contains("-375"), "{text}");
    use super::super::tests_appearance::{click, frame_events, text_rect};
    let ctx = egui::Context::default();
    let texts = frame_events(&ctx, &mut app, vec![], show);
    click(&ctx, &mut app, text_rect(&texts, "125").center(), show);
    let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
    frame_events(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)], show);
    frame_events(&ctx, &mut app, vec![egui::Event::Text("-1500".into())], show);
    frame_events(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], show);
    frame_events(&ctx, &mut app, vec![], show);
    let horizontal = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.diacritic_horizontal).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    assert!(horizontal(&app).iter().all(|v| *v == -1000.0), "{:?}", horizontal(&app));
}

/// Tsume is a field of the panel with the East Asian options only, and shows the selected
/// characters' value, blank where they differ. A value typed past 100 sets 100.
#[test]
fn tsume_field_shows_with_the_east_asian_options() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "๏ผˆๆ—ฅๆœฌ๏ผ‰"})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.run("text.setFormat", json!({"tsume": 37.5})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(!text.contains("โ†’Aโ†") && !text.contains("37.5"), "{text}");
    app.session.prefs.show_east_asian_options = true;
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(text.contains("โ†’Aโ†") && text.contains("37.5"), "{text}");
    // The characters differ: the field is blank.
    app.run("text.setRangeStyle", json!({"id": id, "start": 3, "end": 12, "tsume": 62.5})).unwrap();
    let text = crate::tests_labels::painted_text(&mut app, show);
    assert!(!text.contains("37.5") && !text.contains("62.5"), "{text}");
    app.run("text.setFormat", json!({"tsume": 62.5})).unwrap();
    use super::super::tests_appearance::{click, frame_events, text_rect};
    let ctx = egui::Context::default();
    let texts = frame_events(&ctx, &mut app, vec![], show);
    click(&ctx, &mut app, text_rect(&texts, "62.5%").center(), show);
    let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
    frame_events(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)], show);
    frame_events(&ctx, &mut app, vec![egui::Event::Text("150".into())], show);
    frame_events(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], show);
    frame_events(&ctx, &mut app, vec![], show);
    let tsume = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.tsume).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    assert!(tsume(&app).iter().all(|v| *v == 100.0), "{:?}", tsume(&app));
}

/// The panel menu's Show Font Height Options shows the Set Font Height Reference dropdown,
/// which shows the selected type's reference and sets the one picked (one undo step); Hide
/// Font Height Options hides it again.
#[test]
fn show_font_height_options_shows_the_font_height_reference() {
    use super::super::tests_appearance::{click, frame_events, text_rect};
    use vectorcraft_doc::FontHeightReference as R;
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 12})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let reference = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.font_height_reference).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    let ctx = egui::Context::default();
    crate::theme::install_fonts(&ctx);
    let texts = |ctx: &egui::Context, app: &mut VectorcraftApp, f: fn(&mut VectorcraftApp, &mut Ui)| {
        frame_events(ctx, app, vec![], f);
        frame_events(ctx, app, vec![], f)
    };
    // A menu item's label is drawn after its check column (a check mark or spaces).
    let item = |texts: &[(String, egui::Rect)], s: &str| texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == s).map(|(_, r)| r.center());
    assert!(item(&texts(&ctx, &mut app, show), "Em Box").is_none());
    let at = item(&texts(&ctx, &mut app, menu), "Show Font Height Options").unwrap();
    click(&ctx, &mut app, at, menu);
    assert!(item(&texts(&ctx, &mut app, menu), "Hide Font Height Options").is_some());
    let panel = texts(&ctx, &mut app, show);
    assert!(item(&panel, "Em Box").is_some(), "{panel:?}");
    // Pick Cap Height from the dropdown.
    click(&ctx, &mut app, text_rect(&panel, "Em Box").center(), show);
    let undo = app.session.active().unwrap().history.undo.len();
    let open = texts(&ctx, &mut app, show);
    click(&ctx, &mut app, text_rect(&open, "Cap Height").center(), show);
    assert_eq!(reference(&app), [R::CapHeight]);
    assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
    assert!(item(&texts(&ctx, &mut app, show), "Cap Height").is_some());
    let at = item(&texts(&ctx, &mut app, menu), "Hide Font Height Options").unwrap();
    click(&ctx, &mut app, at, menu);
    assert!(item(&texts(&ctx, &mut app, show), "Cap Height").is_none());
}

/// The Set Font Height Reference dropdown shows an icon before each reference's name, in the
/// closed field and in the open list, and each reference's icon is its own (#6304).
#[test]
fn font_height_references_show_their_icons() {
    use super::super::tests_appearance::click;
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 12})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    crate::theme::install_fonts(&ctx);
    set_pstate(&ctx, FONT_HEIGHT_OPTIONS, true);
    // Every text drawn with its rect, and the rects of every other shape drawn.
    let frame = |ctx: &egui::Context, app: &mut VectorcraftApp| {
        let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
        out.textures_delta.clear();
        fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, marks: &mut Vec<egui::Rect>) {
            match s {
                egui::Shape::Text(t) => texts.push((t.galley.text().to_string(), t.visual_bounding_rect())),
                egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, marks)),
                egui::Shape::Noop => {}
                s => marks.push(s.visual_bounding_rect()),
            }
        }
        let (mut texts, mut marks) = (vec![], vec![]);
        for c in &out.shapes {
            collect(&c.shape, &mut texts, &mut marks);
        }
        (texts, marks)
    };
    // The shapes in the icon's place before the text `rect`, relative to that place and rounded.
    let icon = |marks: &[egui::Rect], rect: egui::Rect| {
        let place = egui::Rect::from_min_max(
            egui::pos2(rect.min.x - FONT_HEIGHT_ICON - 8.0, rect.center().y - 10.0),
            egui::pos2(rect.min.x, rect.center().y + 10.0),
        );
        let mut found: Vec<[i32; 4]> = marks
            .iter()
            .filter(|m| m.is_finite() && place.contains_rect(**m))
            .map(|m| [m.min.x - place.min.x, m.min.y - place.min.y, m.max.x - place.min.x, m.max.y - place.min.y].map(|v| v.round() as i32))
            .collect();
        found.sort_unstable();
        found
    };
    frame(&ctx, &mut app);
    let (texts, marks) = frame(&ctx, &mut app);
    let field = texts.iter().find(|(t, _)| t == "Em Box").map(|(_, r)| *r).expect("the closed field shows Em Box");
    assert!(icon(&marks, field).len() >= 2, "no icon before Em Box in the closed field: {:?}", icon(&marks, field));
    click(&ctx, &mut app, field.center(), show);
    frame(&ctx, &mut app);
    let (texts, marks) = frame(&ctx, &mut app);
    let mut icons = vec![];
    for name in ["Em Box", "Cap Height", "x-Height", "ICF Box"] {
        // The list's row is the last text of that name drawn (the closed field is drawn first).
        let row = texts.iter().rev().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("the open list shows {name}: {texts:?}"));
        let found = icon(&marks, row);
        assert!(found.len() >= 2, "no icon before {name} in the open list: {found:?}");
        icons.push(found);
    }
    for (i, a) in icons.iter().enumerate() {
        assert!(icons.iter().skip(i + 1).all(|b| a != b), "two references share an icon: {icons:?}");
    }
}

/// In the open Set Font Height Reference list, the current reference's row is drawn on the
/// accent-tinted selection fill, so its icon draws the measure in the name's colour rather than
/// the accent, which would lose its contrast there; the other rows keep the accent (#6304).
#[test]
fn the_highlighted_font_height_icon_keeps_its_contrast() {
    use super::super::tests_appearance::click;
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 12})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    crate::theme::install_fonts(&ctx);
    set_pstate(&ctx, FONT_HEIGHT_OPTIONS, true);
    let accent = Tokens::get(&ctx).accent;
    // Every text drawn with its rect, and every stroke drawn with its rect and colour.
    let frame = |ctx: &egui::Context, app: &mut VectorcraftApp| {
        let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
        out.textures_delta.clear();
        fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, strokes: &mut Vec<(egui::Rect, egui::Color32)>) {
            match s {
                egui::Shape::Text(t) => texts.push((t.galley.text().to_string(), t.visual_bounding_rect())),
                egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, strokes)),
                egui::Shape::LineSegment { stroke, .. } => strokes.push((s.visual_bounding_rect(), stroke.color)),
                egui::Shape::Path(p) => {
                    if let egui::epaint::ColorMode::Solid(c) = p.stroke.color {
                        strokes.push((s.visual_bounding_rect(), c));
                    }
                }
                egui::Shape::Rect(r) => strokes.push((s.visual_bounding_rect(), r.stroke.color)),
                _ => {}
            }
        }
        let (mut texts, mut strokes) = (vec![], vec![]);
        for c in &out.shapes {
            collect(&c.shape, &mut texts, &mut strokes);
        }
        (texts, strokes)
    };
    // The stroke colours in the icon's place before the text `rect`.
    let colours = |strokes: &[(egui::Rect, egui::Color32)], rect: egui::Rect| -> Vec<egui::Color32> {
        let place = egui::Rect::from_min_max(
            egui::pos2(rect.min.x - FONT_HEIGHT_ICON - 8.0, rect.center().y - 10.0),
            egui::pos2(rect.min.x, rect.center().y + 10.0),
        );
        strokes.iter().filter(|(r, _)| r.is_finite() && place.contains_rect(*r)).map(|(_, c)| *c).collect()
    };
    frame(&ctx, &mut app);
    let (texts, _) = frame(&ctx, &mut app);
    let field = texts.iter().find(|(t, _)| t == "Em Box").map(|(_, r)| *r).expect("the closed field shows Em Box");
    click(&ctx, &mut app, field.center(), show);
    frame(&ctx, &mut app);
    let (texts, strokes) = frame(&ctx, &mut app);
    let row = |name: &str| texts.iter().rev().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("the open list shows {name}"));
    // The list fades in, so colours are compared without their alpha.
    let rgb = |c: egui::Color32| {
        let [r, g, b, _] = c.to_srgba_unmultiplied();
        [r, g, b]
    };
    let is_accent = |c: &egui::Color32| rgb(*c).iter().zip(rgb(accent)).all(|(a, b)| a.abs_diff(b) <= 4);
    let current = colours(&strokes, row("Em Box"));
    assert!(!current.is_empty() && !current.iter().any(is_accent), "the highlighted Em Box icon draws in the accent: {current:?}");
    let other = colours(&strokes, row("Cap Height"));
    assert!(other.iter().any(is_accent), "the other rows keep the accent measure: {other:?}");
}

/// Tate-chu-yoko is in the panel menu with the East Asian options, and choosing it marks the
/// selected characters.
#[test]
fn tate_chu_yoko_menu_item_shows_with_east_asian_options_and_toggles() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "2026"})).unwrap()["id"].as_u64().unwrap();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    let painted = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, menu);
    assert!(!painted(&mut app).contains("Tate-chu-yoko"));
    app.session.prefs.show_east_asian_options = true;
    let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().all(|r| r.style.tate_chu_yoko),
        _ => panic!("text"),
    };
    assert!(!on(&app));
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "Tate-chu-yoko").unwrap_or_else(|| panic!("{texts:?}")).1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(on(&app));
    assert!(painted(&mut app).contains("โœ“ Tate-chu-yoko"));
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "Tate-chu-yoko").unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(!on(&app));
}

/// Tate-chu-yoko Settingsโ€ฆ is in the panel menu with the East Asian options, and choosing it opens
/// the dialog on the selected characters.
#[test]
fn tate_chu_yoko_settings_menu_item_shows_with_east_asian_options_and_opens_the_dialog() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "2026"})).unwrap()["id"].as_u64().unwrap();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    assert!(!crate::tests_labels::painted_text(&mut app, menu).contains("Tate-chu-yoko Settingsโ€ฆ"));
    app.session.prefs.show_east_asian_options = true;
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim() == "Tate-chu-yoko Settingsโ€ฆ").unwrap_or_else(|| panic!("{texts:?}")).1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::tate_chu_yoko::KIND));
}

/// Warichu and Warichu Settingsโ€ฆ are in the panel menu with the East Asian options: Warichu marks
/// the selected characters and takes the mark off again, one undo step each way, and Warichu
/// Settingsโ€ฆ opens the dialog on them.
#[test]
fn warichu_menu_items_show_with_east_asian_options_toggle_and_open_the_settings() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "abcd"})).unwrap()["id"].as_u64().unwrap();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    let painted = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, menu);
    assert!(!painted(&mut app).contains("Warichu"));
    app.session.prefs.show_east_asian_options = true;
    let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().all(|r| r.style.warichu),
        _ => panic!("text"),
    };
    let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
    let before = undo(&app);
    let find = |ctx: &egui::Context, app: &mut VectorcraftApp, label: &str| {
        let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu);
        texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == label).unwrap_or_else(|| panic!("{texts:?}")).1
    };
    let at = find(&ctx, &mut app, "Warichu");
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(on(&app));
    assert_eq!(undo(&app), before + 1);
    assert!(painted(&mut app).contains("โœ“ Warichu"));
    let at = find(&ctx, &mut app, "Warichu");
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(!on(&app));
    assert_eq!(undo(&app), before + 2);
    let at = find(&ctx, &mut app, "Warichu Settingsโ€ฆ");
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::warichu::KIND));
}

/// Standard Vertical Roman Alignment is in the panel menu with the East Asian options. Choosing it
/// marks the selected characters, one undo step each way; its check shows only while every
/// selected character has it, and a mixed selection turns it on.
#[test]
fn standard_vertical_roman_alignment_menu_item_toggles() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "ABC"})).unwrap()["id"].as_u64().unwrap();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    let label = "Standard Vertical Roman Alignment";
    assert!(!crate::tests_labels::painted_text(&mut app, menu).contains(label));
    app.session.prefs.show_east_asian_options = true;
    let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().all(|r| r.style.standard_vertical_roman),
        _ => panic!("text"),
    };
    // Only the first letter has it: the item is unchecked.
    app.session.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 1, "standardVerticalRoman": true})).unwrap();
    let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
    let before = undo(&app);
    assert!(!on(&app));
    assert!(!crate::tests_labels::painted_text(&mut app, menu).contains(&format!("โœ“ {label}")));
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == label).unwrap_or_else(|| panic!("{texts:?}")).1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(on(&app));
    assert_eq!(undo(&app), before + 1);
    assert!(crate::tests_labels::painted_text(&mut app, menu).contains(&format!("โœ“ {label}")));
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == label).unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(!on(&app));
    assert_eq!(undo(&app), before + 2);
}

/// Digits is in the panel menu with the Middle Eastern (Indic) options only, as Paragraph
/// Direction is in the Paragraph panel.
#[test]
fn digits_show_with_the_indic_options() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "ุตูุญุฉ 3"})).unwrap()["id"].clone();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let shown = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, menu).contains("Digits");
    assert!(!shown(&mut app));
    app.session.prefs.show_indic_options = true;
    assert!(shown(&mut app));
}

/// The Digits submenu lists Default, the Arabic-script numeral systems and the Indic scripts'
/// digits (#4942), and checks the selected characters' system.
#[test]
fn digits_submenu_lists_the_indic_scripts_and_checks_the_selection() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    let text = crate::tests_labels::painted_text(&mut app, |app, ui| digits_items(app, ui, Some(vectorcraft_doc::Digits::Tamil)));
    let items: Vec<_> = text.lines().map(|l| l.trim().trim_start_matches("โœ“ ")).collect();
    let want =
        ["Default", "Arabic", "Hindi", "Farsi", "Devanagari", "Bengali", "Gurmukhi", "Gujarati", "Odia", "Tamil", "Telugu", "Kannada", "Malayalam"];
    assert!(want.iter().all(|w| items.contains(w)), "{items:?}");
    assert_eq!(text.lines().filter_map(|l| l.strip_prefix("โœ“ ")).collect::<Vec<_>>(), ["Tamil"]);
}

/// Character Direction is in the panel menu with the Middle Eastern (Indic) options, beside
/// Digits. Its submenu checks the direction the characters the panel acts on share: the
/// selected type's, or the range the Type tool has selected. It checks no item when they differ.
#[test]
fn character_direction_checks_the_direction_of_the_selection() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "ืฉืœื•ื 21 10 2026"})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let shown = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, menu).contains("Character Direction");
    assert!(!shown(&mut app));
    app.session.prefs.show_indic_options = true;
    assert!(shown(&mut app));
    let checked = |app: &mut VectorcraftApp| {
        let text = crate::tests_labels::painted_text(app, char_direction_items);
        text.lines().filter_map(|l| l.strip_prefix("โœ“ ")).map(str::to_string).collect::<Vec<_>>()
    };
    assert_eq!(checked(&mut app), ["Default"]);
    app.run("text.setRangeStyle", json!({"id": id, "start": 9, "end": 19, "charDirection": "leftToRight"})).unwrap();
    // The object's characters differ: nothing is checked.
    assert!(checked(&mut app).is_empty());
    // The Type tool's selection: the date, then the Hebrew word.
    app.select_tool("type");
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 9, "end": 19}));
    assert_eq!(checked(&mut app), ["Left to Right"]);
    app.session.set_tool_option("select", &json!({"start": 0, "end": 8}));
    assert_eq!(checked(&mut app), ["Default"]);
}

#[test]
fn shared_text_flag_optical_margin_three_object_selections() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({})).unwrap();
    let a = app.run("text.create", json!({"x": 10, "y": 40, "text": "a"})).unwrap()["id"].clone();
    let b = app.run("text.create", json!({"x": 10, "y": 80, "text": "b"})).unwrap()["id"].clone();
    let c = app.run("text.create", json!({"x": 10, "y": 120, "text": "c"})).unwrap()["id"].clone();
    app.run("type.opticalMarginAlignment", json!({"on": true, "id": a})).unwrap();
    app.run("type.opticalMarginAlignment", json!({"on": false, "id": b})).unwrap();
    app.run("type.opticalMarginAlignment", json!({"on": false, "id": c})).unwrap();
    app.run("select.set", json!({"ids": [a.clone(), b.clone(), c.clone()]})).unwrap();
    assert_eq!(shared_text_flag(&app, |t| t.optical_margin), None);
    app.run("type.opticalMarginAlignment", json!({"on": false, "id": a})).unwrap();
    app.run("type.opticalMarginAlignment", json!({"on": true, "id": b})).unwrap();
    app.run("type.opticalMarginAlignment", json!({"on": true, "id": c})).unwrap();
    app.run("select.set", json!({"ids": [a.clone(), b.clone(), c.clone()]})).unwrap();
    assert_eq!(shared_text_flag(&app, |t| t.optical_margin), None);
    app.run("type.opticalMarginAlignment", json!({"on": true, "id": a})).unwrap();
    app.run("type.opticalMarginAlignment", json!({"on": true, "id": b})).unwrap();
    app.run("type.opticalMarginAlignment", json!({"on": true, "id": c})).unwrap();
    app.run("select.set", json!({"ids": [a, b, c]})).unwrap();
    assert_eq!(shared_text_flag(&app, |t| t.optical_margin), Some(true));
}

#[test]
fn shared_text_flag_vertical_three_object_selections() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({})).unwrap();
    let v0 = app.run("text.create", json!({"x": 10, "y": 40, "text": "v0", "vertical": true})).unwrap()["id"].clone();
    let h1 = app.run("text.create", json!({"x": 10, "y": 80, "text": "h1"})).unwrap()["id"].clone();
    let h2 = app.run("text.create", json!({"x": 10, "y": 120, "text": "h2"})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [v0.clone(), h1.clone(), h2.clone()]})).unwrap();
    assert_eq!(shared_text_flag(&app, |t| t.vertical), None);
    let h0 = app.run("text.create", json!({"x": 10, "y": 160, "text": "h0"})).unwrap()["id"].clone();
    let v1 = app.run("text.create", json!({"x": 10, "y": 200, "text": "v1", "vertical": true})).unwrap()["id"].clone();
    let v2 = app.run("text.create", json!({"x": 10, "y": 240, "text": "v2", "vertical": true})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [h0.clone(), v1.clone(), v2.clone()]})).unwrap();
    assert_eq!(shared_text_flag(&app, |t| t.vertical), None);
    app.run("select.set", json!({"ids": [v0.clone(), v1.clone(), v2.clone()]})).unwrap();
    assert_eq!(shared_text_flag(&app, |t| t.vertical), Some(true));
}

/// Small Caps, Superscript and Subscript buttons and menu items stay off when the selection mixes them.
#[test]
fn character_mixed_small_caps_and_position_show_off() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "A"})).unwrap()["id"].clone();
    let b = app.run("text.create", json!({"x": 20, "y": 90, "text": "B"})).unwrap()["id"].clone();
    app.run("text.setRangeStyle", json!({"id": a, "start": 0, "end": 1, "smallCaps": true, "position": "superscript"})).unwrap();
    app.run("text.setRangeStyle", json!({"id": b, "start": 0, "end": 1, "smallCaps": false, "position": "subscript"})).unwrap();
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    assert_eq!(shared(&app, |s| s.small_caps.is_some()), None);
    assert_eq!(shared(&app, |s| s.position), None);
    let ctx = egui::Context::default();
    assert_eq!(script_buttons(&ctx, &mut app).1, [false, false, false]);
    let checked = |app: &mut VectorcraftApp| {
        let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu);
        ["Small Caps", "Superscript", "Subscript"].map(|l| texts.iter().any(|(t, _)| *t == format!("โœ“ {l}")))
    };
    assert_eq!(checked(&mut app), [false, false, false]);
}

/// The All Caps, Underline and Strikethrough buttons are drawn off when only some of the selected
/// characters have them, and a click turns them on for every character.
#[test]
fn mixed_all_caps_underline_and_strikethrough_buttons_show_off_and_turn_on() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap();
    app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "allCaps": true, "underline": true, "strikethrough": true})).unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let flags = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| [r.style.all_caps, r.style.underline, r.style.strikethrough]).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    let ctx = egui::Context::default();
    let (at, lit) = style_buttons(&ctx, &mut app);
    assert_eq!([lit[0], lit[4], lit[5]], [false; 3]);
    for (i, button) in [0, 4, 5].into_iter().enumerate() {
        super::super::tests_appearance::click(&ctx, &mut app, at[button], show);
        assert!(flags(&app).iter().all(|f| f[i]), "button {button}: {:?}", flags(&app));
        assert!(style_buttons(&ctx, &mut app).1[button], "button {button}");
    }
}

/// `type.underline` does what the Underline button does: with only some of the selected characters
/// underlined it underlines all of them, and with all of them underlined it turns underlining off.
#[test]
fn underline_command_underlines_a_mixed_selection() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap();
    app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "underline": true})).unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let underlined = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.underline).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    assert_eq!(super::toggle_underline(&mut app), Ok(json!(true)));
    assert!(underlined(&app).iter().all(|u| *u), "{:?}", underlined(&app));
    assert_eq!(super::toggle_underline(&mut app), Ok(json!(false)));
    assert!(underlined(&app).iter().all(|u| !*u), "{:?}", underlined(&app));
}

/// The panel menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and
/// No Break are unchecked when only some of the selected characters have them, and choosing one
/// turns it on for every character.
#[test]
fn mixed_check_items_show_unchecked_and_turn_on() {
    type Attribute = fn(&CharStyle) -> bool;
    let items: [(&str, &str, Attribute); 6] = [
        ("All Caps", "allCaps", |s| s.all_caps),
        ("Underline", "underline", |s| s.underline),
        ("Strikethrough", "strikethrough", |s| s.strikethrough),
        ("Proportional Metrics", "proportionalMetrics", |s| s.proportional_metrics),
        ("Tate-chu-yoko", "tateChuYoko", |s| s.tate_chu_yoko),
        ("No Break", "noBreak", |s| s.no_break),
    ];
    let mut wrong = vec![];
    for (label, key, has) in items {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.session.prefs.show_east_asian_options = true;
        app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
        let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB"})).unwrap()["id"].as_u64().unwrap();
        app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, key: true})).unwrap();
        app.run("select.set", json!({"ids": [id]})).unwrap();
        let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
            NodeKind::Text(t) => t.runs.iter().map(|r| has(&r.style)).collect::<Vec<_>>(),
            _ => panic!("text"),
        };
        assert_eq!(on(&app), [true, false], "{label}");
        let ctx = egui::Context::default();
        let row = |app: &mut VectorcraftApp| {
            let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu);
            texts.into_iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == label).unwrap_or_else(|| panic!("{label} missing"))
        };
        let (text, at) = row(&mut app);
        super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
        let shown = row(&mut app).0;
        if text.starts_with('โœ“') || !on(&app).iter().all(|o| *o) || !shown.starts_with('โœ“') {
            wrong.push(format!("{label}: shown as {text:?}, then {:?} and {shown:?}", on(&app)));
        }
    }
    assert!(wrong.is_empty(), "{wrong:#?}");
}

/// The panel menu's Character Alignment and Digits submenus check no item when the selected
/// characters differ, and check the value they share.
#[test]
fn character_alignment_and_digits_check_nothing_for_a_mixed_selection() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.session.prefs.show_east_asian_options = true;
    app.session.prefs.show_indic_options = true;
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "A1"})).unwrap()["id"].as_u64().unwrap();
    app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "charAlign": "emBoxTop", "digits": "hindi"})).unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let press = |pos: egui::Pos2, pressed: bool| egui::Event::PointerButton {
        pos,
        button: egui::PointerButton::Primary,
        pressed,
        modifiers: Default::default(),
    };
    let ticked = |texts: &[(String, egui::Rect)]| texts.iter().filter_map(|(t, _)| t.strip_prefix("โœ“ ")).map(str::to_string).collect::<Vec<_>>();
    // The items checked in the submenu `name` opens (not in the panel menu itself), in a fresh
    // context, so that no other submenu is open.
    let checked = |app: &mut VectorcraftApp, name: &str| {
        let ctx = egui::Context::default();
        crate::theme::install_fonts(&ctx);
        let mut frame = |events: Vec<egui::Event>| super::super::tests_appearance::frame_events(&ctx, app, events, menu);
        let texts = frame(vec![]);
        let before = ticked(&texts);
        let sub = texts.iter().find(|(t, _)| t.trim() == name).unwrap_or_else(|| panic!("{name} missing from {texts:?}")).1.center();
        for e in [egui::Event::PointerMoved(sub), press(sub, true), press(sub, false)] {
            frame(vec![e]);
        }
        let texts = frame(vec![]);
        assert!(texts.iter().any(|(t, _)| t.contains("Roman Baseline") || t.contains("Hindi")), "{name} did not open: {texts:?}");
        ticked(&texts).into_iter().filter(|t| !before.contains(t)).collect::<Vec<_>>()
    };
    let mixed = (checked(&mut app, "Character Alignment"), checked(&mut app, "Digits"));
    assert_eq!(mixed, (vec![], vec![]));
    app.run("text.setRangeStyle", json!({"id": id, "charAlign": "emBoxTop", "digits": "hindi"})).unwrap();
    let same = (checked(&mut app, "Character Alignment"), checked(&mut app, "Digits"));
    assert_eq!(same, (vec!["Em Box Top/Right".to_string()], vec!["Hindi".to_string()]));
}

/// At a caret in text the Type tool edits, with no characters selected, the Character
/// Direction items are disabled: a click on one leaves the direction of every character as it was.
#[test]
fn character_direction_does_nothing_at_an_empty_caret() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "ืฉืœื•ื 21 10 2026"})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.select_tool("type");
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 3, "end": 3}));
    let directions = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.char_direction)).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    let before = directions(&app);
    let ctx = egui::Context::default();
    let click_rtl = |app: &mut VectorcraftApp| {
        let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], char_direction_items);
        let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "Right to Left").unwrap_or_else(|| panic!("{texts:?}")).1;
        super::super::tests_appearance::click(&ctx, app, at.center(), char_direction_items);
    };
    click_rtl(&mut app);
    assert_eq!(directions(&app), before);
    // With characters selected, the same click sets their direction.
    app.session.set_tool_option("select", &json!({"start": 0, "end": 4}));
    click_rtl(&mut app);
    assert_ne!(directions(&app), before);
}

/// No Break is in the panel menu, and choosing it marks the selected characters.
#[test]
fn no_break_menu_item_toggles_the_selected_characters() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Hello"})).unwrap()["id"].as_u64().unwrap();
    app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    let painted = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, menu);
    assert!(painted(&mut app).contains("No Break"));
    assert!(!painted(&mut app).contains("โœ“ No Break"));
    let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().all(|r| r.style.no_break),
        _ => panic!("text"),
    };
    assert!(!on(&app));
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "No Break").unwrap_or_else(|| panic!("{texts:?}")).1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(on(&app));
    assert!(painted(&mut app).contains("โœ“ No Break"));
    let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
    let at = texts.iter().find(|(t, _)| t.trim_start_matches(['โœ“', ' ']) == "No Break").unwrap().1;
    super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu);
    assert!(!on(&app));
}

/// Kashidas appears with Middle Eastern options, starts checked, and a mixed selection is
/// unchecked until the user enables all of its characters.
#[test]
fn kashidas_menu_item_handles_default_and_mixed_ranges() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.session.prefs.show_indic_options = true;
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB"})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    let row = |app: &mut VectorcraftApp| {
        super::super::tests_appearance::frame_events(&ctx, app, vec![], menu)
            .into_iter()
            .find(|(text, _)| text.trim_start_matches(['โœ“', ' ']) == "Kashidas")
            .expect("Kashidas menu item")
    };
    assert!(row(&mut app).0.starts_with('โœ“'));
    app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "kashidas": false})).unwrap();
    assert!(!row(&mut app).0.starts_with('โœ“'));
    let at = row(&mut app).1.center();
    super::super::tests_appearance::click(&ctx, &mut app, at, menu);
    assert!(row(&mut app).0.starts_with('โœ“'));
    let states = match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.kashidas).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    assert!(states.iter().all(|v| *v));
    app.select_tool("type");
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 1, "end": 1}));
    let at = row(&mut app).1.center();
    super::super::tests_appearance::click(&ctx, &mut app, at, menu);
    let after = match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| r.style.kashidas).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    assert!(after.iter().all(|v| *v), "an empty caret leaves all characters unchanged");
}

/// Reset Panel sets every character attribute the panel shows, except the font family, style
/// and size, back to its default (Small Caps, the position, Character Alignment, Proportional
/// Metrics, Tate-chu-yoko and its settings, No Break, Character Direction, Digits and the font height reference
/// included), in the selected type and in the text the Type tool has selected while it edits.
#[test]
fn reset_panel_resets_every_attribute_but_the_font() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "One 12"})).unwrap()["id"].as_u64().unwrap();
    let runs = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.clone())).collect::<Vec<_>>(),
        _ => panic!("text"),
    };
    let differs = |s: &CharStyle, d: &CharStyle| {
        [
            s.tracking != d.tracking,
            s.leading != d.leading,
            s.kerning != d.kerning,
            s.baseline_shift != d.baseline_shift,
            s.h_scale != d.h_scale,
            s.v_scale != d.v_scale,
            s.rotation != d.rotation,
            s.underline != d.underline,
            s.strikethrough != d.strikethrough,
            s.all_caps != d.all_caps,
            s.small_caps != d.small_caps,
            s.position != d.position,
            s.char_align != d.char_align,
            s.proportional_metrics != d.proportional_metrics,
            s.tate_chu_yoko != d.tate_chu_yoko,
            s.tcy_up_down != d.tcy_up_down,
            s.tcy_left_right != d.tcy_left_right,
            s.aki_left != d.aki_left,
            s.aki_right != d.aki_right,
            s.tsume != d.tsume,
            s.standard_vertical_roman != d.standard_vertical_roman,
            s.no_break != d.no_break,
            s.char_direction != d.char_direction,
            s.digits != d.digits,
            s.font_height_reference != d.font_height_reference,
            s.diacritic_horizontal != d.diacritic_horizontal,
            s.diacritic_vertical != d.diacritic_vertical,
        ]
    };
    let custom = |app: &mut VectorcraftApp| {
        app.run(
            "text.setRangeStyle",
            json!({
                "id": id, "tracking": 50, "leading": 30, "kerning": 20, "baselineShift": 3, "hScale": 120, "vScale": 90, "rotation": 15,
                "underline": true, "strikethrough": true, "allCaps": true, "smallCaps": true, "position": "superscript",
                "charAlign": "emBoxCenter", "proportionalMetrics": true, "tateChuYoko": true, "tcyUpDown": 2, "tcyLeftRight": -3,
                "akiLeft": 250, "akiRight": 500, "tsume": 50, "standardVerticalRoman": true, "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi", "fontHeightReference": "capHeight",
                "diacriticHorizontal": 120, "diacriticVertical": -80
            }),
        )
        .unwrap();
    };
    let plain = runs(&app)[0].1.clone();
    assert_eq!(differs(&plain, &CharStyle::default()), [false; 27]);
    custom(&mut app);
    let styled = runs(&app)[0].1.clone();
    assert_eq!(differs(&styled, &CharStyle::default()), [true; 27]);
    app.run("select.set", json!({"ids": [id]})).unwrap();
    reset_panel(&mut app);
    assert_eq!(runs(&app), [("One 12".to_string(), plain.clone())]);
    // While the Type tool edits text, Reset Panel resets only its selection.
    custom(&mut app);
    app.select_tool("type");
    app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
    app.session.set_tool_option("select", &json!({"start": 4, "end": 6}));
    assert!(text_editing(&app).is_some());
    reset_panel(&mut app);
    assert_eq!(runs(&app), [("One ".to_string(), styled), ("12".to_string(), plain)]);
}

/// #4232: the panel menu's Show Snap to Glyph Options shows the Snap to Glyph section (with no
/// type selected too) and Hide Snap to Glyph Options hides it; its checkboxes, dimmed while View โ€บ
/// Snap to Glyph is off, set the options.
#[test]
fn snap_to_glyph_options_show_from_the_menu_and_set_the_options() {
    use super::super::tests_appearance::{click, frame_events, text_rect};
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    let ctx = egui::Context::default();
    let toggle = |app: &mut VectorcraftApp, label: &str| {
        let texts = frame_events(&ctx, app, vec![], menu);
        let at = texts.iter().find(|(t, _)| t.trim() == label).unwrap_or_else(|| panic!("{label} in {texts:?}")).1;
        click(&ctx, app, at.center(), menu);
    };
    let section = |app: &mut VectorcraftApp| frame_events(&ctx, app, vec![], show);
    let labels = ["Baseline", "x-height", "Glyph Bounds", "Proximity Guides", "Angular Guides", "Anchor Point"];
    assert!(!section(&mut app).iter().any(|(t, _)| t == "Proximity Guides"), "hidden at first");
    toggle(&mut app, "Show Snap to Glyph Options");
    let texts = section(&mut app);
    assert!(labels.iter().all(|l| texts.iter().any(|(t, _)| t == l)), "{texts:?}");
    let check = |app: &mut VectorcraftApp, label: &str| {
        let at = text_rect(&section(app), label).center();
        click(&ctx, app, at, show);
    };
    check(&mut app, "Angular Guides");
    assert!(app.session.prefs.glyph_snap.angular, "dimmed while Snap to Glyph is off");
    app.ui.view.snap_to_glyph = true;
    check(&mut app, "Angular Guides");
    check(&mut app, "x-height");
    let o = app.session.prefs.glyph_snap;
    assert!(!o.angular && !o.x_height && o.baseline && o.bounds && o.proximity && o.anchors, "{o:?}");
    check(&mut app, "Angular Guides");
    assert!(app.session.prefs.glyph_snap.angular);
    toggle(&mut app, "Hide Snap to Glyph Options");
    assert!(!section(&mut app).iter().any(|(t, _)| t == "Proximity Guides"));
}

/// #5273: the Snap to Glyph options come after every character attribute, so showing them from the
/// panel menu scrolls a short panel down to them; their first checkbox turns View โ€บ Snap to Glyph
/// on and off, which undims the others.
#[test]
fn snap_to_glyph_options_scroll_into_view_and_turn_snapping_on() {
    use super::super::tests_appearance::{click, frame_events, text_rect};
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
    let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Glyphs"})).unwrap()["id"].clone();
    app.run("select.set", json!({"ids": [id]})).unwrap();
    let ctx = egui::Context::default();
    const VIEW: f32 = 160.0;
    // The panel as a short dock shows it: in a scroll area.
    let panel = |app: &mut VectorcraftApp, ui: &mut egui::Ui| {
        egui::ScrollArea::vertical().max_height(VIEW).show(ui, |ui| show(app, ui));
    };
    let texts = frame_events(&ctx, &mut app, vec![], menu);
    let item = texts.iter().find(|(t, _)| t.trim() == "Show Snap to Glyph Options").unwrap().1;
    click(&ctx, &mut app, item.center(), menu);
    // The scroll is animated: it lands over the next second.
    let mut texts = vec![];
    for i in 0..30 {
        let raw = egui::RawInput { time: Some(10.0 + f64::from(i) * 0.1), ..Default::default() };
        texts = super::super::tests_appearance::frame_raw(&ctx, &mut app, raw, panel);
    }
    for label in ["Snap to Glyph", "Anchor Point"] {
        let r = text_rect(&texts, label);
        assert!(r.top() >= 0.0 && r.bottom() <= VIEW + 1.0, "{label} at {r:?} is outside the panel");
    }
    assert!(!app.ui.view.snap_to_glyph);
    click(&ctx, &mut app, text_rect(&texts, "Snap to Glyph").center(), panel);
    assert!(app.ui.view.snap_to_glyph, "the first checkbox turns Snap to Glyph on");
    let texts = frame_events(&ctx, &mut app, vec![], panel);
    click(&ctx, &mut app, text_rect(&texts, "Anchor Point").center(), panel);
    assert!(!app.session.prefs.glyph_snap.anchors, "the options take clicks once it is on");
}

/// Copy and Cut take a selected story after a frame threaded in before the edited one took its whole
/// text.
#[test]
fn copy_and_cut_take_a_story_that_left_the_edited_frame() {
    for cut in [false, true] {
        let mut app = VectorcraftApp::new(Session::new(), Default::default());
        app.run("file.new", json!({"width": 600, "height": 300})).unwrap();
        let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4);
        let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}});
        let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap();
        let b = app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
        app.run("select.set", json!({"ids": [a, b]})).unwrap();
        app.run("text.thread.create", json!({})).unwrap();
        app.session.select_tool("type", Default::default()).unwrap();
        app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0}));
        app.run("select.all", json!({})).unwrap();
        let c = app.run("text.thread.add", json!({"from": a, "before": true, "rect": [700, 10, 400, 600]})).unwrap()["id"].as_u64().unwrap();
        let text = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
            NodeKind::Text(t) => t.plain_text(),
            _ => panic!("not text"),
        };
        assert_eq!((text(&app, a), text(&app, b), text(&app, c)), (String::new(), String::new(), story.clone()));
        assert!(intercept_text_command(&mut app, if cut { "edit.cut" } else { "edit.copy" }).is_some());
        let copied: Vec<String> = app
            .session
            .clipboard
            .nodes
            .iter()
            .filter_map(|n| match &n.kind {
                NodeKind::Text(t) => Some(t.plain_text()),
                _ => None,
            })
            .collect();
        assert_eq!(copied, std::slice::from_ref(&story), "cut: {cut}");
        assert_eq!(text(&app, c).is_empty(), cut);
        if cut {
            // A story that holds no text has nothing to copy, so Cut does not run its delete.
            app.run("select.all", json!({})).unwrap();
            assert_eq!(text_story(&app).map(|frames| frames.len()), Some(3));
            assert!(!text_copy(&mut app, false));
        }
    }
}

/// After Select All in a frame of threaded text, the Character and Paragraph panels and Copy act on
/// the text of every frame of the story.
#[test]
fn select_all_in_threaded_text_formats_and_copies_the_whole_story() {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 600, "height": 300})).unwrap();
    let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4);
    let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}});
    let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap();
    let b = app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [a, b]})).unwrap();
    app.run("text.thread.create", json!({})).unwrap();
    app.run("select.set", json!({"ids": [b]})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    app.session.set_tool_option("textSelection", &json!({"editing": b, "anchor": 0, "caret": 0}));
    app.run("select.all", json!({})).unwrap();
    assert_eq!(text_story(&app), Some(vec![NodeId(a), NodeId(b)]));
    let frame = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => (**t).clone(),
        _ => panic!("not text"),
    };
    format(&mut app, json!({"size": 9}));
    crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap();
    for id in [a, b] {
        let t = frame(&app, id);
        assert!(t.runs.iter().all(|r| (r.style.size - 9.0).abs() < 1e-9), "every character of frame {id} is 9 pt");
        assert!((t.para_at(0).space_before - 4.0).abs() < 1e-9, "frame {id}'s paragraphs take the space");
    }
    assert!(intercept_text_command(&mut app, "edit.copy").is_some());
    let copied: Vec<String> = app
        .session
        .clipboard
        .nodes
        .iter()
        .filter_map(|n| match &n.kind {
            NodeKind::Text(t) => Some(t.plain_text()),
            _ => None,
        })
        .collect();
    assert_eq!(copied, [story]);
}

/// A story threaded through three frames in order, the first `height` tall.
fn three_frame_story(height: u32) -> (VectorcraftApp, u64, u64, u64) {
    let mut app = VectorcraftApp::new(Session::new(), Default::default());
    app.run("file.new", json!({"width": 900, "height": 300})).unwrap();
    let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(6);
    let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": height}});
    let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap();
    let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap();
    let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap();
    (app, a, b, c)
}

/// Select All with the Type tool in frame `id` of a story.
fn select_all_from(app: &mut VectorcraftApp, id: u64) {
    app.run("select.set", json!({"ids": [id]})).unwrap();
    app.session.select_tool("type", Default::default()).unwrap();
    app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 0}));
    app.run("select.all", json!({})).unwrap();
}

fn story_frame(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::TextObject {
    match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind {
        NodeKind::Text(t) => (**t).clone(),
        _ => panic!("not text"),
    }
}

fn story_sizes(app: &VectorcraftApp, id: u64) -> Vec<f64> {
    story_frame(app, id).runs.iter().map(|r| r.style.size).collect()
}

/// The frames that Select All saved are not the frames of the story once the first of them has
/// left the thread: the edited frame's story takes the change.
#[test]
fn story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves() {
    // The first frame is too short for a line, so Select All edits the second.
    let (mut app, a, b, c) = three_frame_story(1);
    select_all_from(&mut app, c);
    assert_eq!(app.session.tool_options()["story"], json!([a, b, c]));
    assert_eq!(text_editing(&app).unwrap().0, NodeId(b));
    app.run("text.thread.break", json!({"id": a, "port": "out"})).unwrap();
    assert_eq!(text_editing(&app).unwrap().0, NodeId(b));

    assert_eq!(text_story(&app), Some(vec![NodeId(b), NodeId(c)]));
    format(&mut app, json!({"size": 9}));
    assert!(story_sizes(&app, a).iter().all(|s| (*s - 12.0).abs() < 1e-9), "the frame that left keeps its size");
    for id in [b, c] {
        assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size");
    }
}

/// A frame that left the thread after Select All takes no change, and a frame added to it does.
#[test]
fn story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined() {
    let (mut app, a, b, c) = three_frame_story(60);
    select_all_from(&mut app, c);
    assert_eq!(text_editing(&app).unwrap().0, NodeId(a));
    app.run("text.thread.break", json!({"id": b, "port": "out"})).unwrap();
    assert_eq!(text_story(&app), Some(vec![NodeId(a), NodeId(b)]));
    let d = app.run("text.thread.add", json!({"from": a, "rect": [600, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap();
    assert_eq!(text_story(&app), Some(vec![NodeId(a), NodeId(d), NodeId(b)]));

    crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap();
    for id in [a, d, b] {
        assert!((story_frame(&app, id).para_at(0).space_before - 4.0).abs() < 1e-9, "frame {id} takes the space");
    }
    assert!(story_frame(&app, c).para_at(0).space_before.abs() < 1e-9, "the frame that left keeps its paragraphs");
}

/// With the thread gone, the selection is in the one edited frame.
#[test]
fn story_changes_stay_in_the_edited_frame_once_its_thread_is_removed() {
    let (mut app, a, b, c) = three_frame_story(60);
    select_all_from(&mut app, c);
    assert_eq!(text_editing(&app).unwrap().0, NodeId(a));
    app.run("text.thread.remove", json!({})).unwrap();
    assert_eq!(text_story(&app), None);

    crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap();
    assert!((story_frame(&app, a).para_at(0).space_before - 4.0).abs() < 1e-9);
    for id in [b, c] {
        assert!(story_frame(&app, id).para_at(0).space_before.abs() < 1e-9, "frame {id} keeps its paragraphs");
    }
}

/// A selected story is one text: its locked and hidden frames take the change too.
#[test]
fn story_changes_take_in_locked_and_hidden_frames() {
    let (mut app, a, b, c) = three_frame_story(60);
    app.run("select.set", json!({"ids": [b]})).unwrap();
    app.run("object.lock", json!({})).unwrap();
    app.run("select.set", json!({"ids": [c]})).unwrap();
    app.run("object.hide", json!({})).unwrap();
    select_all_from(&mut app, a);
    assert_eq!(text_story(&app), Some(vec![NodeId(a), NodeId(b), NodeId(c)]));

    format(&mut app, json!({"size": 9}));
    for id in [a, b, c] {
        assert_eq!(story_sizes(&app, id).iter().filter(|s| (**s - 9.0).abs() > 1e-9).count(), 0, "frame {id} takes the size");
    }
}

/// [`three_frame_story`] with its second frame locked and its third hidden, a type object of its own
/// below it, and the first frame selected with the Selection tool โ†’ the app, the frames and the
/// other type object.
fn story_selected_in_its_first_frame() -> (VectorcraftApp, [u64; 3], u64) {
    let (mut app, a, b, c) = three_frame_story(60);
    let other = app.run("text.create", json!({"x": 10, "y": 250, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [b]})).unwrap();
    app.run("object.lock", json!({})).unwrap();
    app.run("select.set", json!({"ids": [c]})).unwrap();
    app.run("object.hide", json!({})).unwrap();
    app.run("select.set", json!({"ids": [a]})).unwrap();
    assert_eq!(text_editing(&app), None);
    (app, [a, b, c], other)
}

fn undo_steps(app: &VectorcraftApp) -> usize {
    app.session.active().unwrap().history.undo.len()
}

/// With the Selection tool, a selected frame of a threaded story stands for the whole story: the
/// panel's changes reach its locked and hidden frames, each in one undo step, and leave other type
/// alone.
#[test]
fn selection_tool_changes_reach_every_frame_of_the_story() {
    let (mut app, frames, other) = story_selected_in_its_first_frame();
    assert_eq!(selected_stories(&app), frames.map(NodeId).to_vec());

    let steps = undo_steps(&app);
    style(&mut app, json!({"size": 9}));
    assert_eq!(undo_steps(&app), steps + 1, "one undo step");
    for id in frames {
        assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size");
    }
    assert!(story_sizes(&app, other).iter().all(|s| (*s - 12.0).abs() < 1e-9), "other type keeps its size");
    app.run("edit.undo", json!({})).unwrap();
    for id in frames {
        assert!(story_sizes(&app, id).iter().all(|s| (*s - 12.0).abs() < 1e-9), "undo gives frame {id} its size back");
    }

    format(&mut app, json!({"underline": true}));
    for id in frames {
        assert!(story_frame(&app, id).runs.iter().all(|r| r.style.underline), "frame {id} is underlined");
    }
    assert!(story_frame(&app, other).runs.iter().all(|r| !r.style.underline));

    // Tate-chu-yoko Settings and Warichu Settings set their values through `run_format`.
    run_format(&mut app, json!({"tcyUpDown": 2})).unwrap();
    for id in frames {
        assert!(story_frame(&app, id).runs.iter().all(|r| (r.style.tcy_up_down - 2.0).abs() < 1e-9), "frame {id} takes Up/Down");
    }
    assert!(story_frame(&app, other).runs.iter().all(|r| r.style.tcy_up_down.abs() < 1e-9));
}

/// With the Selection tool the anti-aliasing method goes to every frame of the selected story.
#[test]
fn selection_tool_anti_aliasing_reaches_every_frame_of_the_story() {
    let (mut app, frames, other) = story_selected_in_its_first_frame();
    set_anti_alias(&mut app, TypeAntiAlias::Strong);
    for id in frames {
        assert_eq!(story_frame(&app, id).anti_alias, TypeAntiAlias::Strong, "frame {id}");
    }
    assert_eq!(story_frame(&app, other).anti_alias, TypeAntiAlias::Sharp);
    assert_eq!(shared_anti_alias(&app), Some(TypeAntiAlias::Strong));
}

/// With the Selection tool a Variable Font slider sets the axis on every frame of the selected
/// story, in one undo step.
#[test]
fn selection_tool_font_axes_reach_every_frame_of_the_story() {
    use vectorcraft_text::test_fonts::{TWO_AXIS_FAMILY, two_axis_font};
    vectorcraft_text::FontDb::global().add_font(two_axis_font().unwrap());
    let (mut app, frames, _) = story_selected_in_its_first_frame();
    app.run("text.setStyle", json!({"ids": frames, "font": TWO_AXIS_FAMILY})).unwrap();
    app.run("select.set", json!({"ids": [frames[0]]})).unwrap();
    let steps = undo_steps(&app);
    axes_cmd(&mut app, json!({"wght": 700}), widgets::Live::Released);
    assert_eq!(undo_steps(&app), steps + 1, "one undo step");
    for id in frames {
        let t = story_frame(&app, id);
        assert!(t.runs.iter().all(|r| r.style.font_axes.get("wght") == Some(&700.0)), "frame {id}: {:?}", t.runs[0].style.font_axes);
    }
}

/// With the Selection tool a font family picked in the font menu, and its preview, go to every
/// frame of the selected story, in one undo step.
#[test]
fn selection_tool_font_family_reaches_every_frame_of_the_story() {
    let (mut app, frames, other) = story_selected_in_its_first_frame();
    let family = |app: &VectorcraftApp, id: u64| story_frame(app, id).runs.iter().map(|r| r.style.font_family.clone()).collect::<Vec<_>>();
    let before = family(&app, other);
    let ctx = egui::Context::default();
    crate::font_menu::apply(&mut app, &ctx, crate::font_menu::FontPick::Preview("Source Serif 4".into(), None));
    for id in frames {
        assert!(family(&app, id).iter().all(|f| f == "Source Serif 4"), "the preview shows on frame {id}");
    }
    let steps = undo_steps(&app);
    crate::font_menu::apply(&mut app, &ctx, crate::font_menu::FontPick::Chosen("Source Serif 4".into(), None));
    assert_eq!(undo_steps(&app), steps + 1, "one undo step");
    for id in frames {
        assert!(family(&app, id).iter().all(|f| f == "Source Serif 4"), "frame {id} takes the family");
    }
    assert_eq!(family(&app, other), before, "other type keeps its family");
}

/// The fields show a value only when every frame of the selected story has it: a hidden frame that
/// differs leaves them blank.
#[test]
fn selection_tool_fields_read_every_frame_of_the_story() {
    let (mut app, [a, b, c], _) = story_selected_in_its_first_frame();
    assert_eq!(shared(&app, |s| s.size), Some(12.0));
    assert_eq!(shared_anti_alias(&app), Some(TypeAntiAlias::Sharp));
    app.run("text.setStyle", json!({"ids": [c], "size": 20})).unwrap();
    app.run("text.setFormat", json!({"ids": [b], "antiAlias": TypeAntiAlias::Crisp.id()})).unwrap();
    app.run("select.set", json!({"ids": [a]})).unwrap();
    assert_eq!(shared(&app, |s| s.size), None, "the hidden frame's size differs");
    assert_eq!(shared_anti_alias(&app), None, "the locked frame's anti-aliasing differs");
}

/// Two frames of one story, or a frame in a selected group, count once; an unthreaded type
/// object is a story of its own.
#[test]
fn selected_stories_list_each_frame_once() {
    let (mut app, [a, b, c], other) = story_selected_in_its_first_frame();
    app.run("object.unlockAll", json!({})).unwrap();
    app.run("select.set", json!({"ids": [b, a]})).unwrap();
    assert_eq!(selected_stories(&app), [a, b, c].map(NodeId).to_vec(), "thread order, each once");
    app.run("select.set", json!({"ids": [other, a]})).unwrap();
    let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [group]})).unwrap();
    let mut listed = selected_stories(&app);
    listed.sort_by_key(|id| id.0);
    let mut expected = [a, b, c, other].map(NodeId).to_vec();
    expected.sort_by_key(|id| id.0);
    assert_eq!(listed, expected);
    app.run("select.set", json!({"ids": []})).unwrap();
    assert!(selected_stories(&app).is_empty());
}

/// Check that the kept list of the selected stories, and the type objects it resolves to, are the
/// ones a fresh build works out.
fn assert_stories_are_fresh(app: &VectorcraftApp, what: &str) {
    let st = app.session.active().unwrap();
    let fresh = build_selected_stories(st);
    assert_eq!(selected_stories(app), fresh, "{what}");
    let texts = selected_story_texts(app);
    let expected: Vec<_> = fresh
        .iter()
        .filter_map(|id| match &st.doc.node(*id)?.kind {
            NodeKind::Text(t) => Some(t.as_ref()),
            _ => None,
        })
        .collect();
    assert_eq!(texts.len(), expected.len(), "{what}: type objects");
    assert!(texts.iter().zip(&expected).all(|(t, e)| std::ptr::eq(*t, *e)), "{what}: the current document's type objects, in order");
}

/// The kept list of the selected stories follows every change it is worked out from: an edit, a
/// new selection (in another order, or as long with other objects, also without a new revision),
/// a selected group and a switch to another document at the same revision.
#[test]
fn kept_selected_stories_follow_the_document_and_the_selection() {
    let (mut app, [a, b, c], other) = story_selected_in_its_first_frame();
    assert_stories_are_fresh(&app, "a frame of a story");
    let builds = STORY_BUILDS.get();
    assert_eq!(selected_stories(&app), [a, b, c].map(NodeId).to_vec());
    assert_eq!(STORY_BUILDS.get(), builds, "a second read keeps the list");

    app.run("text.setStyle", json!({"size": 9})).unwrap();
    assert_stories_are_fresh(&app, "after an edit");
    app.run("select.set", json!({"ids": [other, a]})).unwrap();
    assert_stories_are_fresh(&app, "two stories");
    app.run("select.set", json!({"ids": [a, other]})).unwrap();
    assert_stories_are_fresh(&app, "the same objects in another order");
    app.run("select.set", json!({"ids": [other, b]})).unwrap();
    assert_stories_are_fresh(&app, "as many other objects");
    app.session.doc_mut().unwrap().selection.objects = vec![NodeId(other)];
    assert_stories_are_fresh(&app, "a new selection at the same revision");
    assert_eq!(selected_stories(&app), vec![NodeId(other)]);

    app.run("select.set", json!({"ids": [other, a]})).unwrap();
    let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
    app.run("select.set", json!({"ids": [group]})).unwrap();
    assert_stories_are_fresh(&app, "a selected group");

    let revision = app.session.active().unwrap().revision;
    app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
    let only = app.run("text.create", json!({"x": 20, "y": 50, "text": "Only", "size": 12})).unwrap()["id"].as_u64().unwrap();
    let st = app.session.doc_mut().unwrap();
    st.selection.objects = vec![NodeId(group)];
    st.revision = revision;
    assert_stories_are_fresh(&app, "another document with the first one's selection and revision");
    assert_ne!(selected_stories(&app), [a, b, c, other].map(NodeId).to_vec());
    app.run("select.set", json!({"ids": [only]})).unwrap();
    assert_stories_are_fresh(&app, "the other document's own type");
    app.run("document.activate", json!({"index": 0})).unwrap();
    assert_stories_are_fresh(&app, "back in the first document");

    app.run("select.set", json!({"ids": []})).unwrap();
    assert!(selected_stories(&app).is_empty());
    assert!(selected_story_texts(&app).is_empty());
}

/// What the Character and Paragraph panels draw, and the values of their fields, with the list of
/// the selected stories kept and with it built for every read.
fn panels_kept_and_unkept(app: &mut VectorcraftApp) -> [(Vec<String>, String); 2] {
    let read = |app: &mut VectorcraftApp, unkept: bool| {
        STORIES_UNKEPT.set(unkept);
        let ctx = egui::Context::default();
        let mut texts = vec![];
        for _ in 0..3 {
            texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| {
                show(app, ui);
                crate::panels::paragraph::show(app, ui);
            });
        }
        // A rect's position can be NaN, which `Rect`'s `==` refuses to compare.
        let texts: Vec<String> = texts.iter().map(|(text, rect)| format!("{text} {rect:?}")).collect();
        let fields = format!(
            "{:?} {:?}",
            [
                shared_effective(app, |s| s.size),
                shared_effective(app, |s| s.h_scale),
                shared_effective(app, |s| s.v_scale),
                shared_effective(app, |s| s.baseline_shift),
                shared_leading(app),
                shared(app, |s| s.tracking),
            ],
            (
                shared(app, |s| (s.font_family.clone(), s.font_style.clone())),
                shared(app, |s| (s.all_caps, s.underline, s.strikethrough, s.position)),
                selected_fonts(app),
                any_style(app, |s| s.underline),
                selected_stories(app),
                selected_story_texts(app).len(),
                text_style(app).map(|(c, p)| (c.size, p.left_indent)),
            )
        );
        STORIES_UNKEPT.set(false);
        (texts, fields)
    };
    [read(app, true), read(app, false)]
}

/// The panels show the same thing whether the list of the selected stories is kept or worked out
/// for each field: with nothing selected, one story, several stories with mixed values and a
/// Type tool selection inside one story.
#[test]
fn panels_show_the_same_with_the_kept_selected_stories() {
    let (mut app, [a, b, c], other) = story_selected_in_its_first_frame();
    let same = |app: &mut VectorcraftApp, what: &str| {
        let [unkept, kept] = panels_kept_and_unkept(app);
        assert_eq!(unkept.1, kept.1, "{what}: field values");
        assert_eq!(unkept.0, kept.0, "{what}: what the panels draw");
        unkept.1
    };
    app.run("select.set", json!({"ids": []})).unwrap();
    same(&mut app, "nothing selected");
    app.run("select.set", json!({"ids": [a]})).unwrap();
    let one = same(&mut app, "one story");
    app.run("text.setStyle", json!({"ids": [c], "size": 20, "tracking": 50})).unwrap();
    app.run("text.setFormat", json!({"ids": [b], "underline": true, "hScale": 120})).unwrap();
    app.run("select.set", json!({"ids": [other, a]})).unwrap();
    let mixed = same(&mut app, "several stories with mixed values");
    assert_ne!(one, mixed);
    app.session.select_tool("type", Default::default()).unwrap();
    app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 4, "caret": 15}));
    assert_eq!(text_editing(&app), Some((NodeId(a), 4, 15)));
    same(&mut app, "a Type tool selection inside one story");
}

/// One frame of the Character and Paragraph panels works out the selected stories once, though
/// many of their fields read them; a change to the document works them out again.
#[test]
fn panels_work_out_the_selected_stories_once_per_frame() {
    let (mut app, [a, ..], other) = story_selected_in_its_first_frame();
    app.run("select.set", json!({"ids": [other, a]})).unwrap();
    let ctx = egui::Context::default();
    let frame = |app: &mut VectorcraftApp| {
        let builds = STORY_BUILDS.get();
        super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| {
            show(app, ui);
            crate::panels::paragraph::show(app, ui);
        });
        STORY_BUILDS.get() - builds
    };
    frame(&mut app);
    app.run("text.setStyle", json!({"size": 9})).unwrap();
    assert_eq!(frame(&mut app), 1, "one build after an edit");
    assert_eq!(frame(&mut app), 0, "nothing changed");
    STORIES_UNKEPT.set(true);
    let reads = frame(&mut app);
    STORIES_UNKEPT.set(false);
    assert!(reads > 1, "the fields read the list {reads} times");
}