From dfa52f919db0c30c82e021a8939dd21e23147eaa Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 14:32:49 +0700 Subject: [PATCH 01/22] The Type tool's editor takes the keys back from its document canvas: the press that starts an edit focuses the canvas as its pass ends, after the editor asked for them, so the edit's typing and input-method text reached nothing --- crates/ui-egui/src/canvas.rs | 4 ++-- crates/ui-egui/src/type_editing.rs | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b7b103290e..682c8ca66c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -258,12 +258,12 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::dimension::floating(app, ui, space.view.rect); } let editing = app.session.tool_wants_text(); - crate::type_editing::show(app, ui); + crate::type_editing::show(app, ui, canvas_id(win)); out.reply = pass.map(|pass| tool_adapter::run(app, ui, pass)); // An edit the tool host started (a double-click on type) shows its editor in the same pass, so the keys of the // next frame are the edit's. if !editing { - crate::type_editing::show(app, ui); + crate::type_editing::show(app, ui, canvas_id(win)); } } drops::show(app, ui, win, kind); diff --git a/crates/ui-egui/src/type_editing.rs b/crates/ui-egui/src/type_editing.rs index 07d622bf3d..9ba78a557d 100644 --- a/crates/ui-egui/src/type_editing.rs +++ b/crates/ui-egui/src/type_editing.rs @@ -348,8 +348,8 @@ impl Component for TypeEditor<'_> { } /// Shows the editor part over the Type tool's caret while the tool edits text, before the tool host. A new edit target -/// is a new IME owner, so a reloaded document interrupts its composition. -pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { +/// is a new IME owner, so a reloaded document interrupts its composition. `canvas` is the document canvas's id. +pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, canvas: egui::Id) { if !app.session.tool_wants_text() || app.viewport_hidden(ui.ctx()) { return; } @@ -359,8 +359,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let Some(canvas_view) = app.canvas_view() else { return }; let caret = Rect::from_two_pos(canvas_view.to_screen(a), canvas_view.to_screen(b)).expand2(egui::vec2(1.0, 0.0)); let out = ui.scope_builder(egui::UiBuilder::new().max_rect(caret), |ui| TypeEditor::new(app, caret).id_salt(target).show(ui)).inner; - // Typing goes to the edit that starts, as a click on the part would take the keys. - if out.unfocused_start { + // Typing goes to the edit that starts, as a click on the part would take the keys. The press that started it + // focuses the canvas as its pass ends, so the editor takes the keys back from its canvas in the next pass. + if out.unfocused_start || focus::has(ui.ctx(), canvas) { focus::request(ui.ctx(), FocusTarget::Id(out.response.id)); } } From fc26b5cc904c9b94e55af0c7c24767d33ab6f5d7 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:08:50 +0700 Subject: [PATCH 02/22] Tests: the font menu rows are compared while the shared font database holds still, Paste's dimming runs on a still clock, the palette's rows are read under the palette as they are judged, a pick's count is left out of what its command changes, the canceled dialog is gone in the next pass, a tutorial step's tool is clicked as its link in the sentence, Classic keeps its own accent as production's tokens did, the held S's canvas press and Enter's drag run in frames as production's did --- crates/ui-egui/src/find_font.rs | 23 +++++++++++++--- crates/ui-egui/src/menus/tests.rs | 26 +++++++++++++++---- crates/ui-egui/src/palette.rs | 25 +++++++++++++++--- crates/ui-egui/src/prefs_dialog/tests.rs | 10 ++++--- .../ui-egui/src/shortcuts/held_tool/tests.rs | 16 ++++++++++-- crates/ui-egui/src/shortcuts/tests.rs | 5 ++-- 6 files changed, 84 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 8388969c29..3dd38efe78 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -1025,6 +1025,19 @@ mod tests { // PLAN: files-w11 owns Missing Fonts' hosted type; its test asserts the search there } + /// `f`'s answer, read while the font menu held still: tests running alongside add fonts to + /// the shared database and lend it composite fonts. + fn while_fonts_hold(mut f: impl FnMut() -> T) -> T { + let db = vectorcraft_text::FontDb::global(); + loop { + let before = db.menu_family_list(); + let out = f(); + if before == db.menu_family_list() { + return out; + } + } + } + /// A document set in Inter and Source Serif 4 (Inter twice), with Inter the one recent font. fn two_font_document() -> VectorcraftApp { let mut app = new_app(); @@ -1160,12 +1173,11 @@ mod tests { assert!(recent.iter().all(|r| r.family == "Inter"), "{recent:?}"); assert_eq!(recent.len(), db.styles("Inter").len(), "each style once, the closest not repeated"); assert!(recent.iter().all(|r| !r.style.is_empty()), "every row names its style: {recent:?}"); - let system = replacement_rows(&app, "system", &used); + let (system, menu) = while_fonts_hold(|| (replacement_rows(&app, "system", &used), db.menu_family_list())); assert!(system.iter().any(|r| r.family == "Source Sans 3" && r.style == "Regular"), "{system:?}"); assert!(!system.iter().any(|r| r.family.starts_with('.')), "the font menu's hidden families stay out"); // A composite font is a family without styles of its own, listed by its name alone. assert!(system.iter().all(|r| !r.style.is_empty() || db.styles(&r.family).is_empty()), "no nameless rows: {system:?}"); - let menu = db.menu_family_list(); let listed: std::collections::BTreeSet<&str> = system.iter().map(|r| r.family.as_str()).collect(); assert_eq!(listed.len(), menu.len(), "every family the font menu shows is listed"); let mut unique = system.clone(); @@ -1173,8 +1185,11 @@ mod tests { assert_eq!(unique.len(), system.len(), "no family and style is listed twice"); // The dialog stores the rows when it opens and when the source changes, and a picked row // sets both fields Change then uses. - open(&mut app); - assert_eq!(opened(&app).rows.len(), system.len()); + let (rows, system) = while_fonts_hold(|| { + open(&mut app); + (opened(&app).rows, replacement_rows(&app, "system", &used)) + }); + assert_eq!(rows.len(), system.len()); let mut d = opened(&app); set_source(&app, &mut d, "document", &used); assert_eq!(d.rows.len(), document.len()); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 3e06c81731..d200bc85d4 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -152,9 +152,13 @@ fn help_f1_opens_discover_without_a_document() { /// shows, marks nothing and the status bar says why. #[test] fn discover_says_why_a_tool_cannot_be_marked() { - fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + fn pass(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::panels::discover::show(app, ui)); out.textures_delta.clear(); + out + } + fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + let out = pass(ctx, app, events); fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { match s { egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), @@ -172,11 +176,23 @@ fn discover_says_why_a_tool_cannot_be_marked() { texts(ctx, app, vec![]); let drawn = texts(ctx, app, vec![]); let pos = drawn.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("`{label}` not drawn: {drawn:?}")).1.center(); + press_at(ctx, app, pos); + } + fn press_at(ctx: &egui::Context, app: &mut VectorcraftApp, pos: egui::Pos2) { let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; for e in [egui::Event::PointerMoved(pos), button(true), button(false)] { - texts(ctx, app, vec![e]); + pass(ctx, app, vec![e]); } } + // A step's tool name is a link inside its sentence: the Link node named by its words. + fn click_link(ctx: &egui::Context, app: &mut VectorcraftApp, name: &str) { + ctx.enable_accesskit(); + pass(ctx, app, vec![]); + let nodes = pass(ctx, app, vec![]).platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let link = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Link && n.label().is_some_and(|l| l == name)); + let b = link.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no link `{name}`")); + press_at(ctx, app, egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)); + } crate::i18n::set_current(crate::i18n::Lang::EN); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); let ctx = crate::testing::ui_context(); @@ -195,16 +211,16 @@ fn discover_says_why_a_tool_cannot_be_marked() { assert!(app.ui.learn_locate.is_none()); assert_eq!(app.ui.status, reason); - let (tutorial, tool) = crate::panels::learn::catalog::SKILLS + let (tutorial, link) = crate::panels::learn::catalog::SKILLS .iter() .flat_map(|skill| skill.tutorials.iter()) - .find_map(|t| t.steps.iter().find_map(|s| s.tool).map(|tool| (t, tool))) + .find_map(|t| t.steps.iter().find_map(|s| s.tool_name()).map(|(_, name, _)| (t, name))) .unwrap(); let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap(); let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap(); app.run("help.discover.choose", json!({"index": index})).unwrap(); app.status(""); - click(&ctx, &mut app, vectorcraft_tools::tool_info(tool).unwrap().label); + click_link(&ctx, &mut app, link); assert!(app.ui.learn_locate.is_none()); assert_eq!(app.ui.status, reason); } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 397f084fe1..5c54be48bf 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1382,8 +1382,10 @@ mod tests { assert_eq!(window.app.ui.recent_commands, recorded); // Cancel closes the dialog without running the command. close_dialogs(&mut window.app, false); - assert!(!window.app.any_dialog_open()); + assert!(crate::tests::picks::open_dialogs(&window.app).is_empty()); + // The window's next pass draws it gone: until then its layer, last drawn, is still up. window.frame(vec![]); + assert!(!window.app.any_dialog_open()); assert_eq!(window.app.ui.recent_commands, recorded); assert_eq!(window.app.ui.command_uses.count_of(&clean_up.key_text()), 1, "counted once, at the pick"); } @@ -1587,8 +1589,10 @@ mod tests { // selected tool), the status line aside. let look = |app: &VectorcraftApp| { let mut ui = serde_json::to_value(&app.ui).unwrap_or_default(); + // The pick's count is the palette's record of the pick ([`record_pick`]), not the command's doing. if let Some(o) = ui.as_object_mut() { o.remove("status"); + o.remove("command_uses"); } let doc = app.session.active().map(|st| { (st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone()) @@ -2024,9 +2028,20 @@ mod tests { window.app.ui.recent_commands = vec![CommandRef::new("object.ungroup"), CommandRef::new("select.all")]; window.app.ui.palette_open = true; window.frame(vec![]); - assert!(!window.resolved("object.ungroup").enabled); - let all = window.resolved("select.all"); - assert!(all.enabled && hint_of(&all).is_none()); + // The rows are judged from the window under the palette, where a pick runs; a command read from + // inside the open palette is under its modal layer. + let nodes = window.frame(vec![]); + let names = names(Lang::EN); + let row = |id: &str| { + // A row shows the result's label; its name's menu path is the row's path. + let name = + names.iter().find(|(at, _)| at == id).and_then(|(_, name)| name.rsplit(" › ").next()).unwrap_or_else(|| panic!("{id} has a name")); + let option = + |n: &&egui::accesskit::Node| n.role() == egui::accesskit::Role::ListBoxOption && n.label().is_some_and(|l| l.starts_with(name)); + nodes.iter().find(option).unwrap_or_else(|| panic!("a row for {name}")) + }; + assert!(row("object.ungroup").is_disabled()); + assert!(!row("select.all").is_disabled()); } /// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system @@ -2034,6 +2049,8 @@ mod tests { #[test] fn paste_is_dimmed_only_while_nothing_can_be_pasted() { let mut window = Window::on(Fixture::Multi.session()); + // A still clock: the tick's next look at the (empty) system clipboard would undo the flag. + window.app.now_override = Some(window.app.system_paste_at.max(0.0)); window.app.system_paste = false; window.frame(vec![]); let hint = hint_of(&window.resolved("edit.paste")).expect("Paste is dimmed"); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index d40401aaa7..8d2e22729f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -131,10 +131,12 @@ fn saved_scheme_accent_and_canvas_color_show_from_the_first_frame() { for _ in 0..2 { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); out.textures_delta.clear(); - let (theme, _, accent) = crate::theme::root_theme(&app.session.prefs); - let (default_theme, _, default_accent) = crate::theme::root_theme(&Prefs::default()); - assert_ne!(theme, default_theme, "the saved scheme"); - assert!(accent.is_some() && accent != default_accent, "the saved accent"); + let shown = crate::theme::root_theme(&app.session.prefs); + assert_ne!(shown.0, crate::theme::root_theme(&Prefs::default()).0, "the saved scheme"); + // Classic keeps its own accent whatever accent is saved, as production's Classic tokens did. + let classic = Prefs { ui_color_scheme: "classic".into(), ui_brightness: app.session.prefs.ui_brightness.clone(), ..Prefs::default() }; + let want = crate::theme::root_theme(&classic); + assert!(shown.0 == want.0 && shown.2 == want.2, "the saved accent"); assert_eq!(canvas_color(&app.session.prefs.canvas_color), Some(egui::Color32::WHITE)); } } diff --git a/crates/ui-egui/src/shortcuts/held_tool/tests.rs b/crates/ui-egui/src/shortcuts/held_tool/tests.rs index 1279c93e25..58e7f55a5b 100644 --- a/crates/ui-egui/src/shortcuts/held_tool/tests.rs +++ b/crates/ui-egui/src/shortcuts/held_tool/tests.rs @@ -27,6 +27,17 @@ impl Keyboard { crate::testing::app_frame(app, &self.ctx, egui::RawInput { events, screen_rect, time: Some(time), focused, ..Default::default() }); } + /// [`Self::frame`] without the window's parts: the app's tick and its held tools' returns only, so a + /// pointer press reaches no canvas. + fn off_canvas(&self, app: &mut VectorcraftApp, time: f64, events: Vec) { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let raw = egui::RawInput { events, screen_rect, time: Some(time), focused: true, ..Default::default() }; + crate::testing::part_frame(app, &self.ctx, raw, |app, ui| { + app.tick(ui.ctx()); + crate::shortcuts::follow_holds(app, ui.ctx()); + }); + } + /// `key` pressed (or repeated while it is down) at `time`, typing `letter`. fn press(&self, app: &mut VectorcraftApp, time: f64, key: Key, letter: &str) { let press = egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; @@ -226,7 +237,8 @@ fn a_press_in_the_frame_that_lets_go_waits_for_the_canvas() { let at = egui::pos2(150.0, 125.0); let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; let release = egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 0.1, vec![egui::Event::PointerMoved(at), press, release]); + // The press reaches no canvas in these frames: the canvas's own press is dispatched here. + keys.off_canvas(&mut app, 0.1, vec![egui::Event::PointerMoved(at), press, release]); assert_eq!(app.session.tool_id(), "scale", "canvas {canvas}: no decision before the canvas"); if canvas { let view = app.view_info(); @@ -234,7 +246,7 @@ fn a_press_in_the_frame_that_lets_go_waits_for_the_canvas() { crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, 150.0, 125.0), view); } } - keys.frame(&mut app, 2.0, vec![]); + keys.off_canvas(&mut app, 2.0, vec![]); assert_eq!(app.session.tool_id(), if canvas { "pen" } else { "scale" }, "canvas {canvas}"); } } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 423fcedfc6..20ca3b2138 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1463,7 +1463,6 @@ fn enter_after_a_drag_repeats_its_offset() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let ctx = ready(&mut app); let enter = || tap(Key::Enter, Modifiers::NONE); let lefts = |app: &VectorcraftApp| { let kids = app.session.doc().unwrap().doc.layers[0].children().unwrap(); @@ -1479,7 +1478,9 @@ fn enter_after_a_drag_repeats_its_offset() { let [moved] = lefts(&app)[..] else { panic!("one rectangle") }; let step = moved - 10.0; assert!(step > 0.0); - key_frame(&mut app, &ctx, vec![]); + // The window's first frame comes after the drag, which the view before it measures: one fitted to the window + // would put the press on a corner handle. + let ctx = ready(&mut app); key_frame(&mut app, &ctx, enter()); assert_eq!(dialog_kind(&app).as_deref(), Some("object.move"), "Enter opens Move"); assert_eq!(dialog_field(&app, "dx").and_then(|v| v.as_f64()).map(f64::round), Some(step)); From fea25adbf6fe4fa062fc40d3ed615ef12b581247 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:14:50 +0700 Subject: [PATCH 03/22] A test folder made under a name another running test also uses is its own: each Folder::new gets a number, so one test's removal no longer takes the other's files --- crates/ui-egui/src/tests/folder.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/tests/folder.rs b/crates/ui-egui/src/tests/folder.rs index e8b4dfae8d..611b9320e6 100644 --- a/crates/ui-egui/src/tests/folder.rs +++ b/crates/ui-egui/src/tests/folder.rs @@ -8,10 +8,13 @@ use std::path::PathBuf; pub(crate) struct Folder(PathBuf); impl Folder { - /// A new empty folder `vectorcraft--` in the system temporary folder. One - /// left there by an earlier process with the same id is removed first. + /// A new empty folder `vectorcraft---` in the system temporary folder, + /// `n` counting this process's folders so two tests running at once under one name don't + /// remove each other's. One left there by an earlier process with the same id is removed first. pub(crate) fn new(name: &str) -> Self { - let dir = std::env::temp_dir().join(format!("vectorcraft-{name}-{}", std::process::id())); + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("vectorcraft-{name}-{}-{n}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Self(dir) @@ -56,14 +59,25 @@ fn a_folder_is_removed_when_its_test_ends() { #[test] fn a_folder_is_removed_when_its_test_panics() { - let path = std::env::temp_dir().join(format!("vectorcraft-ui-folder-panics-{}", std::process::id())); + let path = std::sync::Mutex::new(PathBuf::new()); let r = vectorcraft_testkit::catch_quiet::<()>(|| { let folder = Folder::new("ui-folder-panics"); folder.file("a.txt", b"a"); + *path.lock().unwrap() = folder.to_path_buf(); panic!("the test fails"); }); assert_eq!(r.err().as_deref(), Some("the test fails")); - assert!(!path.exists(), "{} is left", path.display()); + let path = path.into_inner().unwrap(); + assert!(path.is_absolute() && !path.exists(), "{} is left", path.display()); +} + +#[test] +fn two_folders_under_one_name_are_apart() { + let a = Folder::new("ui-folder-twice"); + let b = Folder::new("ui-folder-twice"); + a.file("a.txt", b"a"); + drop(b); + assert!(a.join("a.txt").is_file(), "dropping one folder removed the other"); } #[test] From 3da4e57035d495737c662f84ddcc61f2138b7b4d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:14:51 +0700 Subject: [PATCH 04/22] A scrub of the selection's fields runs to its release: the fields measure from the box the gesture began on, so the base value they show no longer drifts and cancels it; a panel field's previews stay as one step in their document when another becomes active, as the scrub's undo group did --- crates/engine/src/interaction.rs | 3 +++ crates/engine/src/session/documents.rs | 9 +++++++-- crates/engine/src/session/edit.rs | 1 + crates/ui-egui/src/panels.rs | 4 ++++ crates/ui-egui/src/panels/transform.rs | 18 +++++++++++++++--- 5 files changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 06cc86859e..dffc5cdb65 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -33,6 +33,9 @@ pub struct Interaction { /// The bounding box of `selection` in `doc`, measured once for a move drag /// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move. pub(crate) move_box: std::sync::OnceLock>, + /// A switch to another document keeps the previews as one undo step in this one, as a panel field's scrub keeps + /// its edits; otherwise the switch cancels the interaction, as it does a drag. + pub keep_on_switch: bool, } /// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]). diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index b83b242fc3..c29705c364 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -218,9 +218,14 @@ impl Session { let _ = self.give_back_tool(view); let _ = self.deactivate_tool(view); // A batch leaves its interaction open in the document it leaves, to keep or roll back with - // the rest of the batch; anything else in progress (a drag) is cancelled. + // the rest of the batch; one that keeps on a switch is kept; anything else in progress (a + // drag) is cancelled. if self.batch_stash.is_none() { - let _ = self.cancel_interaction(); + let _ = if self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) { + self.commit_interaction() + } else { + self.cancel_interaction() + }; } self.keep_tool_settings(); self.tool = self.make_tool(self.tool.id()); diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 28c2be565e..4dd3309b9d 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -320,6 +320,7 @@ impl Session { plane_placed: false, copies: None, move_box: std::sync::OnceLock::new(), + keep_on_switch: false, }); Ok(()) } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 90b921f08a..fd5321c9fa 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -756,6 +756,10 @@ pub(crate) enum Live { /// it as one undo step. Falls back to a plain run when no document is open. pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: Value, phase: Live) { if app.begin_interaction(label).is_ok() { + // As the scrub's undo step was, the gesture's previews stay in their document when another becomes active. + if let Some(it) = app.session.active_mut().and_then(|st| st.interaction.as_mut()) { + it.keep_on_switch = true; + } if let Err(e) = app.session.preview(cmd, ¶ms) { app.ui.status = e.to_string(); } diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index dde9b1808a..9f54c58271 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -69,11 +69,13 @@ pub struct TransformUi { gesture_origin: Value, /// The artboards' rectangles when a field's running gesture began ([`live_artboard`]). gesture_boards: Vec, + /// The selection's box when a field's running gesture began ([`gesture_start`]). + gesture_start: Rect, } impl Default for TransformUi { fn default() -> Self { - TransformUi { reference_point: 4, popover: false, gesture_origin: Value::Null, gesture_boards: Vec::new() } + TransformUi { reference_point: 4, popover: false, gesture_origin: Value::Null, gesture_boards: Vec::new(), gesture_start: Rect::ZERO } } } @@ -190,6 +192,15 @@ fn gesture_origin(app: &mut VectorcraftApp) -> Value { app.ui.transform_panel.gesture_origin.clone() } +/// The box the selection's fields measure from, `now` outside a gesture: while one runs, the box as it began, since +/// the fields read the gesture's values against the box before the transform and its previews move the selection's. +fn gesture_start(app: &mut VectorcraftApp, now: Rect) -> Rect { + if !app.session.in_interaction() { + app.ui.transform_panel.gesture_start = now; + } + app.ui.transform_panel.gesture_start +} + /// Where the registration point of the one selected symbol instance is on the page, while Use /// Registration Point for Symbol is on: the point of the symbol's art box on the 9-point grid, /// placed by the instance's transform. @@ -400,7 +411,7 @@ fn set_object_bounds(app: &mut VectorcraftApp, source: TransformSource, row: &Tr pub(crate) fn object_fields(app: &mut VectorcraftApp, ui: &mut Ui, groups: TransformGroups) { let bx = app.selection_box(); let state = bx.as_ref().map(|b| box_state(app, b)); - let start = bx.map_or(Rect::ZERO, |b| b.rect); + let start = gesture_start(app, bx.map_or(Rect::ZERO, |b| b.rect)); let out = fields(app, state, start, groups, false).show(ui); apply_fields(app, &out, EditPath::Preview, set_object_bounds); } @@ -410,7 +421,8 @@ pub(crate) fn object_fields(app: &mut VectorcraftApp, ui: &mut Ui, groups: Trans pub(crate) fn object_bar_fields(app: &mut VectorcraftApp, ui: &mut Ui) -> Option { let bx = app.selection_box()?; let state = box_state(app, &bx); - let out = fields(app, Some(state), bx.rect, panel_groups(), true).show(ui); + let start = gesture_start(app, bx.rect); + let out = fields(app, Some(state), start, panel_groups(), true).show(ui); apply_fields(app, &out, EditPath::Preview, set_object_bounds); Some(out) } From 5292fe1dee0375a562ad518571196b20ff2a844b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:14:52 +0700 Subject: [PATCH 05/22] The fake clipboard reports the owner marker the platform has, as production's fake did: set by the app's write, cleared by another app's copy --- crates/ui-egui/src/tests/sysclip.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 510e177176..c3357f4e10 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -19,6 +19,8 @@ use crate::{Services, VectorcraftApp, background}; #[derive(Default)] pub(super) struct Board { flavours: Vec, + /// The app wrote what the clipboard holds (the platform's owner marker): nothing was copied since. + ours: bool, /// How many times the app wrote it. writes: usize, /// Another app has the clipboard open: the app's writes fail and change nothing, and reads @@ -79,13 +81,14 @@ impl ClipboardBackend for Fake { if b.race_with_our_formats { b.flavours.extend(ours.into_iter().filter(|f| f.mime != TEXT)); } + b.ours = false; return Err(ClipboardError::Other("another app has the clipboard open".into())); } if b.partial { b.flavours = if b.partial_keeps_others { ours.into_iter().filter(|f| f.mime != TEXT).collect() } else { vec![] }; return Err(ClipboardError::Other("a format could not be written".into())); } - *b = Board { flavours: ours, writes: b.writes + 1, ..std::mem::take(&mut *b) }; + *b = Board { flavours: ours, ours: true, writes: b.writes + 1, ..std::mem::take(&mut *b) }; Ok(0) } @@ -109,6 +112,10 @@ impl ClipboardBackend for Fake { Ok(None) } + fn owns(&mut self) -> Option { + Some(self.board().ours) + } + fn has(&mut self, mimes: &[&str]) -> bool { if self.board().text_only_has { return mimes.contains(&TEXT) && self.find(&[TEXT]).is_some(); @@ -145,7 +152,7 @@ pub(super) fn app() -> (VectorcraftApp, Arc>) { pub(super) fn copy_elsewhere(board: &Arc>, flavours: Vec<(&'static str, Vec)>) { let flavours = flavours.into_iter().map(|(mime, data)| Flavour { mime, data }).collect(); let mut b = board.lock().unwrap(); - *b = Board { flavours, ..std::mem::take(&mut *b) }; + *b = Board { flavours, ours: false, ..std::mem::take(&mut *b) }; } /// Another app opens the clipboard (`true`) or closes it. From 9df876b1ffe6f9dd8bb9008b369c19758a32ba4a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:14:53 +0700 Subject: [PATCH 06/22] =?UTF-8?q?Shape=20properties'=20angle=20fields=20sh?= =?UTF-8?q?ow=20production's=20trimmed=20degrees=20(360=C2=B0,=20not=20360?= =?UTF-8?q?.0=C2=B0),=20committing=20one=20decimal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/panels/transform/shape.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/transform/shape.rs b/crates/ui-egui/src/panels/transform/shape.rs index f4358ba79a..c81d45da47 100644 --- a/crates/ui-egui/src/panels/transform/shape.rs +++ b/crates/ui-egui/src/panels/transform/shape.rs @@ -74,7 +74,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: let bind = Bind::given(value); let field = match quantity { Quantity::Length => NumberField::length(label, bind, general_lengths(app)), - Quantity::Degrees => NumberField::new(label, bind).unit("°").fixed_decimals(1), + Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1), Quantity::Sides => NumberField::new(label, bind).range(3.0..=1000.0).fixed_decimals(0), }; edit = Some(field.show(ui).edit); From 8a9372bcb1467ab69993242a37383472eee27a9b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:17:05 +0700 Subject: [PATCH 07/22] Tests: Save of an untitled document reads the file after the frame that takes the save panel's answer; touching colour bars count as in row order --- crates/ui-egui/src/tests/nativeoptions.rs | 2 ++ crates/ui-egui/src/tests/recolor.rs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/nativeoptions.rs b/crates/ui-egui/src/tests/nativeoptions.rs index 35826145d5..946cdc30d5 100644 --- a/crates/ui-egui/src/tests/nativeoptions.rs +++ b/crates/ui-egui/src/tests/nativeoptions.rs @@ -198,6 +198,8 @@ fn save_a_copy_and_save_dont_ask_and_options_reach_the_file() { host(&mut app); // Save of an untitled document goes straight to the file, as before. app.run("file.save", Value::Null).unwrap(); + // The save panel's answer arrives as a frame's tick takes it. + pass(&mut app); assert!(open_dialogs(&app).is_empty()); assert_eq!(written.borrow().len(), 1); app.run("file.saveAs", Value::Null).unwrap(); diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 551d6da5dc..d97a3a5ed5 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -939,7 +939,8 @@ fn color_bars_select_edit_and_reorder_the_rows() { assert!(!has(&r, "Color 2"), "no bar for the excluded row"); let first = rect(&r, "Color 1"); let last = rect(&r, "Color 4"); - assert!(r.by_label("Color 3").is_some_and(|t| t.rect.top() > first.bottom() && t.rect.bottom() < last.top()), "in row order"); + // The List's rows touch: a row below another starts where the one above ends. + assert!(r.by_label("Color 3").is_some_and(|t| t.rect.top() >= first.bottom() && t.rect.bottom() <= last.top()), "in row order"); click(&mut r, last.center()); assert_eq!(field(&r, "__sel"), json!([3]), "a click selects the bar's row"); let unedited = field(&r, "rows"); From 2663c9281a2d1c76c7785864d417a194f58d9b3d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:19:38 +0700 Subject: [PATCH 08/22] The plug-in install question records whether automation's injected input pressed its OK in the pass that pressed it: the answer is read after that pass, when no pass is running, so automation's Enter, Space or click on a focused OK installed the plug-in --- crates/ui-egui/src/dialogs/plugin.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 07ab7dbb13..5975c88934 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -35,6 +35,7 @@ use craft::ui::contract::Show as _; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id}; use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; +use craft::ui::runtime::windows::WindowHost; use craft::ui::sections::{DialogRole, FooterButton}; use egui::Ui; use serde_json::{Map, Value, json}; @@ -535,7 +536,8 @@ impl InstallPrompt { } impl StackDialog for InstallPrompt { - type Result = (); + /// OK was pressed in a pass automation's injected input drove: the answer is read after that pass. + type Result = bool; fn id(&self) -> DialogId { self.id @@ -545,7 +547,7 @@ impl StackDialog for InstallPrompt { Some(INSTALL_KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let mut prompt = Prompt::new(tl!("Install Plug-in"), self.message.clone()).paragraph(self.detail.clone()); if self.automated { prompt = prompt.paragraph(automation_asked_note()); @@ -558,7 +560,7 @@ impl StackDialog for InstallPrompt { ]) .show(ui); match shown.picked { - Some(0) => Some(DialogResult::Ok(())), + Some(0) => Some(DialogResult::Ok(WindowHost::of(ui.ctx()).injected_pass())), Some(1) => Some(DialogResult::Cancel), _ => None, } @@ -595,20 +597,21 @@ fn pump_install(app: &mut VectorcraftApp) { }); let Some(answer) = answer else { return }; match answer.ok() { - Some(()) => approve(app), + Some(injected) => approve(app, injected), None => app.pending_plugin_install = None, } } -/// OK of the install question. A question automation asked has no OK that installs, and automation -/// can't press one: either asks again, a new question that waits its delay. -fn approve(app: &mut VectorcraftApp) { +/// OK of the install question, `injected` when automation's input pressed it. A question automation +/// asked has no OK that installs, and automation can't press one: either asks again, a new question +/// that waits its delay. +fn approve(app: &mut VectorcraftApp, injected: bool) { let Some(pending) = app.pending_plugin_install.take() else { return }; if pending.origin == InstallOrigin::Automation { ask_install(app, pending); return; } - if app.automation_is_acting() { + if injected || app.automation_is_acting() { app.status("Only the person at the keyboard can approve installing a plug-in".to_string()); ask_install(app, pending); return; From 128f4e30a839de9fc1228cc8b83c62a2756c9446 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:21:04 +0700 Subject: [PATCH 09/22] Tests: the W field is found by its name Width in a full-size window and the press lands where the canvas shows the other rectangle; the chip popover's swatches are clicked by their names with values, the Control bar test in a window's width --- crates/ui-egui/src/tests/numfields.rs | 11 ++++++----- crates/ui-egui/src/tests/paintchips.rs | 14 ++++++++++---- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/tests/numfields.rs b/crates/ui-egui/src/tests/numfields.rs index 21b71e580c..36359507e9 100644 --- a/crates/ui-egui/src/tests/numfields.rs +++ b/crates/ui-egui/src/tests/numfields.rs @@ -99,12 +99,13 @@ fn a_press_on_the_canvas_commits_to_the_object_being_edited() { let app = Rc::new(RefCell::new(app)); let shared = app.clone(); let mut fixture = Fixture::new(move |ui| window(&mut shared.borrow_mut(), ui)); - fixture.settle(); - // The Transform panel's W field is named by its label, "W"; a click on it focuses the field. - let label = fixture.by_label("W").expect("the Transform panel shows the W field"); + // A window as large as the scrub tests', with the docked Transform panel; the fixture's own room is too small for it. + fixture.room(egui::vec2(1600.0, 900.0)).settle(); + // The W field shows the label "W" and is named "Width"; a click on it focuses the field. + let label = fixture.by_label("Width").expect("the Transform panel shows the W field"); fixture.click(&label).idle(2).key(Key::A, Modifiers::COMMAND).type_text("42").idle(1); - // PLAN: assumed the artboard is centred in the window, so the window's centre is on the big rectangle only. - let canvas = fixture.ctx().content_rect().center(); + // A point of the big rectangle away from the small one, where the canvas shows it. + let canvas = app.borrow().canvas_view().expect("the canvas is laid out").to_screen(vectorcraft_geom::Point::new(250.0, 200.0)); fixture.click_at(canvas).idle(3); let app = app.borrow(); diff --git a/crates/ui-egui/src/tests/paintchips.rs b/crates/ui-egui/src/tests/paintchips.rs index 1f356acdf7..8eeb123055 100644 --- a/crates/ui-egui/src/tests/paintchips.rs +++ b/crates/ui-egui/src/tests/paintchips.rs @@ -18,6 +18,9 @@ fn fill_hex(app: &VectorcraftApp) -> String { panels::current_paints(app).0.color().map(|c| c.to_hex()).unwrap_or_default() } +/// The Red swatch's name in the swatch popover. +const RED: &str = "Red, #ed1c24"; + /// A point of the panel's room that holds no control. fn outside() -> Pos2 { Pos2::new(ROOM.x - 5.0, ROOM.y - 5.0) @@ -37,16 +40,19 @@ fn a_popover_tile_click_sets_the_fill() { app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); app.run("paint.toggleActive", json!({"fill": false})).unwrap(); let mut panel = Panel::new(app, chrome::control_bar); + // The Control bar ranks its groups out of a panel's width; a window's width shows Fill and Stroke. + panel.room(egui::vec2(2200.0, 200.0)); panel.click("Fill"); assert!(panel.app().session.fill_active, "the Fill chip brings its proxy forward"); - panel.click("Red"); + // A colour swatch is named by its name and value. + panel.click(RED); assert_eq!(fill_hex(&panel.app()), "#ed1c24"); assert_eq!(panel.app().session.doc().unwrap().history.undo.last().unwrap().label, "Fill Color", "through paint.setFill"); // The Stroke chip: its proxy comes forward; Shift-click shows the mixer instead of swatches. panel.key(Key::Escape, Modifiers::NONE); panel.click_with("Stroke", Modifiers::SHIFT); assert!(!panel.app().session.fill_active); - assert!(!panel.shows("Red"), "no swatches in the mixer"); + assert!(!panel.shows(RED), "no swatches in the mixer"); assert!(panel.shows("Recent Colors"), "the Color panel's body"); } @@ -60,14 +66,14 @@ fn the_properties_panel_has_the_control_bars_fill_and_stroke() { } assert!(panel.rect("Stroke").top() > panel.rect("Fill").bottom(), "Fill above Stroke"); panel.click("Fill"); - panel.click("Red"); + panel.click(RED); assert_eq!(fill_hex(&panel.app()), "#ed1c24", "the next object's fill"); panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); assert_eq!(fill_hex(&panel.app()), "#ed1c24", "the new rectangle (selected) has it"); // With the rectangle selected: the same chips, under the Transform section. panel.key(Key::Escape, Modifiers::NONE); panel.click("Fill"); - panel.click("Black"); + panel.click("Black, #000000"); assert_eq!(fill_hex(&panel.app()), "#000000"); assert_eq!(panel.app().session.doc().unwrap().history.undo.last().unwrap().label, "Fill Color"); } From a579ca90dbeac50bcf0f9de66b09fc8f8c9b3be2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 23 Nov 2026 15:58:59 +0700 Subject: [PATCH 10/22] Docking and document windows follow production again: a tab F7 hid with its group comes back alone when a command shows it; a panel floated out of the icon column by a command opens expanded; a floating panel's OS window takes the canvas's carried art and passes its leftover Escape and Enter on as the main window does; a dimmed key does nothing while a dialog or a text field has the keys; a press anywhere on a floating document window makes it current, but not while a dialog is open; floating windows fit again when their size changes and after Presentation Mode; a tab dragged without a reorder is no click and one dropped back on its own strip docks nothing; the document-window tests read a window's bounds and the tab strip from the access tree --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/panes.rs | 17 +++-- crates/ui-egui/src/canvas/tool_adapter.rs | 59 +++++++++-------- crates/ui-egui/src/chrome/tabs.rs | 10 ++- crates/ui-egui/src/doc_windows.rs | 19 ++++-- crates/ui-egui/src/doc_windows/tests.rs | 78 ++++++++++++++++------- crates/ui-egui/src/panel_docking.rs | 54 ++++++++++++++-- crates/ui-egui/src/shortcuts.rs | 17 ++++- 8 files changed, 185 insertions(+), 71 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b7b103290e..d0be1a260c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -52,7 +52,7 @@ pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; pub(crate) use rulers::{general_lengths, stroke_lengths}; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions}; pub use tool_adapter::{apply_requests, dispatch, mods}; -pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page}; +pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page, tool_enter}; /// Which body a document's canvas runs: the current window's interactive one, or a display-only /// pane of a tiled or floating window. diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 4dedfa2f09..0d4f6a1076 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -378,12 +378,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { super::drops::show(app, &mut catcher, w, BodyKind::Pane); } drop_released(app); - // Note the fits this frame made, for `refit_resized`. - for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { - if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { - app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); - } - } + note_fits(app, &areas, &unfitted); }); let activated = split.output.activated; app.canvas.panes.at = lines; @@ -434,6 +429,16 @@ pub(crate) fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect) .collect() } +/// Note the fits this frame made, for [`refit_resized`]: each of `areas`' views that was unfitted +/// (`unfitted`, as `refit_resized` returned) and is fitted now, with its area's size. +pub(crate) fn note_fits(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)], unfitted: &[bool]) { + for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { + if let (true, Some(v), Some(s)) = (*was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { + app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); + } + } +} + /// Fit `v` to show its artboard (the first if it has gone) in `area`, with the interface zoomed by /// `ui_zoom` on a screen of `pixels_per_point`, as Fit Artboard in Window does. fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, area: egui::Rect, (ui_zoom, pixels_per_point): (f32, f32), scheme: &ZoomScheme) { diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 9bb95ae577..bf97fb56c2 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -109,6 +109,30 @@ fn sync_artboard(app: &mut VectorcraftApp) { } } +/// Enter that the tool does not claim, while no gesture runs: it takes what the tool asks of the UI (Rotate, Scale, +/// Reflect and Shear open their dialog), and with a selection tool it opens the Move dialog, as a double-click on the +/// tool's button does. Taken only when a dialog opened, so that Enter is not also its OK. +pub(crate) fn tool_enter(app: &mut VectorcraftApp, mods: Mods, view: ViewInfo) -> bool { + if app.session.tool_busy() { + return false; + } + let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); + let before = open(app); + let r = app.session.tool_key(EngineKey::Enter, mods, view); + apply_requests(app, r); + let tool = app.session.tool_id().to_owned(); + if open(app) == before && vectorcraft_tools::catalog::is_selection_tool(&tool) { + // Nothing selected: it fails and nothing opens (the menu item is disabled then too). + let _ = crate::toolbar::open_options(app, &tool); + } + let opened = open(app) > before; + // The dialog uses the tool a held key chose. + if opened { + crate::shortcuts::note_tool_use(app); + } + opened +} + /// The session as a tool for one pass. The host's trait takes `&self` for the cursor and the claims, which the /// session answers through `&mut`, so the app sits in a cell. struct SessionTool<'a> { @@ -126,9 +150,10 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } - /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas. + /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating + /// document's or a floating panel's OS window. fn covered(&self, pointer: &ToolPointer) -> bool { - self.ctx.layer_id_at(pointer.pos).is_some_and(|l| l != self.layer) + self.ctx.layer_id_at(pointer.pos).is_some_and(|l| l != self.layer) || crate::panel_docking::os_window_at(&self.app(), &self.ctx, pointer.pos) } fn app(&self) -> RefMut<'_, &'a mut VectorcraftApp> { @@ -153,29 +178,9 @@ impl<'a> SessionTool<'a> { true } - /// Enter that the tool does not claim, while no gesture runs: it takes what the tool asks of the UI (Rotate, - /// Scale, Reflect and Shear open their dialog), and with a selection tool it opens the Move dialog, as a - /// double-click on the tool's button does. Taken only when a dialog opened, so that Enter is not also its OK. + /// [`tool_enter`] in this canvas's view. fn enter(&self, mods: Mods) -> bool { - let mut app = self.app(); - if app.session.tool_busy() { - return false; - } - let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); - let before = open(&app); - let r = app.session.tool_key(EngineKey::Enter, mods, self.view); - apply_requests(&mut app, r); - let tool = app.session.tool_id().to_owned(); - if open(&app) == before && vectorcraft_tools::catalog::is_selection_tool(&tool) { - // Nothing selected: it fails and nothing opens (the menu item is disabled then too). - let _ = crate::toolbar::open_options(&mut app, &tool); - } - let opened = open(&app) > before; - // The dialog uses the tool a held key chose. - if opened { - crate::shortcuts::note_tool_use(&mut app); - } - opened + tool_enter(&mut self.app(), mods, self.view) } /// A key the tool does not claim while its gesture runs: arrows and digits still reach it, with no modifier (a @@ -286,7 +291,8 @@ impl CanvasTool for SessionTool<'_> { return; } // Art carried off the canvas waits where it last moved; back on the canvas the move goes on. - let carried = super::drops::carry_out(&mut self.app(), cx, pointer, self.covered(pointer)); + let covered = self.covered(pointer); + let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { let ev = pointer_event(PointerKind::Drag, pointer, cx); dispatch(&mut self.app(), &ev, self.view); @@ -306,7 +312,8 @@ impl CanvasTool for SessionTool<'_> { return; } drop(app); - let carried = super::drops::carried(&self.app(), cx, pointer, self.covered(pointer)); + let covered = self.covered(pointer); + let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); if cx.over_drop_target() || carried.is_some() { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index a2235c79d4..e19c5a6ddd 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -101,7 +101,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { } let held = !carrying && ui.input(|i| i.pointer.primary_down()); for event in strip.show(ui).events { - if matches!(event, DocumentTabsEvent::Reordered { .. } | DocumentTabsEvent::TornOff { .. }) { + if matches!(event, DocumentTabsEvent::Reordered { .. } | DocumentTabsEvent::TornOff { .. } | DocumentTabsEvent::DroppedInto { .. }) { ui.data_mut(|d| d.remove::(pressed)); } match event { @@ -134,7 +134,9 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { } } DocumentTabsEvent::DroppedInto { documents, .. } => { - for (index, view) in documents { + // A tab of this strip dropped back on it past the tabs is already docked. + let floating: Vec = documents.into_iter().filter(|w| doc_windows::floats(app, *w)).collect(); + for (index, view) in floating { run_reporting(app, "window.arrange.consolidateAllWindows", json!({"index": index, "view": view})); } } @@ -142,6 +144,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { _ => {} } } + // A press that moved past a click's reach is a drag, whether or not it reordered the tabs. + if held && ui.input(|i| i.pointer.is_decidedly_dragging()) { + ui.data_mut(|d| d.remove::(pressed)); + } if !held && let Some(w) = ui.data_mut(|d| d.remove_temp::(pressed)) { doc_windows::show_window(app, w); } diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 619d1ee8c8..ca2fa7fe3b 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -348,6 +348,8 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { for w in wins { if let Some(v) = view_mut(app, w) { v.fitted = false; + // The area it last showed its art in is the main window's: it fits its window's. + v.rect = egui::Rect::NOTHING; } } } @@ -381,21 +383,24 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin)); let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window }; let out = window.show(ui, |ui, _| { + // A press anywhere on the window, its title bar and tab included, makes its document current. + pressed = pressed_on_layer(ui); crate::chrome::window_tab(app, ui, win); - let rect = ui.available_rect_before_wrap(); - crate::canvas::panes::refit_resized(app, &[(win, rect)]); + let areas = [(win, ui.available_rect_before_wrap())]; + let unfitted = crate::canvas::panes::refit_resized(app, &areas); if live { show_document(app, ui, win, BodyKind::Live); } else { - pressed = crate::canvas::pane(app, ui, win, rect); + pressed |= crate::canvas::pane(app, ui, win, areas[0].1); } + crate::canvas::panes::note_fits(app, &areas, &unfitted); }); if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) { x.focused = out.focused; } if out.close_requested.is_some() { close = Some(win); - } else if (out.focus_gained || pressed) && !is_current { + } else if (out.focus_gained || pressed) && !is_current && !app.any_dialog_open() { activate = Some(win); } } @@ -413,5 +418,11 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } +/// Whether the primary button went down over `ui`'s layer in this pass. +fn pressed_on_layer(ui: &egui::Ui) -> bool { + let at = ui.ctx().input(|i| i.pointer.primary_pressed().then_some(i.pointer.interact_pos()).flatten()); + at.is_some_and(|at| ui.ctx().layer_id_at(at) == Some(ui.layer_id())) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 887cb15def..28bab1d05a 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -23,19 +23,54 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec s => out.push(s), } } + let out = run_frame(app, ctx, events); + let mut shapes = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); + shapes +} + +/// One headless frame of the canvas panel's body and the floating document windows on a 1200 × +/// 800 window. The windows' access nodes, by name, are kept for [`window_of`]. +fn run_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), max_texture_side: Some(8192), events, ..Default::default() }; + ctx.enable_accesskit(); let out = crate::testing::part_frame(app, ctx, raw, |app, ui| { app.canvas_area(ui); show(app, ui); }); - let mut shapes = vec![]; - out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); - shapes + let nodes = out.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]); + let named: Vec = nodes + .iter() + .filter(|(_, n)| matches!(n.role(), egui::accesskit::Role::Group | egui::accesskit::Role::TabList)) + .filter_map(|(_, n)| { + let b = n.bounds()?; + Some((n.role(), n.label()?.to_owned(), egui::Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))) + }) + .collect(); + ctx.data_mut(|d| d.insert_temp(egui::Id::new(NAMED), std::sync::Arc::new(named))); + out +} + +/// A group or tab list of the last frame's accessibility tree: its role, name and bounds. +type Named = (egui::accesskit::Role, String, egui::Rect); + +/// Where [`run_frame`] keeps the last frame's [`Named`] nodes. +const NAMED: &str = "doc-window-tests-named"; + +/// The last frame's [`Named`] nodes of `role` whose name `matches`. +fn named(ctx: &egui::Context, role: egui::accesskit::Role, matches: impl Fn(&str) -> bool) -> Option { + let nodes: std::sync::Arc> = ctx.data(|d| d.get_temp(egui::Id::new(NAMED))).unwrap_or_default(); + nodes.iter().find(|(r, name, _)| *r == role && matches(name)).map(|(_, _, rect)| *rect) +} + +/// The main window's document tab strip, as the last frame drew it. +fn strip(ctx: &egui::Context) -> egui::Rect { + named(ctx, egui::accesskit::Role::TabList, |name| name == "Documents").expect("the tab strip was drawn") } fn button(pos: Pos2, pressed: bool) -> egui::Event { @@ -61,11 +96,15 @@ fn canvas_rect(app: &VectorcraftApp) -> egui::Rect { app.view().unwrap().rect } -/// The whole of document `i`'s window, title bar included. -fn window_of(app: &VectorcraftApp, _ctx: &egui::Context, i: usize) -> egui::Rect { - let uid = app.session.documents()[i].uid; - // PLAN: the window's bounds come from its access node (canvas-w27's kit driver); the placed rect stands in until then. - app.ui.floating.iter().find(|w| w.uid == uid).unwrap().place +/// The whole of document `i`'s window, title bar included, as the last frame drew it: the bounds +/// of its access node, named by its title. +fn window_of(app: &VectorcraftApp, ctx: &egui::Context, i: usize) -> egui::Rect { + let title = app.session.documents()[i].title(); + // The name is the title, a `*` while it has unsaved changes, then the zoom and color mode. + let window = |name: &str| { + name.strip_prefix(title.as_str()).map(|rest| rest.trim_start_matches('*')).is_some_and(|rest| rest.is_empty() || rest.starts_with(' ')) + }; + named(ctx, egui::accesskit::Role::Group, window).unwrap_or_else(|| panic!("document {i}'s window, {title}, was drawn")) } /// Where the last frame drew the tab of the window `window` at the top of its body (the title text @@ -488,8 +527,8 @@ fn dragging_a_tab_off_the_strip_floats_its_document_at_the_pointer() { let tab = tab_at(&shapes, &title); // A short drag, and a drag along the strip short of the next tab's middle, leave the tabs as // they are. - // The strip is 35 points tall: a drag that stays within its height is no tear-off. - drag(&mut app, &ctx, tab, tab + vec2(0.0, 35.0 - tab.y)); + // A drag that stays within the strip's height is no tear-off. + drag(&mut app, &ctx, tab, pos2(tab.x, strip(&ctx).bottom())); drag(&mut app, &ctx, tab, tab + vec2(40.0, 0.0)); assert!(app.ui.floating.is_empty(), "the document stays under its tab"); assert_eq!(app.session.active_index(), Some(2), "a drag is not a click"); @@ -530,7 +569,7 @@ fn a_window_dragged_by_its_tab_onto_the_strip_goes_back_under_the_tabs() { assert!(tab_drawn(&shapes, &app.session.documents()[2].title()), "it has its tab again"); assert!(app.views[2].fitted, "it fits the canvas under the tabs"); let canvas = canvas_rect(&app); - assert!(canvas.top() >= 35.0 && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}"); + assert!(canvas.top() >= strip(&ctx).bottom() && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}"); // Torn off again, it opens where its tab is dropped, not where its last window was. let to = pos2(200.0, 300.0); let tab = tab_at(&shapes, &app.session.documents()[2].title()); @@ -694,8 +733,9 @@ fn an_os_windows_tab_docks_on_the_strip() { }; // The tab at the top of the window. let tab = pos2(20.0, 15.0); - // Released over the main window's tab strip (y 0 to 35 on the screen), it docks. - os_drag(&mut app, tab, pos2(20.0, -280.0)); + // Released over the main window's tab strip, it docks. + let over_strip = strip(&ctx).center().y - 300.0; + os_drag(&mut app, tab, pos2(20.0, over_strip)); assert!(app.ui.floating.is_empty(), "the document is back under the tabs"); assert_eq!(docked(&app), [0, 1]); assert_eq!(app.session.active_index(), Some(1)); @@ -861,17 +901,7 @@ fn switching_views_targets_the_artboard_the_view_shows() { /// ([`crate::canvas::release_over_panel`]), then the tabs and the canvas or panes, then the floating /// document windows. → the cursor. fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::CursorIcon { - let raw = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), - max_texture_side: Some(8192), - events, - ..Default::default() - }; - let out = crate::testing::part_frame(app, ctx, raw, |app, ui| { - app.canvas_area(ui); - show(app, ui); - }); - out.platform_output.cursor_icon + run_frame(app, ctx, events).platform_output.cursor_icon } /// Two 400 × 300 pt documents on `ctx`: the first, current under its tab, holds a 50 pt square at diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index bdf8309acb..08d08d9a7c 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -459,6 +459,26 @@ pub(crate) fn hide_group(app: &mut VectorcraftApp, panel: &str) -> Result