From 0ca2145429c829b5834786028c0b693b8cc88e36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:56:26 -0800 Subject: [PATCH] Plug-ins: a filter run is given the typing in progress, and a refused output keeps it in progress With Real-time Drawing off, typing in progress is kept as its own step before the run is prepared, in plugin.run, a plug-in command and the app's background start, so the plug-in is given the typed text. A run whose typing started after it was prepared, with its text still out of the document, is refused, and a background run that finishes then asks to be run again. Typing whose text is already in the document is kept only after every check that can refuse the output has passed, so a refused output leaves the document, the history and the typing in progress as they were. When keeping it changes the document, the output is applied to the document as kept. --- crates/engine/src/cmd/plugin.rs | 93 +++++++++++++++++++------ crates/engine/src/tests/plugins.rs | 67 ++++++++++++++++++ crates/ui-egui/src/plugin_runs.rs | 10 ++- crates/ui-egui/src/tests/plugin_runs.rs | 63 +++++++++++++++++ 4 files changed, 209 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 4d4929c910..f8240b08e6 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -394,29 +394,52 @@ impl FilterRun { if s.script_running() { return Err(EngineError::Busy); } - // Typing in progress is kept first, as `s.edit` keeps it, so the copy below holds it. - if !s.previewing && super::typing_in_progress(s) { + // Typing whose text Real-time Drawing off left out of the document isn't in what the + // plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it + // before the run is prepared). + if unapplied_typing(s) { + return Err(err(vectorcraft_plugins::Error::Output( + "typing in progress isn't in what the plug-in was given: nothing was changed".into(), + ))); + } + let data = out.document_data; + // The output applied to `now`, with the checks that refuse it. + let build = |now: &Document, objects: Vec| -> Result<(Document, Vec)> { + let mut d = now.clone(); + let before = (!may_write).then(|| d.layers.clone()); + let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?; + if before.is_some_and(|b| b != d.layers) { + return Err(not_granted(&m.name, Permission::DocWrite)); + } + // Type whose text the output changed is laid out again. + let retyped: Vec = ids + .iter() + .copied() + .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { + (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, + _ => false, + }) + .collect(); + super::typecmd::refresh_bounds_of(&mut d, &retyped); + if let Some(data) = data.clone() { + d.set_plugin_data(&m.id, data); + } + Ok((d, ids)) + }; + // Typing in progress, its text already in the document, is kept as `s.edit` keeps it once + // nothing can refuse the output, so a refused output leaves it in progress. Keeping it can + // change the document, and the output is then applied to the document as kept. + let typing = !s.previewing && super::typing_in_progress(s); + let again = typing.then(|| out.objects.clone()); + let mut now = s.doc()?.doc.clone(); + let (mut d, mut ids) = build(&now, out.objects)?; + if let Some(objects) = again { super::settle_interaction(s)?; - } - let now = s.doc()?.doc.clone(); - let mut d = (*now).clone(); - let before = (!may_write).then(|| d.layers.clone()); - let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; - if before.is_some_and(|b| b != d.layers) { - return Err(not_granted(&m.name, Permission::DocWrite)); - } - // Type whose text the output changed is laid out again. - let retyped: Vec = ids - .iter() - .copied() - .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { - (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, - _ => false, - }) - .collect(); - super::typecmd::refresh_bounds_of(&mut d, &retyped); - if let Some(data) = out.document_data { - d.set_plugin_data(&m.id, data); + let kept = s.doc()?.doc.clone(); + if !Arc::ptr_eq(&kept, &now) { + now = kept; + (d, ids) = build(&now, objects)?; + } } let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::>(); if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) { @@ -454,6 +477,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed"))) } +/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a +/// preview's run)? A run prepared now isn't given that text. +pub fn unapplied_typing(s: &Session) -> bool { + !s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some() +} + +/// Keeps typing in progress whose text Real-time Drawing off left out of the document +/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the +/// typed text; one prepared before it is prepared again. +pub fn keep_unapplied_typing(s: &mut Session) -> Result { + if !unapplied_typing(s) { + return Ok(false); + } + super::settle_interaction(s)?; + Ok(true) +} + /// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with @@ -470,6 +510,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; return r.run_with_calls(s); } + // Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it. + let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r }; // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -893,6 +935,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result }; return r.run_with_calls(s).map_err(failed); } + let r = match keep_unapplied_typing(s)? { + true => { + let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + FilterRun::prepare_with(s, plugin, Some(command), id, p)? + } + false => r, + }; let output = r.run().map_err(&failed)?; r.finish(s, &output).map_err(failed) } diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a2819faa32..53b160889c 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4903,6 +4903,73 @@ fn the_document_context_is_capped_and_its_rows_cost_instructions() { refused(&mut s); } +/// A filter that writes type, run while typing is in progress: the plug-in is given the typed +/// text, so an echo keeps it, with Real-time Drawing on and off. An output that is refused leaves +/// the document and the history as they were; with Real-time Drawing on the typing stays in +/// progress, and off it is kept as its own step before the plug-in is given its input. +#[test] +fn a_filter_that_writes_type_is_given_the_typing_in_progress() { + use vectorcraft_doc::NodeKind; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let manifest = |id: &str| { + format!( + r#"{{"id":"{id}","name":"Retype","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ) + }; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let plain = |s: &Session, t: NodeId| match &node(s, t).kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let typing = |real_time: bool| { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + let v = ViewInfo::default(); + let t = NodeId(run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20}))["id"].as_u64().unwrap()); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("B", v).unwrap(); + assert_eq!(plain(&s, t), if real_time { "AB" } else { "A" }, "real time {real_time}"); + (s, t) + }; + let bang = "test.engine.writes.typing.bang"; + let bad = "test.engine.writes.typing.bad"; + for real_time in [false, true] { + // The plug-in adds "!" to the text it is given: "AB" or, given only "A", "A". + let (mut s, t) = typing(real_time); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + put(&mut s, &tpl::when_given_else(&manifest(bang), tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!"))); + run(&mut s, "plugin.run", json!({"id": bang, "ids": [t.0]})); + assert_eq!(plain(&s, t), "AB!", "real time {real_time}: the plug-in is given the typed text"); + let steps = labels(&s); + assert_eq!(steps[steps.len() - 2..], ["Typing", "Retype"], "real time {real_time}"); + + let (mut s, t) = typing(real_time); + put(&mut s, &tpl::returning(&manifest(bad), &json!({"objects": [{"id": t.0, "transform": [0, 0, 0, 0, 0, 0]}]}).to_string())); + let undo = labels(&s); + let e = s.execute("plugin.run", &json!({"id": bad, "ids": [t.0]})).unwrap_err().to_string(); + assert!(e.contains("transform: flattens the object to a line or a point"), "{e}"); + assert_eq!(plain(&s, t), "AB", "real time {real_time}"); + if real_time { + assert_eq!(labels(&s), undo, "the refused output leaves the history as it was"); + assert!(s.in_interaction(), "and the typing in progress"); + } else { + assert_eq!(labels(&s)[undo.len()..], ["Typing"], "only the typing is kept"); + } + } +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index f7c579337c..020260c5d1 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -23,7 +23,7 @@ use std::sync::mpsc::{Receiver, TryRecvError, channel}; use serde_json::{Value, json}; use vectorcraft_engine::EngineError; use vectorcraft_engine::cmd::fileio::progress::{self, Progress}; -use vectorcraft_engine::cmd::plugin::FilterRun; +use vectorcraft_engine::cmd::plugin::{self, FilterRun}; use crate::VectorcraftApp; use crate::export_progress; @@ -74,6 +74,11 @@ pub fn start(app: &mut VectorcraftApp, p: Value) -> Result { } // Bad parameters and a missing document fail here, before anything runs. let run = FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?; + // Typing Real-time Drawing off left out of the document is kept next, so the plug-in is given it. + let run = match plugin::keep_unapplied_typing(&mut app.session).map_err(|e| e.to_string())? { + true => FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?, + false => run, + }; let who = format!("“{}”", run.plugin().manifest().name.trim_end_matches('…')); let mut params = p; params["ids"] = json!(run.inputs().iter().map(|i| i.0).collect::>()); @@ -140,7 +145,8 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { return; } }; - if !run.current(&app.session) { + // Typing started meanwhile with Real-time Drawing off isn't in what the plug-in was given. + if !run.current(&app.session) || plugin::unapplied_typing(&app.session) { app.status(format!("{} finished, but the document or the plug-in changed meanwhile: run it again", r.who)); return; } diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index ed161e797f..ef910a800e 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -201,6 +201,69 @@ fn a_heavy_filter_s_result_needs_the_document_as_it_was() { assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); } +/// A heavy filter that writes type, run while typing is in progress with Real-time Drawing off: +/// the typing is kept before the run starts, so the plug-in is given the typed text and its result +/// applies once it is done. A run that can't start keeps no typing. Typing started with Real-time +/// Drawing off while it runs isn't in what it was given: nothing changes, and the status bar says +/// to run it again. +#[test] +fn a_heavy_filter_is_given_the_typing_in_progress() { + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_engine::ViewInfo; + use vectorcraft_engine::tools::{PointerEvent, PointerKind}; + let id = "test.ui.heavy.typing"; + let plain = |app: &VectorcraftApp, t: NodeId| match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + // Clicks into the end of `t` with the Type tool and types `text`. + let type_into = |app: &mut VectorcraftApp, t: NodeId, text: &str| { + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(text, v).unwrap(); + }; + let mut app = app(); + app.session.prefs.real_time_drawing = false; + let t = NodeId(app.run("text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20})).unwrap()["id"].as_u64().unwrap()); + let style = match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","budget":"heavy","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ); + // It adds "!" to the text it is given: "AB" or, given only "A", "A". + let src = tpl::when_given_else(&manifest, tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!")); + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + app.run("plugin.install", json!({"dataBase64": data, "allowHeavy": true, "grant": ["doc.read", "doc.write"]})).unwrap(); + type_into(&mut app, t, "B"); + assert_eq!(plain(&app, t), "A", "Real-time Drawing off leaves the typing out of the document"); + // A run that can't start leaves the typing in progress, out of the document. + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(plugin_runs::start(&mut app, json!({"id": "test.ui.heavy.missing", "ids": [t.0]})).is_err()); + assert_eq!(plain(&app, t), "A", "a run that can't start keeps no typing"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(app.session.in_interaction(), "the typing is still in progress"); + let p = json!({"id": id, "ids": [t.0]}); + assert_eq!(plugin_runs::start(&mut app, p.clone()).unwrap()["background"], true); + assert_eq!(plain(&app, t), "AB", "the typing is kept before the run starts"); + finish_runs(&mut app); + assert_eq!(plain(&app, t), "AB!", "{}", app.ui.status); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + // Typing started while it runs, Real-time Drawing off. + plugin_runs::start(&mut app, p).unwrap(); + type_into(&mut app, t, "C"); + let doc = app.session.doc().unwrap().doc.clone(); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().doc, doc, "nothing changed"); + assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); +} + /// The progress window is the run's: headed by it, with Cancel and Continue in Background; Cancel /// stops the run, which changes nothing, and the window goes. #[test]