From 02c80000d3cd8512d725170cc4459a53ec425df0 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 26 Nov 2026 19:55:29 -0800 Subject: [PATCH] Keep 3D effect previews in their opening drawing (#9651) * Keep 3D effect previews in their opening drawing * Preserve read-only Map Art surface updates --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/dialogs/revolve_gizmo.rs | 4 +- crates/ui-egui/src/dialogs/three_d.rs | 328 ++++++++++++++++++-- 3 files changed, 305 insertions(+), 29 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d13d79e4b9..cb9ab68bd1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -74,7 +74,7 @@ pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { /// Whether a 3D effect is edited in its dialog: the selection's marks and widgets give way to the dialog's gizmo. pub(crate) fn revolve_editing(app: &VectorcraftApp) -> bool { - app.three_d_dialog.is_some() + crate::dialogs::three_d::editing_current_drawing(app) } /// The arrows the canvas takes with nothing in the window focused, as it takes every arrow while it has the focus: diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 985b13174a..32e66cb6f8 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -819,7 +819,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { three_d::with_fields(app, |dialog| write(dialog, before, landed)); } } - super::three_d_classic::show_outline(app, ui, space); + if three_d::editing_current_drawing(app) { + super::three_d_classic::show_outline(app, ui, space); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 1bf8a87680..6d4effc8e0 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -1,7 +1,7 @@ //! The host of the 3D effects' dialog: opens it through the held-dialog mechanism, keeps the app facts its rows read, //! runs the live preview, and refuses values the effect cannot draw. The rows are built by [`super::revolve`]. -use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard}; +use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, Weak}; use craft::ui::contract::Bind; use craft::ui::contract::overlay::{FloatPlace, Place as OverlayPlace}; @@ -9,7 +9,7 @@ use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog, ParamLayout, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value}; -use vectorcraft_doc::{Document, Unit}; +use vectorcraft_doc::{Document, Selection, Unit}; use vectorcraft_effects::{MAP_ART, MAP_INVISIBLE, MAP_SHADE, MapSurface, is_classic_three_d}; use vectorcraft_engine::EngineError; @@ -26,6 +26,7 @@ const MAP_ART_PAGE: &str = "mapArt"; /// The open 3D dialog and what its pump keeps between passes. pub(crate) struct Session { id: DialogId, + source: Option<(u64, u64)>, effect: String, label: String, // PLAN: the contract has `item: Option`; the command needs `null` (the object's effects) apart from an omitted item. @@ -34,12 +35,19 @@ pub(crate) struct Session { edit_target: Value, aligned: bool, preview: LivePreview, + preview_owner: Option, /// The command params of the last Preview-off try; `None` while Preview is on, so turning it off tries again. tried: Option, /// What the rows read, pushed each pump. pub(crate) data: Arc>, } +/// The interaction and preview last written by the 3D dialog. +struct PreviewOwner { + selection: Weak, + command: Option<(String, Value)>, +} + /// The app facts the 3D rows read. #[derive(Clone)] pub(crate) struct Data { @@ -87,6 +95,67 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map bool { + self.source == active_drawing(app) + } + + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let active = active_drawing(app); + if active == self.source { + Ok(()) + } else if active.map(|(id, _)| id) == self.source.map(|(id, _)| id) { + Err(tl!("The document was reverted. Reopen this dialog to continue.").into()) + } else { + Err(tl!("Return to the original drawing to apply the effect").into()) + } + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + self.is_current_drawing(app) + && self.preview_owner.as_ref().is_some_and(|owner| { + app.session.active().and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection)) + && owner.command == interaction.preview + }) + }) + } + + fn cancel_preview(&mut self, app: &mut VectorcraftApp) { + let owned = self.owns_preview(app); + let preview = std::mem::take(&mut self.preview); + self.preview_owner = None; + if owned { + preview.cancel(app); + } + } + + fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result { + if self.owns_preview(app) { + return Ok(true); + } + self.preview = LivePreview::default(); + self.preview_owner = None; + if app.session.in_interaction() { + app.keep_typing()?; + } + Ok(!app.session.in_interaction()) + } + + fn run_preview(&mut self, app: &mut VectorcraftApp, cmd: &str, params: &Value) -> Option> { + match self.ready_to_edit(app) { + Ok(true) => {} + Ok(false) => return None, + Err(why) => return Some(Err(why)), + } + let verdict = self.preview.run(app, true, &self.label, cmd, params)?.map(|_| ()); + self.preview_owner = app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), command: interaction.preview.clone() }); + Some(verdict) + } + /// The command OK runs, and the params it takes. fn command(&self, params: &Map) -> (&'static str, Value) { super::effect::command_for(&self.effect, self.item.as_ref(), self.index, &self.edit_target, self.aligned, params.clone(), None) @@ -105,6 +174,10 @@ impl Session { } } +fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|doc| (doc.uid, doc.reverts)) +} + /// Opens the dialog for the record `effect::open` resolved: `effect`, `item`, `index`, `aligned`, `editTarget` and the /// `params` to start from. pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result { @@ -112,6 +185,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result let info = vectorcraft_effects::effect_info(&effect).ok_or_else(|| format!("unknown effect `{effect}`"))?; let label = info.label.trim_end_matches('…').to_owned(); let params = p.get("params").and_then(Value::as_object).cloned().or_else(|| info.defaults.as_object().cloned()).unwrap_or_default(); + let source = active_drawing(app); let shared = Arc::new(RwLock::new(data(app, Some(&effect), ¶ms))); let mut fields = fields_of(&revolve::params(&read(&shared), &DialogFields::new(), Place::Dialog), ¶ms); fields.set("__effect", effect.clone()); @@ -146,13 +220,15 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result None => dialog, } }); - if let Some(old) = app.three_d_dialog.take() { - old.preview.cancel(app); - } - let options = HeldOptions { cancel: Some(Box::new(cancel)), ..HeldOptions::default() }; + let cancelled = Arc::clone(&shared); + let options = HeldOptions { cancel: Some(Box::new(move |app| cancel(app, &cancelled))), ..HeldOptions::default() }; let id = open_held_with(app, dialog, ok, options).ok_or("no window")?; + if let Some(mut old) = app.three_d_dialog.take() { + old.cancel_preview(app); + } app.three_d_dialog = Some(Session { id, + source, effect, label, item: p.get("item").cloned(), @@ -160,6 +236,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result edit_target: p.get("editTarget").cloned().unwrap_or(Value::Null), aligned: p.get("aligned").and_then(Value::as_bool) == Some(true), preview: LivePreview::default(), + preview_owner: None, tried: None, data: shared, }); @@ -169,6 +246,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result /// OK: the preview becomes one undo step. A refusal keeps the dialog, and the session, open. fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { let mut s = app.three_d_dialog.take().ok_or_else(|| "the 3D dialog is gone".to_string())?; + let ready = s + .check_source(app) + .and_then(|()| if s.ready_to_edit(app)? { Ok(()) } else { Err(tl!("Finish the current edit before applying the effect").into()) }); + if let Err(why) = ready { + app.three_d_dialog = Some(s); + return Err(why); + } let (cmd, p, _) = s.request(&answer.fields); match std::mem::take(&mut s.preview).commit(app, cmd, p.clone()) { Ok(_) => { @@ -179,6 +263,7 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { Ok(()) } Err(e) => { + s.preview_owner = None; app.three_d_dialog = Some(s); Err(e) } @@ -186,9 +271,11 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { } /// Cancel: the preview rolls back. -fn cancel(app: &mut VectorcraftApp) { - if let Some(s) = app.three_d_dialog.take() { - s.preview.cancel(app); +fn cancel(app: &mut VectorcraftApp, opening: &Arc>) { + if app.three_d_dialog.as_ref().is_some_and(|s| Arc::ptr_eq(opening, &s.data)) + && let Some(mut s) = app.three_d_dialog.take() + { + s.cancel_preview(app); } } @@ -197,10 +284,15 @@ fn dialog_of(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut HostedPa } fn peek(app: &VectorcraftApp, f: impl FnOnce(&HostedParamDialog) -> R) -> Option { - let id = app.three_d_dialog.as_ref()?.id; + let id = app.three_d_dialog.as_ref().filter(|s| s.is_current_drawing(app))?.id; app.dialogs()?.with(|h| h.get_by_id::(id).map(f)) } +/// Whether the active canvas should give its selection marks to the 3D dialog. +pub(crate) fn editing_current_drawing(app: &VectorcraftApp) -> bool { + app.three_d_dialog.as_ref().is_some_and(|s| s.is_current_drawing(app)) +} + /// Gives the gizmo and the outline the open dialog; `None` when there is none. pub(crate) fn with_fields(app: &mut VectorcraftApp, f: impl FnOnce(&mut HostedParamDialog) -> R) -> Option { let id = app.three_d_dialog.as_ref()?.id; @@ -265,6 +357,7 @@ fn surfaces(app: &mut VectorcraftApp, s: &Session, fields: &DialogFields, params /// refusal standing until the values change. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut s) = app.three_d_dialog.take() else { return }; + let current = s.is_current_drawing(app); // A dialog that closed is finished by the held drain (OK or Cancel), which owns the session's end. let Some((fields, previewing)) = dialog_of(app, s.id, |d| { match d.take_action().as_deref() { @@ -278,32 +371,213 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { return; }; let (cmd, p, params) = s.request(&fields); - let mut fresh = data(app, Some(&s.effect), ¶ms); + // Map Art keeps its read-only surface list current. While away, editable document data + // such as symbol names and artwork drop ownership still belongs to the opening drawing. + let mut fresh = if current { data(app, Some(&s.effect), ¶ms) } else { read(&s.data).clone() }; fresh.surfaces = surfaces(app, &s, &fields, ¶ms); *s.data.write().unwrap_or_else(PoisonError::into_inner) = fresh; - let mut verdict = s.preview.run(app, previewing, &s.label, cmd, &p).map(|r| r.map(|_| ())); - if previewing { + if !current { s.tried = None; - } else if app.session.in_interaction() && s.tried.as_ref() != Some(&p) { - // Changed values end the refusal of the values before them; they are tried once the other interaction ends. - verdict = Some(Ok(())); - } else if s.tried.as_ref() != Some(&p) { - // Waits for another interaction to end: trying inside it would replace its preview and cancel it. A failure - // to begin leaves no interaction: the try then reports it. - let _ = app.begin_interaction(&s.label); - verdict = Some(app.session.preview(cmd, &p).map(|_| ()).map_err(|e| match e { - EngineError::BadParams { msg, .. } => msg, - other => other.to_string(), - })); - // Only a try: without an interaction there is nothing to roll back. - let _ = app.session.cancel_interaction(); - s.tried = Some(p); + app.three_d_dialog = Some(s); + return; } + let verdict = if previewing { + s.tried = None; + s.run_preview(app, cmd, &p) + } else { + s.cancel_preview(app); + if s.tried.as_ref() == Some(&p) { + None + } else if app.session.in_interaction() { + // Clear the old refusal now and try again once the other interaction ends. + Some(Ok(())) + } else { + let tested = try_values(app, &s.label, cmd, &p); + s.tried = Some(p); + Some(tested) + } + }; if let Some(v) = verdict { dialog_of(app, s.id, |d| d.refuse(v.err().map(Label::from))); } app.three_d_dialog = Some(s); } +/// With Preview off, try changed values as a temporary interaction to expose engine refusals. +fn try_values(app: &mut VectorcraftApp, label: &str, cmd: &str, params: &Value) -> Result<(), String> { + app.begin_interaction(label)?; + let verdict = app.session.preview(cmd, params).map(|_| ()).map_err(|error| match error { + EngineError::BadParams { msg, .. } => msg, + other => other.to_string(), + }); + let _ = app.session.cancel_interaction(); + verdict +} + #[cfg(test)] pub(crate) mod tests_support; + +#[cfg(test)] +mod drawing_tests { + use craft::ui::dialog::StackDialog as _; + use serde_json::json; + use vectorcraft_doc::NodeId; + use vectorcraft_effects::EXTRUDE; + + use super::*; + + fn drawing() -> (VectorcraftApp, u64) { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let node = rectangle(&mut app, 10); + (app, node) + } + + fn rectangle(app: &mut VectorcraftApp, x: u32) -> u64 { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + } + + fn second_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 220, "height": 220})).unwrap(); + rectangle(app, 80) + } + + fn open_effect(app: &mut VectorcraftApp, preview: bool) { + app.run("effect.dialog", json!({"effect": EXTRUDE})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(app, |dialog| dialog.set_json_field(&ctx, "preview", json!(preview))).unwrap().unwrap(); + } + + fn applied(app: &VectorcraftApp, node: u64) -> Vec { + app.session.active().unwrap().doc.node(NodeId(node)).unwrap().appearance.effects.iter().map(|effect| effect.id.clone()).collect() + } + + fn frame(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + super::super::host::pump(app, &ctx); + } + + fn hold_ok(app: &VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.three_d_dialog.as_ref().unwrap().id; + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id))); + } + + #[test] + fn three_d_ownership_preview_resumes_only_in_the_opening_drawing() { + let (mut app, original) = drawing(); + open_effect(&mut app, true); + let first = app.session.active().unwrap().uid; + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + let other = second_drawing(&mut app); + frame(&mut app); + assert!(applied(&app, other).is_empty(), "3D preview reached the other drawing"); + assert!(!app.session.in_interaction()); + assert!(!gizmo_shown(&app)); + assert!(!crate::canvas::revolve_editing(&app)); + assert_eq!(read(&app.three_d_dialog.as_ref().unwrap().data).document_uid, Some(first)); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + assert!(gizmo_shown(&app)); + assert!(crate::canvas::revolve_editing(&app)); + } + + #[test] + fn three_d_ownership_ok_refuses_the_other_drawing_and_can_retry() { + let (mut app, original) = drawing(); + open_effect(&mut app, false); + hold_ok(&app); + let other = second_drawing(&mut app); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app); + assert!(applied(&app, other).is_empty(), "3D OK reached the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + app.run("document.activate", json!({"index": 0})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + } + + #[test] + fn three_d_ownership_cancel_leaves_the_other_drawings_preview_running() { + let (mut app, _) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.three_d_dialog.as_ref().unwrap().id; + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + frame(&mut app); + assert!(app.session.in_interaction(), "3D Cancel ended the other drawing's edit"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn three_d_ownership_preview_off_preserves_another_drawings_interaction() { + let (mut app, _) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + let other = second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(&mut app, |dialog| dialog.set_json_field(&ctx, "preview", json!(false))).unwrap().unwrap(); + frame(&mut app); + assert!(app.session.in_interaction()); + assert!(app.session.active().unwrap().doc == before); + assert!(applied(&app, other).is_empty()); + } + + #[test] + fn three_d_ownership_replacement_keeps_its_own_preview() { + let (mut app, original) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + app.run("effect.dialog", json!({"effect": vectorcraft_effects::REVOLVE})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(&mut app, |dialog| dialog.set_json_field(&ctx, "preview", json!(true))).unwrap().unwrap(); + frame(&mut app); + assert!(app.three_d_dialog.is_some(), "a replaced 3D dialog's Cancel removed the new opening"); + assert_eq!(applied(&app, original), [vectorcraft_effects::REVOLVE]); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [vectorcraft_effects::REVOLVE]); + } + + #[test] + fn three_d_ownership_ok_refuses_the_reloaded_drawing() { + let (mut app, original) = drawing(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let folder = vectorcraft_testkit::TempDir::new("three-d-opening-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rectangle(&mut app, 80); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + open_effect(&mut app, false); + hold_ok(&app); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reloaded = app.session.active().unwrap(); + assert_eq!(reloaded.uid, uid); + assert_ne!(reloaded.reverts, generation); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app); + assert!(applied(&app, original).is_empty(), "3D OK reached the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + open_effect(&mut app, false); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + } +}