diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 32e46a3c52..ce6b66251f 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -338,6 +338,40 @@ pub(crate) fn format_target_kept(app: &mut VectorcraftApp) -> Result Option<(u64, u64, u64, FormatTarget)> { + let st = app.session.active()?; + // The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves + // typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to + // the length the text has with it ([`pending_text_len`]). The same characters key the same + // whether a drag or Select All, whose end lies past the text, selected them. + let o = app.session.tool_options(); + let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize); + let editing = text_editing(app).map(|(id, a, b)| { + let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true) + && st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc)); + let (a, b, len) = if unapplied_typing { + let (a, b) = (offset("start"), offset("end")); + pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len))) + } else { + let len = st.doc.node(id).and_then(|node| match &node.kind { + NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)), + _ => None, + }); + (a, b, len) + }; + if caret || (b > a && !(a == 0 && len.is_some_and(|len| b >= len))) { (id, a, b) } else { (id, 0, 0) } + }); + Some((st.uid, st.reverts, st.history_restores, format_target(app, editing))) +} + /// Apply a settings dialog to its opening text only. Compare before keeping typing so a /// refused confirmation on different text does not commit that text's in-progress edit. pub(crate) fn run_format_at_target(app: &mut VectorcraftApp, p: Value, target: &FormatTarget) -> Result { @@ -1230,6 +1264,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added); let sample = font_menu::sample_text(app); let unit = type_unit(app); + let target = character_target(app, true); let mut source = FontPickerSource::new(catalog) .settings(Bind::bound(&mut hold.settings)) .filters(Bind::bound(&mut hold.filters)) @@ -1244,7 +1279,8 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow .rows(rows) .font_picker(source) .axes_layout(AxesLayout::Button) - .anti_alias_methods(&ANTI_ALIAS_METHODS); + .anti_alias_methods(&ANTI_ALIAS_METHODS) + .edit_target(target); if let Some(languages) = &languages { controls = controls.languages(languages); } @@ -1323,37 +1359,6 @@ fn snap_to_glyph(app: &mut VectorcraftApp, ui: &mut Ui) { }); } -/// What the bars' Font Size field edits, as its edit target: the document, how many times File › -/// Revert and Undo or Redo replaced its content (after which a node id can name another object), -/// and the text `text.setStyle` changes ([`format_target`]): the range or story the Type tool has -/// selected, all of the edited text at a caret, else the selected stories. The field drops a value -/// typed and not yet committed when this changes, even where the new text has the same size. -fn size_target(app: &VectorcraftApp) -> Option<(u64, u64, u64, FormatTarget)> { - let st = app.session.active()?; - // The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves - // typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to - // the length the text has with it ([`pending_text_len`]). A caret changes the whole text - // wherever it is ([`range_style`]); a range over the whole text keys as a caret does. - let o = app.session.tool_options(); - let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize); - let editing = text_editing(app).map(|(id, a, b)| { - let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true) - && st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc)); - let (a, b, len) = if unapplied_typing { - let (a, b) = (offset("start"), offset("end")); - pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len))) - } else { - let len = st.doc.node(id).and_then(|node| match &node.kind { - NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)), - _ => None, - }); - (a, b, len) - }; - if b > a && !(a == 0 && len.is_some_and(|len| b >= len)) { (id, a, b) } else { (id, 0, 0) } - }); - Some((st.uid, st.reverts, st.history_restores, format_target(app, editing))) -} - /// The byte length text `id` will have once the typing that Real-time Drawing off leaves unapplied /// is applied: the stored text with the `text.editRange` preview's range replaced by its runs. /// `None` for a frame of a threaded story, whose text can reflow from other frames, when the @@ -1380,9 +1385,9 @@ fn pending_text_len(st: &DocState, id: NodeId) -> Option { /// The Font Size field of the bars, named `name`: typed, stepped, scrubbed or picked from the /// presets, in the type unit, blank where the selected text's sizes differ. A value typed and not -/// yet committed stays with the text it was typed for ([`size_target`]). +/// yet committed stays with the text it was typed for ([`character_target`]). fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) { - let target = size_target(app); + let target = character_target(app, false); let unit = type_unit(app); let scale = unit_scale(unit); let units = Env::of(ui).units(); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 473f834734..22b6114ce8 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -433,6 +433,282 @@ fn highlight_commands_ask_the_framework_to_focus_the_field_by_key() { } } +/// A number field of the character controls, by name, and the attribute of a character it sets. +type CharacterField = (&'static str, fn(&CharStyle) -> f64); + +/// The Character panel's number fields with its options and the East Asian and Middle Eastern +/// options shown. Properties shows the first four. +const CHARACTER_FIELDS: [CharacterField; 13] = [ + ("Font size", |s| s.size), + ("Leading", |s| s.leading.unwrap_or(0.0)), + ("Kerning", |s| s.kerning.unwrap_or(0.0)), + ("Tracking", |s| s.tracking), + ("Vertical scale", |s| s.v_scale), + ("Horizontal scale", |s| s.h_scale), + ("Baseline shift", |s| s.baseline_shift), + ("Rotation", |s| s.rotation), + ("Insert Aki Left", |s| s.aki_left), + ("Insert Aki Right", |s| s.aki_right), + ("Tsume", |s| s.tsume), + ("Horizontal Diacritic Position", |s| s.diacritic_horizontal), + ("Vertical Diacritic Position", |s| s.diacritic_vertical), +]; + +/// A panel that shows the character controls: its name, how it draws and the fields it shows. +type CharacterDraw = (&'static str, fn(&mut VectorcraftApp, &mut egui::Ui), &'static [CharacterField]); + +/// The Character panel and Properties with the fields each shows. +fn character_draws() -> [CharacterDraw; 2] { + [("Character", show, &CHARACTER_FIELDS), ("Properties", super::super::properties::show, &CHARACTER_FIELDS[..4])] +} + +/// A document with two text objects, `Ab` and `Cd`, at 12 pt with a leading of 20 pt and a tracking +/// of 10, and the East Asian and Middle Eastern options shown. +fn two_styled_texts() -> (VectorcraftApp, u64, u64) { + 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": 300})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.create", json!({"x": 20, "y": 140, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setStyle", json!({"ids": [a, b], "leading": 20, "tracking": 10})).unwrap(); + (app, a, b) +} + +/// Types `3+` into the field `name` without committing it. +fn type_unfinished(p: &mut crate::tests::panel_harness::Panel, name: &str) { + p.focus(name); + p.key(egui::Key::A, egui::Modifiers::COMMAND); + p.type_text("3+"); +} + +/// Draws a frame, then types `1` and Enter into the focused field. +fn finish_typing(p: &mut crate::tests::panel_harness::Panel) { + p.frame(); + p.type_text("1"); + p.key(egui::Key::Enter, egui::Modifiers::NONE); +} + +/// The attribute `read` of each run of the text `id`. +fn run_values(app: &VectorcraftApp, id: u64, read: fn(&CharStyle) -> f64) -> Vec<(String, f64)> { + block_text(app, NodeId(id)).runs.iter().map(|r| (r.text.clone(), read(&r.style))).collect() +} + +/// The number fields of the Character panel and Properties keep a value typed and not yet committed +/// while the text it was typed for stays selected, and drop it when other text with the same value +/// is selected. +#[test] +fn an_unfinished_character_value_does_not_reach_other_selected_text() { + use crate::tests::panel_harness::Panel; + for (panel, draw, fields) in character_draws() { + for &(name, read) in fields { + let (mut app, a, b) = two_styled_texts(); + let before = run_values(&app, a, read); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, name); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), a, read), [("Ab".to_string(), 4.0)], "{panel} {name}: an unchanged selection keeps 3+"); + p.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(run_values(&p.app(), a, read), before, "{panel} {name}: undone"); + + type_unfinished(&mut p, name); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_typing(&mut p); + let app = p.app(); + assert_eq!( + (run_values(&app, a, read), run_values(&app, b, read)), + (before, vec![("Cd".to_string(), 1.0)]), + "{panel} {name}: b takes 1, not 3+1" + ); + } + } +} + +/// While the Type tool edits text, a value typed into the Character panel belongs to the selected +/// characters: another range in the same text drops it. +#[test] +fn an_unfinished_character_value_does_not_reach_another_text_range() { + use crate::tests::panel_harness::Panel; + for (panel, draw, _) in character_draws() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + 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": 2})); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, "Tracking"); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 4})); + finish_typing(&mut p); + let want = vec![("Ab".to_string(), 0.0), ("cd".to_string(), 1.0)]; + assert_eq!(run_values(&p.app(), id, |s| s.tracking), want, "{panel}: the second range takes 1, not 3+1"); + } +} + +/// While the Type tool edits text, a range dragged over the whole text and Select All select the same +/// characters, so a value typed with one selected is kept when the other replaces it. +#[test] +fn an_unfinished_character_value_survives_select_all_over_the_same_characters() { + use crate::tests::panel_harness::Panel; + for (panel, draw, _) in character_draws() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + 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": 4})); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, "Tracking"); + p.app().run("select.all", json!({})).unwrap(); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), id, |s| s.tracking), [("Abcd".to_string(), 4.0)], "{panel}: Select All keeps 3+"); + } +} + +/// At a caret the Kerning field sets the pair at the caret, so a value typed there does not reach +/// the pair at another caret position in the same text, though both pairs have the same kerning. +#[test] +fn an_unfinished_kerning_does_not_reach_another_caret_position() { + use crate::tests::panel_harness::Panel; + for (panel, draw, _) in character_draws() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "kerning": 10})).unwrap(); + 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": 1, "caret": 1})); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, "Kerning"); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 3, "caret": 3})); + finish_typing(&mut p); + let kernings: Vec = run_values(&p.app(), id, |s| s.kerning.unwrap_or(0.0)).into_iter().map(|(_, k)| k).collect(); + assert!(kernings.contains(&1.0) && !kernings.contains(&4.0), "{panel}: the pair at the second caret takes 1, not 3+1: {kernings:?}"); + } +} + +/// Another document whose text has the same id and tracking drops the value. +#[test] +fn an_unfinished_character_value_does_not_reach_another_document() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_styled_texts(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let other = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "both documents' texts have the same id"); + app.run("text.setStyle", json!({"ids": [a], "tracking": 10})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().run("document.activate", json!({"index": 1})).unwrap(); + finish_typing(&mut p); + let tracking = |s: &CharStyle| s.tracking; + let second = run_values(&p.app(), a, tracking); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + let first = run_values(&p.app(), a, tracking); + assert_eq!((first, second), (vec![("Ab".to_string(), 10.0)], vec![("Ab".to_string(), 1.0)]), "the other document takes 1"); +} + +/// File › Revert drops the value, though the restored text has the same id and tracking. +#[test] +fn an_unfinished_character_value_is_dropped_by_file_revert() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_styled_texts(); + let dir = vectorcraft_testkit::TempDir::new("character-value-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Type.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the text as saved. + app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [a]})).unwrap(); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), a, |s| s.tracking), [("Ab".to_string(), 1.0)], "Revert drops the unfinished value"); +} + +/// Undo drops the value, though the text it takes away and the text made and selected after it +/// have the same id and tracking. +#[test] +fn an_unfinished_character_value_is_dropped_by_undo() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().run("edit.undo", json!({})).unwrap(); + let b = p.app().run("text.create", json!({"x": 20, "y": 40, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(b, a, "the new text has the undone text's id"); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), b, |s| s.tracking), [("Cd".to_string(), 1.0)], "Undo drops the unfinished value"); +} + +/// With Real-time Drawing off, a Type tool range that reaches into typing not applied yet is +/// another range than the applied text it starts in. +#[test] +fn an_unfinished_character_value_does_not_reach_a_range_with_unapplied_typing() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).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": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The keymap builds in the first pass. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + let tracking = |s: &CharStyle| s.tracking; + assert_eq!(run_values(&app, id, tracking), [("Ab".to_string(), 0.0)], "the typing is not applied yet"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().session.set_tool_option("select", &json!({"start": 0, "end": 4})); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 1.0)], "the longer range takes 1, not 3+1"); +} + +/// Settling unapplied typing keeps an unfinished Character value for the Select All range. +#[test] +fn an_unfinished_character_value_survives_select_all_typing_settling() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).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": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The keymap builds in the first pass. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + let tracking = |s: &CharStyle| s.tracking; + assert_eq!(run_values(&app, id, tracking), [("Ab".to_string(), 0.0)], "the typing is not applied yet"); + app.run("select.all", json!({})).unwrap(); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + end_typing(&mut p.app()); + assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 0.0)], "the typing is applied"); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 4.0)], "settling the typing keeps 3+"); +} + /// The slider list and its gestures are the framework's. What the app decides: which axes the selection /// shares, that a change carries only the axes that moved (so a mixed axis stays as it is), the /// command (the object, or the Type tool's range) and that Reset Panel leaves the settings.