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/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 0f61119fc8..9f810b6117 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -11,7 +11,7 @@ //! applies and makes objects). What only the art of symbol instances holds needs Object on. use craft::ui::contract::SaveKey; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::memory::Lifetime; use serde_json::{Value, json}; use vectorcraft_engine::cmd::expand::{DEFAULT_STEPS, MAX_STEPS}; @@ -22,6 +22,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "expand"; const CMD: &str = "object.expand"; +const OPENING_DRAWING: &str = "__openingDrawing"; /// Where the choices OK expanded with are kept for the rest of the app's run. const REMEMBER: SaveKey = SaveKey::new("vectorcraft.dialog.expand"); @@ -145,8 +146,11 @@ fn rows() -> Vec { /// every option on before that. fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result { let ctx = app.ui_ctx.as_ref().ok_or("no window")?; + let active = app.session.active().ok_or("no document open")?; + let mut fields = DialogFields::new(); + fields.set(OPENING_DRAWING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts}))); let rows = rows(); - Ok(HostedParamDialog::new(ctx, KIND, DialogFields::new(), move |fields| { + Ok(HostedParamDialog::new(ctx, KIND, fields, move |fields| { refresh(info, fields); ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run) })) @@ -154,10 +158,17 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result Result { - let document = app.session.active().ok_or("no document open")?.uid; - crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { - if app.session.active().is_none_or(|st| st.uid != document) { + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { + let Some(FieldValue::Json(opening)) = result.fields.get(OPENING_DRAWING) else { return Err(tl!("Return to the original drawing to expand the artwork").into()); + }; + let active = app + .session + .active() + .filter(|st| Some(st.uid) == opening["uid"].as_u64()) + .ok_or_else(|| tl!("Return to the original drawing to expand the artwork").to_owned())?; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); } ok(app, result) }) @@ -533,4 +544,33 @@ mod tests { app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); assert!(is_open(&app)); } + + #[test] + fn expand_approval_does_not_expand_artwork_restored_by_revert() { + let mut app = app(); + gradient_rectangle(&mut app); + let rectangle = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("expand-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [rectangle.0]})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().doc, restored); + + close(&app); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + ok_and_close(&mut app); + let st = app.session.active().unwrap(); + let art = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &art.kind else { panic!("expected a clip group") }; + assert!(matches!(children[1].kind, NodeKind::Mesh(_))); + } } diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 5580f9511c..39bbd6a984 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -55,7 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ); return Ok(Value::Null); }; - let document = st.uid; + let document = (st.uid, st.reverts); let p = std::path::Path::new(&path); let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); @@ -107,9 +107,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } } -fn require_package_document(app: &VectorcraftApp, document: u64) -> Result<(), String> { - if app.session.active().is_none_or(|st| st.uid != document) { +fn require_package_document(app: &VectorcraftApp, (document, reverts): (u64, u64)) -> Result<(), String> { + let Some(active) = app.session.active().filter(|st| st.uid == document) else { return Err(tl!("Package can only save and collect the document where it was opened.").to_owned()); + }; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } Ok(()) } @@ -160,7 +163,7 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result return r; } } - // A completed background job may have changed the active document while Package waited. + // A completed background job may have changed the active document or its loaded contents while Package waited. require_package_document(app, document)?; let package = app.session.prepare_package(¶ms).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?; let label = format!("Packaging {}", text("name")); 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/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index 23ed5cfa85..cb58f856a7 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -86,7 +86,7 @@ pub(crate) struct Strip { /// Which command the strip previews. pub kind: StripKind, /// The drawing whose selection and preview the strip uses. - document: Option, + document: Option<(u64, u64)>, /// The slider's value, 0 to 100. pub level: f64, /// The selection's document bounds when the strip opened, so the strip stays put while the @@ -102,7 +102,7 @@ pub(crate) struct Strip { impl Strip { fn in_source(&self, app: &VectorcraftApp) -> bool { - self.document == app.session.active().map(|doc| doc.uid) + self.document == app.session.active().map(|doc| (doc.uid, doc.reverts)) } fn cancel(self, app: &mut VectorcraftApp) { @@ -142,7 +142,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: StripKind) { } let strip = Strip { kind, - document: app.session.active().map(|doc| doc.uid), + document: app.session.active().map(|doc| (doc.uid, doc.reverts)), level: opening_level(app, kind), bounds: app.selection_bounds(), open: true, diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 8fd5193074..e9a2166fa7 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -293,3 +293,36 @@ fn simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path() assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len + 1); kept(&app, "the dialog"); } + +#[test] +fn path_sliders_close_when_file_revert_restores_the_artwork() { + for (kind, command) in + [(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")] + { + let mut app = app_with_dense_path(); + let id = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("path-slider-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 19]]})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 19]]})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + frame(&mut app, vec![]); + assert!(!simplify_slider::showing_of(&app, kind), "{command}"); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.active().unwrap().doc, restored); + + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 5dec578456..392e77a4ed 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -665,3 +665,31 @@ fn package_save_first_does_not_save_a_different_drawing() { crate::tests::picks::poll(&mut app, &ctx); assert_eq!(picker.requests().len(), 1, "approval in the opening drawing starts Save As"); } + +#[test] +fn held_package_approval_does_not_write_output_after_revert() { + let dir = Folder::new("package-revert"); + let mut app = saved(&dir); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.session.execute("prefs.set", &json!({"values": {"backgroundExport": false, "backgroundSave": false}})).unwrap(); + let before = std::fs::read(dir.path("card.vectorcraft")).unwrap(); + let out = dir.path("out"); + let output = std::path::Path::new(&out).join("card Folder"); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + package_dialog(&mut app, &out); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, package_id()))); + assert_eq!(held_state(&app), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!output.exists(), "the old approval writes no output"); + assert_eq!(std::fs::read(dir.path("card.vectorcraft")).unwrap(), before); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + close_all(&app); + package_dialog(&mut app, &out); + assert!(press_ok(&mut app)); + assert!(output.join("card.vectorcraft").exists()); +} 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]); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 62dce937d1..d339f895b9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -288,8 +288,8 @@ pub struct VectorcraftApp { pub(crate) three_d: panels::three_d::Model, /// The open export option dialogs and what runs after each. pub(crate) export_dialogs: dialogs::export_host::ExportDialogs, - /// The drawing the open Package dialog saves and collects. - pub(crate) package_document: Option, + /// The drawing and loaded contents the open Package dialog saves and collects. + pub(crate) package_document: Option<(u64, u64)>, /// Save for Web's renders and colour table. pub(crate) web_export: dialogs::save_for_web::WebExport, /// The Flattener Preview panel's model.