Keep standalone effect edits in their opening drawing

This commit is contained in:
dotCooCoo committed 2026-11-26 18:07:21 -08:00
1 parent 0aea8fed95
commit 55fa366081
1 file changed
+243 -11
+243 -11
View File
@@ -10,7 +10,7 @@
//! effect's defaults for the rest.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::{Arc, Weak};
use craft::host::{PickRequest, Picked};
use craft::ui::contract::Bind;
@@ -18,6 +18,7 @@ use craft::ui::dialog::{DialogId, PromptChoice, StandardPrompt};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamResult};
use craft::ui::runtime::memory::{Lifetime, SaveKey};
use serde_json::{Map, Value, json};
use vectorcraft_doc::Selection;
use super::effect_params::{EffectCx, effect_params, heading, label};
use super::form;
@@ -51,6 +52,8 @@ pub(crate) struct Open {
pub id: DialogId,
/// Identity of this opening, since effect dialogs reuse the same dialog ID.
opening: Arc<()>,
/// The drawing and its file generation when the dialog was opened.
source: Option<(u64, u64)>,
/// The item the effect goes to, resolved.
target: Value,
/// The parameters that find the applied effect (`item`, `aligned`).
@@ -66,12 +69,65 @@ pub(crate) struct Open {
opened: Map<String, Value>,
/// The live preview OK keeps and Cancel rolls back.
pub preview: LivePreview,
preview_owner: Option<PreviewOwner>,
/// What the rows need from the app.
pub cx: EffectCx,
/// Whether the Edit or Add New question is still open.
asking: bool,
}
/// The interaction and preview last written by this opening.
struct PreviewOwner {
selection: Weak<Selection>,
command: Option<(String, Value)>,
}
fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> {
app.session.active().map(|doc| (doc.uid, doc.reverts))
}
impl Open {
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.source == active_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(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result<bool, String> {
if self.owns_preview(app) {
return Ok(true);
}
// A tab switch normally rolls the preview back. A new edit can now hold the interaction.
self.preview = LivePreview::default();
self.preview_owner = None;
if app.session.in_interaction() {
app.keep_typing()?;
}
Ok(!app.session.in_interaction())
}
}
/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog.
pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) {
let Some(open) = app.effect_dialogs.effect.as_ref() else { return };
@@ -111,6 +167,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let mut open = Open {
id: DialogId::NULL,
opening: Arc::new(()),
source: active_drawing(app),
target: target.clone(),
edit_target,
index: None,
@@ -118,6 +175,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
aligned: p.get("aligned").and_then(Value::as_bool) == Some(true),
opened: Map::new(),
preview: LivePreview::default(),
preview_owner: None,
cx: EffectCx::new(app, id, false),
asking: false,
};
@@ -149,6 +207,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) -
let open = Open {
id: DialogId::NULL,
opening: Arc::new(()),
source: active_drawing(app),
target: Value::Null,
edit_target: json!({}),
index: None,
@@ -156,6 +215,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) -
aligned: false,
opened: Map::new(),
preview: LivePreview::default(),
preview_owner: None,
cx: EffectCx::new(app, effect, false),
asking: false,
};
@@ -248,6 +308,9 @@ fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result<Value, String> {
.button(PromptChoice::Alternate, tl!("Add New").to_string())
.button(PromptChoice::Cancel, tl!("Cancel").to_string());
let Some(dialogs) = app.dialogs() else { return Err("no window".into()) };
if let Some(old) = app.effect_dialogs.effect.take() {
old.cancel_preview(app);
}
open.id = dialogs.with(|h| h.open(prompt));
open.asking = true;
app.effect_dialogs.effect = Some(open);
@@ -259,7 +322,7 @@ fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result<Value, String> {
fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>, seed: Map<String, Value>) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
if let Some(old) = app.effect_dialogs.effect.take() {
old.preview.cancel(app);
old.cancel_preview(app);
}
let id = open.cx.id.clone();
let fresh = open.index.is_none();
@@ -296,9 +359,12 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>
};
if warp_new { dialog.remember(WARP_KEY).remember_for(Lifetime::Run) } else { dialog }
});
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.effect_dialogs.effect.take() {
open.preview.cancel(app);
let cancelled = Arc::clone(&open.opening);
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if app.effect_dialogs.effect.as_ref().is_some_and(|open| Arc::ptr_eq(&cancelled, &open.opening))
&& let Some(open) = app.effect_dialogs.effect.take()
{
open.cancel_preview(app);
}
});
let options = HeldOptions { cancel: Some(cancel), ..Default::default() };
@@ -313,12 +379,22 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>
/// with the reason, and the record with a fresh preview.
fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Result<(), String> {
let Some(mut open) = app.effect_dialogs.effect.take() else { return Ok(()) };
if let Err(why) = open.check_source(app) {
app.effect_dialogs.effect = Some(open);
return Err(why);
}
let (cmd, params) = command(&open, &result.fields);
// An edit that sends nothing changes nothing and records no step: the preview rolls back.
if cmd == "effect.setParams" && params.get("warpStyle").is_none() && params["params"].as_object().is_some_and(Map::is_empty) {
open.preview.cancel(app);
open.cancel_preview(app);
return Ok(());
}
let ready =
open.ready_to_edit(app).and_then(|ready| if ready { Ok(()) } else { Err(tl!("Finish the current edit before applying the effect").into()) });
if let Err(why) = ready {
app.effect_dialogs.effect = Some(open);
return Err(why);
}
let preview = std::mem::take(&mut open.preview);
match preview.commit(app, cmd, params.clone()) {
Ok(_) => {
@@ -333,6 +409,7 @@ fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -
Ok(())
}
Err(e) => {
open.preview_owner = None;
app.effect_dialogs.effect = Some(open);
Err(e)
}
@@ -415,6 +492,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
fn answer(app: &mut VectorcraftApp, mut open: Open) -> Option<Open> {
let result = app.dialogs()?.with(|h| h.take_by_id::<StandardPrompt>(open.id))?;
let choice = result.ok().map_or(PromptChoice::Cancel, |answer| answer.choice);
if choice != PromptChoice::Cancel
&& let Err(why) = open.check_source(app)
{
app.status(why);
return None;
}
let id = open.cx.id.clone();
let launched = match (choice, open.index) {
(PromptChoice::Proceed, Some(k)) => {
@@ -455,6 +538,10 @@ fn show_stored(cx: &EffectCx, d: &mut HostedParamDialog) {
/// One frame of the open dialog: the preview of its values, and the requests its rows filed.
fn drive(app: &mut VectorcraftApp, mut open: Open) {
let Some(dialogs) = app.dialogs() else { return };
if open.check_source(app).is_err() {
app.effect_dialogs.effect = Some(open);
return;
}
let Some((fields, previewing, path)) = dialogs.with(|h| {
h.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| {
show_stored(&open.cx, d);
@@ -464,10 +551,26 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) {
app.effect_dialogs.effect = Some(open);
return;
};
let (cmd, params) = command(&open, &fields);
let english = vectorcraft_effects::effect_info(&open.cx.id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_default();
// `run` reports a failed preview itself.
let _ = open.preview.run(app, previewing, &english, cmd, &params);
if previewing || open.owns_preview(app) {
match open.ready_to_edit(app) {
Ok(true) => {
let (cmd, params) = command(&open, &fields);
let english = vectorcraft_effects::effect_info(&open.cx.id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_default();
let ran = open.preview.run(app, previewing, &english, cmd, &params);
if !previewing {
open.preview_owner = None;
} else if ran.is_some() {
open.preview_owner = app
.session
.active()
.and_then(|doc| doc.interaction.as_ref())
.map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), command: interaction.preview.clone() });
}
}
Ok(false) => {}
Err(why) => app.status(why),
}
}
if let Some(request) = path {
let (id, key) = (open.id, request.key);
let opening = Arc::clone(&open.opening);
@@ -475,8 +578,11 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) {
app.effect_dialogs.effect.as_ref().is_some_and(|current| current.id == id && Arc::ptr_eq(&opening, &current.opening))
};
let same_opening = is_current.clone();
let source = open.source;
let is_live = move |app: &VectorcraftApp| {
same_opening(app) && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
same_opening(app)
&& app.session.documents().iter().any(|doc| Some((doc.uid, doc.reverts)) == source)
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
};
pick_texture_while(app, Owner::Document, is_live, move |app, path, fields| {
if !is_current(app) {
@@ -879,4 +985,130 @@ mod tests {
ok(&mut app);
assert_eq!(params(&app, node)["centerX"].as_f64(), Some(0.5));
}
fn standalone_effect_source(app: &mut VectorcraftApp) {
app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap();
set(app, "size", json!(16.0));
set(app, "preview", json!(true));
}
fn effect_frame(app: &mut VectorcraftApp) {
let ctx = app.ui_ctx.clone().unwrap();
super::super::host::pump(app, &ctx);
}
#[test]
fn standalone_effect_preview_stays_with_the_opening_drawing() {
let mut app = app();
let original = rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
assert_eq!(params(&app, original)["size"], 16.0);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
rect(&mut app, 80);
let other = app.session.active().unwrap().doc.clone();
effect_frame(&mut app);
assert!(app.session.active().unwrap().doc == other, "effect preview reached the other drawing");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
effect_frame(&mut app);
assert_eq!(params(&app, original)["size"], 16.0, "preview resumes on the opening drawing");
}
#[test]
fn standalone_effect_ok_can_be_retried_on_the_opening_drawing() {
let mut app = app();
let original = rect(&mut app, 10);
standalone_effect_source(&mut app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
rect(&mut app, 80);
let before = app.session.active().unwrap().doc.clone();
let history = steps(&app);
ok(&mut app);
assert!(app.session.active().unwrap().doc == before, "effect OK reached the other drawing");
assert_eq!(steps(&app), history);
app.run("document.activate", json!({"index": 0})).unwrap();
let history = steps(&app);
ok(&mut app);
assert_eq!(params(&app, original)["size"], 16.0);
assert_eq!(steps(&app), history + 1);
}
#[test]
fn standalone_effect_cancel_preserves_the_other_drawings_edit() {
let mut app = app();
rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
rect(&mut app, 80);
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, id) = (app.ui_ctx.clone().unwrap(), id(&app));
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
effect_frame(&mut app);
assert!(app.session.in_interaction(), "effect Cancel ended the other drawing's edit");
assert!(app.session.active().unwrap().doc == before);
}
#[test]
fn standalone_effect_cancel_preserves_a_replaced_preview_in_the_same_drawing() {
let mut app = app();
rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let (ctx, id) = (app.ui_ctx.clone().unwrap(), id(&app));
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
effect_frame(&mut app);
assert!(app.session.in_interaction(), "effect Cancel ended a different preview on the same interaction");
assert!(app.session.active().unwrap().doc == before);
}
#[test]
fn standalone_effect_replacement_keeps_its_own_preview() {
let mut app = app();
let node = rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
app.run("effect.dialog", json!({"effect": "distort.zigZag"})).unwrap();
set(&mut app, "size", json!(12.0));
set(&mut app, "preview", json!(true));
effect_frame(&mut app);
assert!(app.effect_dialogs.effect.is_some(), "a replaced dialog's Cancel removed the new opening");
assert_eq!(params(&app, node)["size"], 12.0);
ok(&mut app);
assert_eq!(params(&app, node)["size"], 12.0);
}
#[test]
fn standalone_effect_ok_cannot_change_the_reloaded_drawing() {
let mut app = app();
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("effect-opening-revert");
let path = folder.join("drawing.vectorcraft");
let original = rect(&mut app, 10);
app.run("file.saveAs", json!({"path": path})).unwrap();
rect(&mut app, 80);
app.run("select.set", json!({"ids": [original]})).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
standalone_effect_source(&mut 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 before = app.session.active().unwrap().doc.clone();
let history = steps(&app);
ok(&mut app);
assert!(app.session.active().unwrap().doc == before, "effect OK reached the reloaded drawing");
assert_eq!(steps(&app), history);
standalone_effect_source(&mut app);
ok(&mut app);
assert_eq!(params(&app, original)["size"], 16.0, "a fresh opening applies to the restored drawing");
}
}