diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 06cc86859e..d6b572535c 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 preview as one undo step instead of canceling it + /// ([`crate::Session::keep_interaction_on_switch`]). + pub(crate) 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 1685adc40f..804ef2f494 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -218,9 +218,11 @@ 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; anything else in progress (a drag) is cancelled, except a drag on a + // panel's slider, which keeps its preview as one undo step there. if self.batch_stash.is_none() { - let _ = self.cancel_interaction(); + let keep = self.active().and_then(|d| d.interaction.as_ref()).is_some_and(|it| it.keep_on_switch); + let _ = if keep { 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 e2ba1715b9..95827f0ff6 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -312,6 +312,7 @@ impl Session { plane_placed: false, copies: None, move_box: std::sync::OnceLock::new(), + keep_on_switch: false, }); Ok(()) } @@ -508,6 +509,15 @@ impl Session { Ok(()) } + /// Keep the open interaction's preview as one undo step, instead of canceling it, when another + /// document becomes active: a drag on a panel's slider, which keeps what it previewed when it + /// ends without a release. + pub fn keep_interaction_on_switch(&mut self) { + if let Some(it) = self.active_mut().and_then(|d| d.interaction.as_mut()) { + it.keep_on_switch = true; + } + } + pub fn in_interaction(&self) -> bool { self.active().is_some_and(|d| d.interaction.is_some()) } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 5287aa0f4d..af504e8dac 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -1516,9 +1516,36 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } if let Some((key, v, phase)) = slid { let p = aligned(app, json!({"item": item, "index": k, "params": {key: v}})); - super::live_run(app, SLIDE_LABEL, "effect.setParams", p, phase); - let owner = if phase == widgets::Live::Dragging { slide_interaction(app) } else { None }; - set_pstate(ui.ctx(), SLIDE_OWNER, owner); + let hold = match pstate::(ui.ctx(), SLIDE_OWNER) { + // A drag that previewed goes on only in the interaction it began. + SlideHold::Live(owner) => { + if slide_interaction(app).is_some_and(|now| same_slide(&owner, &now)) { + SlideHold::Live(owner) + } else { + SlideHold::Lost + } + } + SlideHold::Lost => SlideHold::Lost, + SlideHold::Idle => begin_slide(app), + }; + match hold { + SlideHold::Live(owner) => { + super::live_run(app, SLIDE_LABEL, "effect.setParams", p, phase); + let next = if phase == widgets::Live::Dragging { SlideHold::Live(owner) } else { SlideHold::Idle }; + set_pstate(ui.ctx(), SLIDE_OWNER, next); + } + // The slider's own interaction could not begin: a click or a key still runs its edit. + SlideHold::Idle => { + if phase == widgets::Live::Released { + app.run("effect.setParams", p).ok(); + } + } + // Another interaction is open, or replaced the drag's own: the drag leaves it alone. + SlideHold::Lost => { + let next = if phase == widgets::Live::Dragging { SlideHold::Lost } else { SlideHold::Idle }; + set_pstate(ui.ctx(), SLIDE_OWNER, next); + } + } } if edit { app.run("effect.dialog", aligned(app, json!({"effect": e.id, "index": k, "item": item}))).ok(); @@ -1536,9 +1563,22 @@ const SLIDER_MIN_W: f32 = 24.0; const SLIDE_LIVE: &str = "ap-fx-slide-live"; /// The interaction that a drag on a plug-in parameter's slider in [`effect_editor`] previews in -/// ([`slide_interaction`]). +/// ([`SlideHold`]). const SLIDE_OWNER: &str = "ap-fx-slide-owner"; +/// Where a drag on a plug-in parameter's slider in [`effect_editor`] previews. +#[derive(Clone, Debug, Default)] +enum SlideHold { + /// No drag has previewed yet. + #[default] + Idle, + /// The drag previews in the interaction it began ([`slide_interaction`]). + Live(SlideOwner), + /// Another interaction was open when the drag began, or replaced the one it began: the drag + /// previews nothing and keeps nothing until it ends. + Lost, +} + /// The undo step a drag on a plug-in parameter's slider in [`effect_editor`] is kept as. const SLIDE_LABEL: &str = "Effect Options"; @@ -1552,6 +1592,30 @@ fn slide_interaction(app: &VectorcraftApp) -> Option { d.interaction.as_ref().filter(|it| it.label == SLIDE_LABEL).map(|it| (d.uid, Arc::downgrade(&it.selection))) } +/// Whether two [`SlideOwner`]s are the same interaction. +fn same_slide(a: &SlideOwner, b: &SlideOwner) -> bool { + a.0 == b.0 && a.1.ptr_eq(&b.1) +} + +/// Begin the interaction a drag on a plug-in parameter's slider previews in → [`SlideHold::Live`] +/// with it; [`SlideHold::Lost`] when another interaction is open, which beginning leaves as it is; +/// [`SlideHold::Idle`] when it could not begin (a script runs). A switch to another document during +/// the drag keeps what it previewed as one undo step in the document it began in. +fn begin_slide(app: &mut VectorcraftApp) -> SlideHold { + let open: Option = app.session.active().and_then(|d| d.interaction.as_ref().map(|it| (d.uid, Arc::downgrade(&it.selection)))); + if app.begin_interaction(SLIDE_LABEL).is_err() { + return SlideHold::Idle; + } + match slide_interaction(app) { + // One that was open before the drag, of the same name, is not the drag's own. + Some(now) if !open.is_some_and(|o| same_slide(&o, &now)) => { + app.session.keep_interaction_on_switch(); + SlideHold::Live(now) + } + _ => SlideHold::Lost, + } +} + /// A drag on a plug-in parameter's slider that this pass did not draw (its row closed, the /// selection changed so the row is gone, or the panel closed), or that ended with no value to /// keep, reports no release: the preview it made in its own interaction is kept as one undo step @@ -1559,9 +1623,8 @@ fn slide_interaction(app: &VectorcraftApp) -> Option { /// rows, and the app at the end of every pass, after the panels. pub(crate) fn end_stale_slide(app: &mut VectorcraftApp, ctx: &egui::Context) { if pstate::>(ctx, SLIDE_LIVE).is_some_and(|pass| pass != root_pass(ctx)) { - let owner = pstate::>(ctx, SLIDE_OWNER); - let ours = match (owner, slide_interaction(app)) { - (Some((uid, snapshot)), Some((open, now))) => uid == open && snapshot.ptr_eq(&now), + let ours = match (pstate::(ctx, SLIDE_OWNER), slide_interaction(app)) { + (SlideHold::Live(owner), Some(now)) => same_slide(&owner, &now), _ => false, }; if ours { @@ -1571,7 +1634,7 @@ pub(crate) fn end_stale_slide(app: &mut VectorcraftApp, ctx: &egui::Context) { app.sync_views(); } set_pstate(ctx, SLIDE_LIVE, None::); - set_pstate(ctx, SLIDE_OWNER, None::); + set_pstate(ctx, SLIDE_OWNER, SlideHold::Idle); } } @@ -1621,7 +1684,10 @@ fn param_slider_edit( // panel keeps both in view. let room = ui.available_width() - NUMBER_W - 2.0 * ui.spacing().item_spacing.x; let width = room.clamp(SLIDER_MIN_W, crate::dialogs::PARAM_SLIDER_WIDTH); - let (new, resp) = crate::dialogs::plugin_slider(ui, ("fx-slider", id), &p.spec, &cur, range, p.ui.step, width); + // The slider is a widget of its own for each document and selection, so a drag on it ends when + // they change and sends no more values: the objects the drag began on keep what it previewed + // ([`end_stale_slide`]), and the others stay as they are. + let (new, resp) = crate::dialogs::plugin_slider(ui, ("fx-slider", id, target), &p.spec, &cur, range, p.ui.step, width); let edit = if resp.drag_stopped() { // The value the drag ended on, kept even when its last preview waited. new.or(std::mem::take(&mut slide).value).map(|value| (value, widgets::Live::Released)) diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 28945cf076..df827eba40 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -659,6 +659,162 @@ fn a_plug_in_slider_drag_s_value_stays_with_its_drag() { app.run("plugin.remove", json!({"id": "test.ui.slideselection"})).unwrap(); } +/// A drag on a plug-in slider ends when another object with the same effect is selected while the +/// button is down: the object the drag began on keeps what the drag previewed, as one undo step, and +/// the other object stays selected and unchanged, also when the button comes up in the same pass. +/// A drag also leaves alone an interaction that it did not begin: one that replaced its own while +/// its row stays in view, and one that was open before it began. +#[test] +fn a_plug_in_slider_drag_ends_on_another_object_and_leaves_other_interactions_alone() { + use egui::accesskit::Role; + use vectorcraft_plugins::wat as tpl; + let params = r#"{"amount":{"type":"number","min":0,"max":100,"default":10,"label":"Amount","widget":"slider"}}"#; + let src = tpl::module(&tpl::manifest("test.ui.slideswitch", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let add = |app: &mut VectorcraftApp, x: f64| { + let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.slideswitch"})).unwrap(); + id + }; + let (a, b) = (add(&mut app, 0.0), add(&mut app, 40.0)); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let amount = + |app: &VectorcraftApp, id: u64| app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["amount"].as_f64(); + let slider = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)]| { + nodes.iter().find(|(_, n)| n.role() == Role::Slider).and_then(|(_, n)| n.bounds()) + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let open_preview = |app: &VectorcraftApp| app.session.doc().unwrap().interaction.as_ref().map(|it| it.preview.is_some()); + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let rail = slider(&frame(&mut app, vec![])).expect("the slider shows"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + // B is selected while the button is down, and the button comes up in the next pass. + let steps = undo(&app); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.4))]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.7))]); + let previewed = amount(&app, a); + assert_ne!(previewed, Some(10.0), "the drag previews"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.9)), button(at(0.9), false)]); + frame(&mut app, vec![]); + assert!(!app.session.in_interaction(), "the drag's interaction is still open"); + assert_eq!(amount(&app, a), previewed, "the drag did not keep only what it previewed"); + assert_eq!(amount(&app, b), Some(10.0), "the drag changed the other object"); + let sel = &app.session.doc().unwrap().selection; + assert!(sel.len() == 1 && sel.contains(NodeId(b)), "the other object is no longer the selection"); + assert_eq!(undo(&app), steps + 1, "the drag is one undo step"); + // A drag whose interaction another one replaced, of the same name, while its row stays in view. + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let before = amount(&app, a); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.5))]); + assert_eq!(open_preview(&app), Some(true), "the drag previews"); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Effect Options").unwrap(); + for i in 1..=12 { + frame(&mut app, vec![egui::Event::PointerMoved(at(0.5 + 0.03 * i as f64))]); + } + frame(&mut app, vec![button(at(0.9), false)]); + frame(&mut app, vec![]); + assert_eq!(open_preview(&app), Some(false), "the drag previewed in, or ended, the interaction that replaced it"); + assert_eq!(amount(&app, a), before, "the drag changed the object"); + app.session.cancel_interaction().unwrap(); + // A drag that begins while another interaction is open. + app.session.begin_interaction("Move").unwrap(); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + for i in 1..=12 { + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2 + 0.05 * i as f64))]); + } + frame(&mut app, vec![button(at(0.8), false)]); + frame(&mut app, vec![]); + assert_eq!(open_preview(&app), Some(false), "the drag previewed in, or ended, the interaction open before it"); + assert_eq!(amount(&app, a), before, "the drag changed the object"); + app.session.cancel_interaction().unwrap(); + // A drag after them previews and keeps its value again. + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.6))]); + frame(&mut app, vec![button(at(0.6), false)]); + frame(&mut app, vec![]); + assert!(!app.session.in_interaction(), "the drag's interaction is still open"); + assert_ne!(amount(&app, a), before, "the drag kept nothing"); + app.run("plugin.remove", json!({"id": "test.ui.slideswitch"})).unwrap(); +} + +/// A drag on a plug-in slider keeps what it previewed as one undo step in its own document when +/// another document becomes active while the button is down (as the keyboard switches documents). +#[test] +fn a_plug_in_slider_drag_keeps_its_preview_when_another_document_becomes_active() { + use egui::accesskit::Role; + use vectorcraft_plugins::wat as tpl; + let params = r#"{"amount":{"type":"number","min":0,"max":100,"default":10,"label":"Amount","widget":"slider"}}"#; + let src = tpl::module(&tpl::manifest("test.ui.slidedoc", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert!(app.session.set_active(0)); + let a = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.slidedoc"})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let amount = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(NodeId(a)).unwrap().appearance.effects[0].params["amount"].as_f64(); + let slider = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)]| { + nodes.iter().find(|(_, n)| n.role() == Role::Slider).and_then(|(_, n)| n.bounds()) + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![]); + let rail = slider(&frame(&mut app, vec![])).expect("the slider shows"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + let steps = app.session.doc().unwrap().history.undo.len(); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.6))]); + let previewed = amount(&app); + assert_ne!(previewed, Some(10.0), "the drag previews"); + assert!(app.session.set_active(1)); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.8))]); + frame(&mut app, vec![button(at(0.8), false)]); + assert!(!app.session.in_interaction(), "the other document has an interaction open"); + assert!(app.session.set_active(0)); + assert!(!app.session.in_interaction(), "the drag's interaction is still open"); + assert_eq!(amount(&app), previewed, "the drag did not keep its preview"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the drag is not one undo step"); + app.run("plugin.remove", json!({"id": "test.ui.slidedoc"})).unwrap(); +} + /// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does. #[test] fn the_effect_editor_lists_a_loaded_glass_texture() {