diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..7e7a3f9328 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -654,6 +654,7 @@ impl VectorcraftApp { crate::toasts::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); + crate::panels::appearance::end_stale_slide(self, &ctx); if self.custom_titlebar { titlebar::resize_zones(ui); } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 8976502aa4..5287aa0f4d 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -16,7 +16,7 @@ //! fills/strokes for Duplicate and Delete. Delete on a selected Opacity row sets it back to //! Default (100%, Normal). -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, OnceLock, Weak}; use egui::{Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -555,6 +555,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // An empty spacer row at the end of the list. ui.allocate_exact_size(vec2(ui.available_width(), 10.0), Sense::hover()); }); + end_stale_slide(app, ui.ctx()); bottom(app, ui, node.as_deref(), sel); delete_key(app, ui); // A row's popup, beside the panel (in the same window when the panel floats). @@ -1378,6 +1379,8 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let params = editor_params(e); let mut change: Option<(String, Value)> = None; let mut slid: Option<(String, Value, widgets::Live)> = None; + // The objects a slider drag edits: the editor shows a drag's value for these alone. + let target = app.session.active().map(|d| (d.uid, d.selection.subjects().to_vec())); let mut edit = false; let built_in = built_in_effect(&e.id); // A plug-in effect's parameters are labelled, measured and shown as its manifest says. @@ -1457,7 +1460,7 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let dragged; let v = match manifest.and_then(|m| m.param(key)).and_then(|p| Some((p, p.ui.slider_range(&p.spec)?))) { Some((p, range)) => { - let (shown, edit) = param_slider_edit(ui, (item, k, key.as_str()), p, v, range); + let (shown, edit) = param_slider_edit(ui, (item, k, key.as_str()), &target, p, v, range); slid = edit.map(|(value, phase)| (key.clone(), value, phase)).or(slid.take()); dragged = shown; &dragged @@ -1513,7 +1516,9 @@ 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, "Effect Options", "effect.setParams", p, phase); + 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); } if edit { app.run("effect.dialog", aligned(app, json!({"effect": e.id, "index": k, "item": item}))).ok(); @@ -1526,28 +1531,91 @@ const NUMBER_W: f32 = 70.0; /// The narrowest a plug-in parameter's slider gets in [`effect_editor`]. const SLIDER_MIN_W: f32 = 24.0; +/// The UI pass that last drew a drag on a plug-in parameter's slider in [`effect_editor`] that has +/// not ended with a value to keep ([`end_stale_slide`]). +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`]). +const SLIDE_OWNER: &str = "ap-fx-slide-owner"; + +/// The undo step a drag on a plug-in parameter's slider in [`effect_editor`] is kept as. +const SLIDE_LABEL: &str = "Effect Options"; + +/// An interaction: its document's uid and the selection snapshot it previews from, which each +/// interaction makes anew when it begins and keeps while it lasts. +type SlideOwner = (u64, Weak); + +/// The interaction open in the active document, when it is one a plug-in parameter's slider starts. +fn slide_interaction(app: &VectorcraftApp) -> Option { + let d = app.session.active()?; + d.interaction.as_ref().filter(|it| it.label == SLIDE_LABEL).map(|it| (d.uid, Arc::downgrade(&it.selection))) +} + +/// 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 +/// and the interaction ends. Any other interaction is left alone. The panel runs this after its +/// 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), + _ => false, + }; + if ours { + if let Err(e) = app.session.commit_interaction() { + app.status(e.to_string()); + } + app.sync_views(); + } + set_pstate(ctx, SLIDE_LIVE, None::); + set_pstate(ctx, SLIDE_OWNER, None::); + } +} + +/// The main window's pass in progress. A floating window draws inside it and counts its own +/// passes, so the slider's marks use this one wherever the panel draws. +fn root_pass(ctx: &egui::Context) -> u64 { + ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT) +} + /// What a drag on the slider of a plug-in effect's parameter in [`effect_editor`] keeps between -/// frames: the value it reached, and when it last previewed. +/// frames: the value it reached, and when it last previewed, for the objects (document and +/// selection) it edits, as of the UI pass that last drew it. #[derive(Clone, Debug, Default)] struct ParamSlide { value: Option, preview: crate::dialogs::SlidePreview, + target: Option<(u64, Vec)>, + pass: u64, } /// The slider of plug-in parameter `p` with value `v`, which asks for one, over `range`, in the row -/// `id` (appearance item, effect index and parameter name) → the value the row's number shows (a -/// drag's in progress, else `v`) and the edit to run with its phase ([`super::live_run`]): a click -/// or key as one undo step, and a drag previewed on the canvas about ten times a second -/// ([`crate::dialogs::SlidePreview`]) and kept as one undo step when it ends. +/// `id` (appearance item, effect index and parameter name) of the objects `target` (document and +/// selection) → the value the row's number shows (a drag's in progress, else `v`) and the edit to +/// run with its phase ([`super::live_run`]): a click or key as one undo step, and a drag previewed +/// on the canvas about ten times a second ([`crate::dialogs::SlidePreview`]) and kept as one undo +/// step when it ends. A drag's value is dropped when the selection or the document changes, or +/// after a pass that did not draw the row, so it never shows on or goes to other objects; a drag in +/// progress is noted under [`SLIDE_LIVE`] until it ends with a value to keep. fn param_slider_edit( ui: &mut Ui, id: (Option, usize, &str), + target: &Option<(u64, Vec)>, p: &vectorcraft_plugins::Param, v: &Value, range: std::ops::RangeInclusive, ) -> (Value, Option<(Value, widgets::Live)>) { let memory = egui::Id::unique(("fx-slide", id)); + let pass = root_pass(ui.ctx()); let mut slide: ParamSlide = ui.data(|d| d.get_temp(memory)).unwrap_or_default(); + if slide.target != *target || slide.pass.saturating_add(1) < pass { + slide = ParamSlide::default(); + } + slide.target.clone_from(target); + slide.pass = pass; let cur = slide.value.clone().unwrap_or_else(|| v.clone()); // The slider takes the room the row has left after the number field after it, so a narrow // panel keeps both in view. @@ -1565,6 +1633,11 @@ fn param_slider_edit( } else { new.map(|value| (value, widgets::Live::Released)) }; + if matches!(edit, Some((_, widgets::Live::Released))) { + set_pstate(ui.ctx(), SLIDE_LIVE, None::); + } else if resp.dragged() { + set_pstate(ui.ctx(), SLIDE_LIVE, Some(pass)); + } let shown = slide.value.clone().unwrap_or(cur); ui.data_mut(|d| { if slide.value.is_some() { diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 8efe31adfb..28945cf076 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -528,10 +528,18 @@ fn a_plug_in_slider_in_the_editor_previews_a_drag_and_keeps_it_as_one_step() { } } assert!(seen.len() > 2 && seen.len() < 15, "the canvas showed {} values in 30 frames: {seen:?}", seen.len()); - frame(&mut app, vec![button(at(0.85), false)]); + // One more move, too soon after the last preview to preview, then the release: the drag keeps + // the value it ended on, which the canvas had not shown yet. + let nodes = frame(&mut app, vec![egui::Event::PointerMoved(at(0.95))]); + let ended = nodes + .iter() + .find(|(_, n)| n.role() == Role::Slider && n.labelled_by().iter().any(|l| label_of(l).starts_with("Amount"))) + .and_then(|(_, n)| n.numeric_value()) + .expect("Amount's slider shows the value the drag reached"); + assert_ne!(params(&app)["amount"].as_f64(), Some(ended), "the last move previewed at once"); + frame(&mut app, vec![button(at(0.95), false)]); frame(&mut app, vec![]); - let kept = params(&app)["amount"].as_f64().unwrap(); - assert!(kept > 70.0 && kept <= 100.0, "the value the drag ended on: {kept}"); + assert_eq!(params(&app)["amount"].as_f64(), Some(ended), "the value the drag ended on"); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "the drag is one undo step"); assert!(!app.session.in_interaction(), "the drag's interaction ended"); // Count's slider: focused, an arrow moves it by its step of 2, as one more undo step. @@ -553,6 +561,104 @@ fn a_plug_in_slider_in_the_editor_previews_a_drag_and_keeps_it_as_one_step() { app.run("plugin.remove", json!({"id": "test.ui.inlineslider"})).unwrap(); } +/// A drag on a plug-in slider whose end the editor did not see, because the selection changed +/// while the button was down, keeps what it previewed as its undo step, ends its interaction and +/// leaves no value behind: the editor then shows each object's own value, for another object with +/// the same effect and for the object the drag started on. +#[test] +fn a_plug_in_slider_drag_s_value_stays_with_its_drag() { + 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.slideselection", "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.slideselection"})).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)| Some((n.numeric_value()?, n.bounds()?))) + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for (back, name) in [(a, "the object the drag started on"), (b, "another object")] { + 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); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + // The first move previews at once; the next comes too soon and waits. + frame(&mut app, vec![egui::Event::PointerMoved(at(0.4))]); + let (reached, _) = slider(&frame(&mut app, vec![egui::Event::PointerMoved(at(0.7))])).expect("the slider shows"); + let previewed = amount(&app, a); + assert_ne!(previewed, Some(reached), "the second move previewed at once"); + assert!(app.session.in_interaction(), "the drag previews"); + // With the button still down, nothing is selected, and the button comes up off the editor: + // the drag keeps what it previewed, and its interaction ends. + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![button(at(0.7), false)]); + assert!(!app.session.in_interaction(), "{name}: the drag's interaction is still open"); + assert_eq!(amount(&app, a), previewed, "{name}: the drag did not keep its preview"); + app.run("select.set", json!({"ids": [back]})).unwrap(); + frame(&mut app, vec![]); + let (shown, _) = slider(&frame(&mut app, vec![])).expect("the slider shows"); + assert_eq!(Some(shown), amount(&app, back), "{name} shows the drag's value"); + } + // A drag whose interaction another one replaced, of the same name on the same document, leaves + // that one open when its row goes. + 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); + 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!(app.session.in_interaction(), "the drag previews"); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Effect Options").unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![button(at(0.5), false)]); + assert!(app.session.in_interaction(), "the other interaction was ended"); + app.session.cancel_interaction().unwrap(); + // A drag whose panel closes keeps what it previewed at the end of the first pass that does not + // draw the panel, as the app checks after its panels. + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + 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, a); + assert!(app.session.in_interaction(), "the drag previews"); + for events in [vec![], vec![button(at(0.6), false)]] { + time += 1.0 / 60.0; + let input = egui::RawInput { events, time: Some(time), ..Default::default() }; + let _ = ctx.run_ui(input, |ui| crate::panels::appearance::end_stale_slide(&mut app, ui.ctx())); + assert!(!app.session.in_interaction(), "the drag's interaction is still open after the panel closed"); + } + assert_eq!(amount(&app, a), previewed, "the drag did not keep its preview"); + app.run("plugin.remove", json!({"id": "test.ui.slideselection"})).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() {