diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 02c4391921..ead201ffab 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -78,7 +78,7 @@ pub struct Selection { } /// See [`Selection::symbol_part`]. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct SymbolPart { /// The symbol instance. pub instance: NodeId, diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 677eec516a..b158a9175b 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -316,7 +316,7 @@ fn run_format_after_typing(app: &mut VectorcraftApp, mut p: Value, editing: Opti app.run("text.setRangeStyle", p) } -#[derive(PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Hash)] pub(crate) enum FormatTarget { Objects(Vec, Option), Story(Vec), @@ -1318,9 +1318,66 @@ 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 +/// preview is not an edit of `id`, or when its range does not fit the stored text. +fn pending_text_len(st: &DocState, id: NodeId) -> Option { + if st.doc.story_of(id).len() > 1 { + return None; + } + let (cmd, params) = st.interaction.as_ref()?.preview.as_ref()?; + if cmd != "text.editRange" || params.get("id")?.as_u64()? != id.0 { + return None; + } + let NodeKind::Text(text) = &st.doc.node(id)?.kind else { return None }; + let stored_len = vectorcraft_text::edit::runs_len(&text.runs); + let start = usize::try_from(params.get("start")?.as_u64()?).ok()?; + let end = usize::try_from(params.get("end")?.as_u64()?).ok()?; + if end > stored_len { + return None; + } + let removed_len = end.checked_sub(start)?; + let inserted_len = params.get("runs")?.as_array()?.iter().try_fold(0usize, |len, run| len.checked_add(run.get("text")?.as_str()?.len()))?; + stored_len.checked_sub(removed_len)?.checked_add(inserted_len) +} + /// 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. +/// 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`]). fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) { + let target = size_target(app); let unit = type_unit(app); let scale = unit_scale(unit); let units = Env::of(ui).units(); @@ -1332,7 +1389,12 @@ fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) { }) .collect(); let mut size = shared_effective(app, |s| s.size).map(|v| v * scale); - let out = NumberField::new(name, Bind::bound(&mut size)).unit_kind(unit.kind).range(0.1 * scale..=1296.0 * scale).presets(&presets).show(ui); + let out = NumberField::new(name, Bind::bound(&mut size)) + .unit_kind(unit.kind) + .range(0.1 * scale..=1296.0 * scale) + .presets(&presets) + .edit_target(&target) + .show(ui); apply_edits(app, &out.edit, EditPath::Scope, |app, value, _| { if let Some(v) = value { style(app, json!({"size": v / scale})); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index d1f6be332e..473f834734 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1482,3 +1482,273 @@ fn panels_work_out_the_selected_stories_once_per_frame() { STORIES_UNKEPT.set(false); assert!(reads > 1, "the fields read the list {reads} times"); } + +/// A drawing of controls over the app. +type Draw = fn(&mut VectorcraftApp, &mut egui::Ui); + +/// The Control bar's and the Contextual Task Bar's type controls, each drawn alone. +const BARS: [(&str, Draw); 2] = [ + ("Control bar", |app, ui| { + control_bar(app, ui); + }), + ("Contextual Task Bar", task_bar), +]; + +/// Types `3+` into the bar's Font Size field without committing it. +fn unfinished_size(p: &mut crate::tests::panel_harness::Panel) { + p.focus(tl!("Font Size")); + p.key(egui::Key::A, egui::Modifiers::COMMAND); + p.type_text("3+"); +} + +/// Draws a frame, then types `1` and Enter into the Font Size field. +fn finish_size(p: &mut crate::tests::panel_harness::Panel) { + p.frame(); + p.type_text("1"); + p.key(egui::Key::Enter, egui::Modifiers::NONE); +} + +/// Each run of the text `id` with its size. +fn run_sizes(app: &VectorcraftApp, id: u64) -> Vec<(String, f64)> { + block_text(app, NodeId(id)).runs.iter().map(|r| (r.text.clone(), r.style.size)).collect() +} + +/// A document with two text objects at 12 pt: `Ab` and `Cd`. +fn two_texts() -> (VectorcraftApp, u64, u64) { + 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(); + let b = app.run("text.create", json!({"x": 20, "y": 140, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + (app, a, b) +} + +/// The bars' Font Size field keeps a value typed and not yet committed while the text it was typed +/// for stays selected, and drops it when other text with the same size is selected. +#[test] +fn an_unfinished_font_size_does_not_reach_other_selected_text() { + use crate::tests::panel_harness::Panel; + for (bar, draw) in BARS { + let (mut app, a, b) = two_texts(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, draw); + unfinished_size(&mut p); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), a), [("Ab".to_string(), 4.0)], "{bar}: an unchanged selection keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [a], "size": 12})).unwrap(); + + unfinished_size(&mut p); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_size(&mut p); + let app = p.app(); + assert_eq!( + (run_sizes(&app, a), run_sizes(&app, b)), + (vec![("Ab".to_string(), 12.0)], vec![("Cd".to_string(), 1.0)]), + "{bar}: b takes 1 pt, not 3+1" + ); + } +} + +/// While the Type tool edits text, the field's value belongs to the selected characters: another +/// range in the same text drops it. At a caret it belongs to the whole text, so moving the caret +/// keeps it. +#[test] +fn an_unfinished_font_size_does_not_reach_another_text_range() { + use crate::tests::panel_harness::Panel; + for (bar, draw) in BARS { + 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": 1, "caret": 1})); + let mut p = Panel::new(app, draw); + unfinished_size(&mut p); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 3, "caret": 3})); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: a caret moved in the same text keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap(); + + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 2})); + p.frame(); + unfinished_size(&mut p); + p.app().run("select.all", json!({})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: Select All after a caret keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap(); + + // Select All over text whose characters are all selected selects the same characters. + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 4})); + p.frame(); + unfinished_size(&mut p); + p.app().run("select.all", json!({})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: Select All over the same characters keeps 3+"); + p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap(); + + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 2})); + p.frame(); + unfinished_size(&mut p); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 4})); + finish_size(&mut p); + let want = vec![("Ab".to_string(), 12.0), ("cd".to_string(), 1.0)]; + assert_eq!(run_sizes(&p.app(), id), want, "{bar}: the second range takes 1 pt, not 3+1"); + } +} + +/// Another document whose text has the same id and size drops the value. +#[test] +fn an_unfinished_font_size_does_not_reach_another_document() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_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("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, task_bar); + unfinished_size(&mut p); + p.app().run("document.activate", json!({"index": 1})).unwrap(); + finish_size(&mut p); + let second = run_sizes(&p.app(), a); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + let first = run_sizes(&p.app(), a); + assert_eq!((first, second), (vec![("Ab".to_string(), 12.0)], vec![("Ab".to_string(), 1.0)]), "the other document takes 1 pt"); +} + +/// File › Revert drops the value, though the restored text has the same id and size. +#[test] +fn an_unfinished_font_size_is_dropped_by_file_revert() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_texts(); + let dir = vectorcraft_testkit::TempDir::new("font-size-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, task_bar); + unfinished_size(&mut p); + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [a]})).unwrap(); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), a), [("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 size. +#[test] +fn an_unfinished_font_size_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, task_bar); + unfinished_size(&mut p); + 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_size(&mut p); + assert_eq!(run_sizes(&p.app(), b), [("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_font_size_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)); + assert_eq!(run_sizes(&app, id), [("Ab".to_string(), 12.0)], "the typing is not applied yet"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().session.set_tool_option("select", &json!({"start": 0, "end": 4})); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("AbCd".to_string(), 1.0)], "the longer range takes 1 pt, not 3+1"); +} + +/// With Real-time Drawing off, deleting a paragraph break pulls text from the next frame when +/// typing is applied. A different range drops the unfinished size before that reflow. +#[test] +fn an_unfinished_font_size_does_not_reach_a_range_in_threaded_text_with_unapplied_typing() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "a\nb", "size": 12, "area": {"width": 150, "height": 20}}); + 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(); + assert_eq!(story_frame(&app, a).plain_text(), "a\n"); + assert_eq!(story_frame(&app, b).plain_text(), "b"); + app.run("select.set", json!({"ids": [a]})).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 first frame builds the keymap. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + let backspace = |pressed| egui::Event::Key { + key: egui::Key::Backspace, + physical_key: Some(egui::Key::Backspace), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![backspace(true), backspace(false)]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + assert_eq!(story_frame(&app, a).plain_text(), "a\n", "the deletion is not applied yet"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 1})); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().session.set_tool_option("select", &json!({"start": 0, "end": 2})); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), a), [("ab".to_string(), 1.0)], "the longer range takes 1 pt, not 3+1"); + assert_eq!(story_frame(&p.app(), b).plain_text(), "", "the following text flows into the first frame"); +} + +#[test] +fn an_unfinished_font_size_stays_when_typing_is_kept() { + use crate::tests::panel_harness::Panel; + for real_time_drawing in [true, false] { + 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": real_time_drawing})).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), "realTimeDrawing={real_time_drawing}"); + let stored_text = if real_time_drawing { "AbCd" } else { "Ab" }; + assert_eq!(run_sizes(&app, id), [(stored_text.to_string(), 12.0)], "typing before keeping, realTimeDrawing={real_time_drawing}"); + app.run("select.all", json!({})).unwrap(); + let mut p = Panel::new(app, task_bar); + unfinished_size(&mut p); + p.app().keep_typing().unwrap(); + assert_ne!(p.app().session.tool_options()["typing"], json!(true), "realTimeDrawing={real_time_drawing}"); + finish_size(&mut p); + assert_eq!(run_sizes(&p.app(), id), [("AbCd".to_string(), 4.0)], "the kept typing keeps 3+, realTimeDrawing={real_time_drawing}"); + } +}