diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 9584166098..12e13a36b3 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -7,6 +7,7 @@ use craft::ui::dialog::{Alert, DialogHost, DialogId, DialogResult, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage}; use egui::Context; use serde_json::{Value, json}; +use vectorcraft_engine::file_access::ScopeHandle; use crate::VectorcraftApp; @@ -81,8 +82,18 @@ macro_rules! wrapped_dialog { } pub(crate) use wrapped_dialog; -/// A confirmation: its tag is the command OK runs and that command's params. +/// A confirmation: its tag is an [`Asked`]. pub(crate) struct Question(StandardPrompt); + +/// The tag of a confirmation ([`ask`]): the command OK runs, and the access it runs under. +struct Asked { + command: String, + params: Value, + /// The automation roots in force when asked: the command runs under them. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. + automated: bool, +} wrapped_dialog!(Question, StandardPrompt, KIND); /// A message with a Close button. @@ -110,6 +121,10 @@ pub(crate) struct ReplaceFiles { pub(crate) command: String, /// Its params. pub(crate) params: Value, + /// The automation roots in force when asked: the command runs again under them. + pub(crate) scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs again as automation. + pub(crate) automated: bool, } /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` @@ -123,7 +138,8 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, if !detail.is_empty() { prompt = prompt.paragraph(detail.to_string()); } - let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag((command.to_string(), params)); + let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() }; + let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked); dialogs.with(|host| host.open(Question(prompt))); } @@ -184,6 +200,8 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str allowed: allowed.to_vec(), command: command.to_string(), params, + scope: ScopeHandle::capture(), + automated: app.automation_asked(), }); // Asked when a Background Save or Export ends: a dialog open then stays, and this waits its turn // (however many messages wait: the save or export needs the answer). @@ -240,8 +258,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }; if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) && answer.choice == PromptChoice::Proceed - && let Some((command, params)) = answer.take_tag::<(String, Value)>() - && let Err(e) = app.run(&command, params) + && let Some(Asked { command, params, scope, automated }) = answer.take_tag::() + && let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { app.status(e); } @@ -273,8 +291,8 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, String, String)> { app.dialogs()?.with(|host| { let prompt = &host.get::()?.0; - let (command, _) = prompt.tag_as::<(String, Value)>()?; - Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), command.clone())) + let asked = prompt.tag_as::()?; + Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), asked.command.clone())) }) } @@ -290,3 +308,13 @@ pub(crate) fn open_message(app: &VectorcraftApp) -> Option<(String, String)> { pub(crate) fn open_replace_files(app: &VectorcraftApp) -> Option> { app.dialogs()?.with(|host| host.get::().and_then(|q| q.0.tag_as::().map(|tag| tag.files.clone()))) } + +/// Whether the open question about replacing files runs its command confined to automation roots, +/// and whether as automation, while it is open. +#[cfg(test)] +pub(crate) fn open_replace_files_access(app: &VectorcraftApp) -> Option<(bool, bool)> { + app.dialogs()?.with(|host| { + let tag = host.get::()?.0.tag_as::()?; + Some((tag.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), tag.automated)) + }) +} diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index 9624d81a5e..ba6a6f57dd 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -51,6 +51,10 @@ struct Waiting { /// A replace question on the dialog host, and what proceeding runs. struct Replacing { dialog: DialogId, + /// The automation roots in force when asked, as [`Waiting::scope`]. + scope: ScopeHandle, + /// Automation asked, as [`Waiting::automated`]. + automated: bool, then: Proceed, } @@ -74,6 +78,14 @@ impl FileAsks { pub(crate) fn asking(&self) -> bool { !self.waiting.is_empty() || !self.replacing.is_empty() } + + /// Whether the newest open replace question goes on confined to automation roots, and whether + /// as automation. + #[cfg(test)] + pub(crate) fn replace_access(&self) -> Option<(bool, bool)> { + let r = self.replacing.last()?; + Some((r.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), r.automated)) + } } // PLAN: callers use the function form of `BUSY` and `CLOSED`; `tl!` is a runtime lookup, so they are not consts. @@ -155,7 +167,8 @@ pub(crate) fn ask_replace( app.file_asks.next_question += 1; let prompt = StandardPrompt::replace_file(name(path), Some(name(answered))).instance(("vectorcraft.replaceFile", app.file_asks.next_question)); let dialog = dialogs.with(|host| host.open(prompt)); - app.file_asks.replacing.push(Replacing { dialog, then: Box::new(then) }); + let (scope, automated) = (ScopeHandle::capture(), app.automation_asked()); + app.file_asks.replacing.push(Replacing { dialog, scope, automated, then: Box::new(then) }); json!({ "pending": "replaceFile" }) } @@ -307,7 +320,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let files = dialogs.with(|host| { for r in previous { match host.take_by_id::(r.dialog) { - Some(DialogResult::Ok(answer)) if answer.choice == PromptChoice::Proceed => proceed.push(r.then), + Some(DialogResult::Ok(answer)) if answer.choice == PromptChoice::Proceed => proceed.push(r), Some(_) => {} None if host.get_by_id::(r.dialog).is_some() => open.push(r), // Neither open nor holding a result: closed from outside. @@ -317,8 +330,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { host.take::() }); app.file_asks.replacing.extend(open); - for then in proceed { - let result = then(app); + for Replacing { scope, automated, then, .. } in proceed { + let result = scope.run(|| as_automated(app, automated, then)); report(app, result); } if let Some(DialogResult::Ok(mut answer)) = files @@ -328,7 +341,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { { let all: Vec = r.files.iter().chain(&r.allowed).cloned().collect(); crate::io::save::allow_replacing(app, &all); - let result = app.run(&r.command, r.params); + let ReplaceFiles { scope, automated, command, params, .. } = r; + let result = scope.run(|| as_automated(app, automated, |app| app.run(&command, params))); report(app, result); } } diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 8f19aaef13..e3acc7f9b8 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -157,6 +157,8 @@ fn write_export(app: &mut VectorcraftApp, export: Export, path: String) -> Resul let (exists, allowed) = checks_replaced(app); let allowed_before = allowed.clone(); let rerun = with_path(&again, &path); + // The question whether the export may replace files is asked under the request's scope. + let asked_access = (vectorcraft_engine::file_access::ScopeHandle::capture(), app.automation_asked()); let work = move |write: Writer| { progress::scope(&reporting, || { cancel::check().map_err(|e| e.to_string())?; @@ -192,7 +194,7 @@ fn write_export(app: &mut VectorcraftApp, export: Export, path: String) -> Resul // Nothing written: asked first. if let Some(files) = r.get("replaces").and_then(Value::as_array) { let files: Vec = files.iter().filter_map(Value::as_str).map(str::to_string).collect(); - return Ok(ask_to_replace_files(app, uid, &files, &allowed_before, "file.exportAs", &rerun)); + return Ok(ask_to_replace_files(app, uid, &files, &allowed_before, "file.exportAs", &rerun, asked_access)); } let what = match r["files"].as_array() { Some(files) => format!("{} files", files.len()), diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 322ab69b1f..98f082b312 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -13,6 +13,7 @@ use craft::platform::watch::FileWatch; use craft::ui::dialog::DialogId; #[cfg(not(target_arch = "wasm32"))] use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; +use vectorcraft_engine::file_access::ScopeHandle; use super::export::file_url; use super::open::note_recent; @@ -41,6 +42,9 @@ struct SaveDone { retry: Option, /// The changed-on-disk question, while it is open. question: Option, + /// The file-access scope and automation flag of the request that started the save: the steps + /// [`pump`] runs once the flow answers run under them, not under the desktop's access of that frame. + asked: (ScopeHandle, bool), then: Option, } @@ -135,8 +139,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { app.saves.watch.forget(&uid); continue; } - let Some(step) = next_step(app, uid) else { continue }; - if let Err(e) = run_step(app, uid, step) + let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone()); + let r = scope.run(|| { + file_asks::as_automated(app, automated, |app| { + let step = next_step(app, uid)?; + Some(run_step(app, uid, step)) + }) + }); + if let Some(Err(e)) = r && e != "cancelled" { app.status(e); @@ -278,6 +288,7 @@ fn start_flow(app: &mut VectorcraftApp, first: &SavePlan, s: Start<'_>) -> Resul retrying: s.retrying, retry: s.retry, question: None, + asked: (ScopeHandle::capture(), app.automation_asked()), then, }; app.saves.done.insert(uid, done); @@ -811,9 +822,22 @@ pub(super) fn checks_replaced(app: &mut VectorcraftApp) -> (Option Value { - dialogs::confirm::ask_replace_files(app, doc, files, allowed, command, params.clone()); +/// (those an earlier OK allowed); Cancel writes nothing → `{pending}`. `asked` is the file-access +/// scope and automation flag of the request that started the save or export, captured before it +/// went to the background: OK runs `command` again under them. +pub(super) fn ask_to_replace_files( + app: &mut VectorcraftApp, + doc: u64, + files: &[String], + allowed: &[String], + command: &str, + params: &Value, + asked: (ScopeHandle, bool), +) -> Value { + let (scope, automated) = asked; + scope.run(|| { + file_asks::as_automated(app, automated, |app| dialogs::confirm::ask_replace_files(app, doc, files, allowed, command, params.clone())); + }); json!({ "pending": dialogs::confirm::REPLACE_FILES }) } @@ -1017,6 +1041,8 @@ fn write_plan( // Capture the caller before background work leaves the request: it must never open a panel // or error dialog later, when answering_control has been reset. let by_control = app.automation_asked(); + // The question whether the save may replace files is asked under the request's scope. + let asked_scope = ScopeHandle::capture(); let location_refused = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let refused_by_work = location_refused.clone(); let own_path = target.clone(); @@ -1099,7 +1125,7 @@ fn write_plan( // Nothing written either: asked first. if let Some(files) = r.get("replaces").and_then(Value::as_array) { let files: Vec = files.iter().filter_map(Value::as_str).map(str::to_string).collect(); - return Ok(ask_to_replace_files(app, uid, &files, &allowed, again.0, &again.1)); + return Ok(ask_to_replace_files(app, uid, &files, &allowed, again.0, &again.1, (asked_scope, by_control))); } // The document may have closed meanwhile: the file is written all the same. done.complete(&mut app.session, uid); diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 0b081f125c..7511d656d3 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -15,6 +15,7 @@ use craft::ui::runtime::requests::{PathKind, PathRequest}; use egui::{Pos2, Rect, vec2}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use vectorcraft_engine::file_access; use crate::dialogs::confirm::REPLACE_FILES; use crate::{Services, VectorcraftApp, file_asks}; @@ -394,6 +395,79 @@ fn a_pdf_automation_asked_for_is_not_opened_when_its_save_panel_answers() { assert!(matches!(urls.as_slice(), [url] if url.ends_with("/art/mine.pdf")), "{urls:?}"); } +/// A replace question automation asked while confined to a folder: what Replace allows runs as +/// automation's, with that folder still the only place it may write, as the answer of a file dialog does. +#[test] +fn a_replace_question_goes_on_under_the_access_it_was_asked_with() { + let mut app = app(); + app.ui_ctx = Some(crate::testing::ui_context()); + let (inside, outside) = (vectorcraft_testkit::TempDir::new("replace-scope-in"), vectorcraft_testkit::TempDir::new("replace-scope-out")); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let path = inside.join("Art.svg").to_string_lossy().into_owned(); + let elsewhere = outside.join("Art.svg").to_string_lossy().into_owned(); + let seen = Rc::new(RefCell::new(None)); + let s = seen.clone(); + file_access::confine(roots.as_ref(), || { + file_asks::as_automated(&mut app, true, |app| { + file_asks::ask_replace(app, &path, "Art", move |app| { + *s.borrow_mut() = Some((file_access::check_write(&elsewhere).is_ok(), app.automation_asked())); + Ok(Value::Null) + }) + }) + }); + assert_eq!(replace_asked(&app).as_deref(), Some("Art.svg")); + answer_replace(&mut app, true); + assert_eq!(*seen.borrow(), Some((false, true)), "(may write outside the folder, runs as automation's)"); +} + +/// The question whether a save or export may replace files, asked by automation confined to a +/// folder: OK runs the command again with that folder still the only place it may read. +#[test] +fn a_replace_files_question_runs_its_command_under_the_access_it_was_asked_with() { + let mut app = app(); + app.ui_ctx = Some(crate::testing::ui_context()); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + let (inside, outside) = + (vectorcraft_testkit::TempDir::new("replace-files-scope-in"), vectorcraft_testkit::TempDir::new("replace-files-scope-out")); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let elsewhere = outside.join("Other.svg"); + std::fs::write(&elsewhere, SVG).unwrap(); + let elsewhere = elsewhere.to_string_lossy().into_owned(); + let doc = app.session.active().unwrap().uid; + let there = [inside.join("Art.svg").to_string_lossy().into_owned()]; + file_access::confine(roots.as_ref(), || { + file_asks::as_automated(&mut app, true, |app| { + crate::dialogs::confirm::ask_replace_files(app, doc, &there, &[], "file.open", json!({ "path": elsewhere })); + }) + }); + assert_eq!(crate::dialogs::confirm::open_replace_files(&app), Some(there.to_vec())); + answer_replace(&mut app, true); + assert!(app.ui.status.contains("outside the read root"), "the file outside the folder is refused: {}", app.ui.status); + assert_eq!(app.session.documents().len(), 1, "nothing else opened"); +} + +/// A confirmation automation asked while confined to a folder: OK runs its command as automation's, +/// with that folder still the only place it may read. +#[test] +fn a_confirmation_runs_its_command_under_the_access_it_was_asked_with() { + let mut app = app(); + app.ui_ctx = Some(crate::testing::ui_context()); + let (inside, outside) = (vectorcraft_testkit::TempDir::new("confirm-scope-in"), vectorcraft_testkit::TempDir::new("confirm-scope-out")); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let elsewhere = outside.join("Other.svg"); + std::fs::write(&elsewhere, SVG).unwrap(); + let elsewhere = elsewhere.to_string_lossy().into_owned(); + file_access::confine(roots.as_ref(), || { + file_asks::as_automated(&mut app, true, |app| { + crate::dialogs::confirm::ask(app, "Open it?", "", "file.open", json!({ "path": elsewhere })); + }) + }); + let id = open_dialogs(&app).last().map(|d| d.id).expect("the question is open"); + answer_dialog(&mut app, id, &[], true); + assert!(app.ui.status.contains("outside the read root"), "the file outside the folder is refused: {}", app.ui.status); + assert!(app.session.documents().is_empty(), "nothing opened"); +} + /// A Browse row's answer fills the open dialog's field; an answer after the dialog closed does nothing. #[test] fn a_dialogs_folder_button_fills_its_field_when_the_picker_answers() { diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index 2c1fc025df..c5a2815463 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -420,6 +420,38 @@ fn an_eps_save_with_use_artboards_asks_before_replacing_an_artboard_file_that_is let _ = std::fs::remove_dir_all(d); } +/// A background save that automation confined to a folder started asks about the files it would +/// replace once its result arrives, outside the request; OK still runs the save again under that +/// folder and as automation. +#[test] +fn a_background_save_asks_about_replacing_files_under_the_access_of_the_request_that_started_it() { + let d = dir("eps-artboards-confined"); + let path = d.join("Art.eps").to_string_lossy().to_string(); + let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false}); + let mut other = app(); + other.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let _ = other.run("file.saveAs", json!({"path": path, "options": options})); + let there = artboard_files(&d); + assert_eq!(there.len(), 2, "{there:?}"); + std::fs::remove_file(&path).unwrap(); + let mut app = app(); + checks_files_there(&mut app); + app.services.write_shared = Some(std::sync::Arc::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut app); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[d.as_path()], &[d.as_path()]).unwrap(); + let r = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| app.run("file.saveAs", json!({"path": path, "options": options}))) + }) + .unwrap(); + assert_eq!(r["background"], true, "{r}"); + // The save's result is applied outside the request, as the next frame does. + crate::background::wait_all(&mut app); + assert_eq!(confirm::open_replace_files(&app), Some(there.clone())); + assert_eq!(confirm::open_replace_files_access(&app), Some((true, true)), "(confined, as automation)"); + let _ = std::fs::remove_dir_all(d); +} + #[test] fn native_saves_stream_into_the_file() { let d = dir("stream"); diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index d3ed6f1a3e..dd058a6043 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -302,6 +302,31 @@ fn a_replaced_extension_asks_before_replacing_a_file_there() { } } +/// A save that automation confined to a folder started: its panel answers in a later frame, outside +/// the request, and the question before replacing a file the panel did not ask about goes on under +/// that folder and as automation. +#[test] +fn a_replace_question_after_a_save_panel_goes_on_under_the_access_of_the_request() { + let (mut app, picker, w) = saving_app(); + let inside = vectorcraft_testkit::TempDir::new("save-replace-scope"); + let typed = inside.join("card.png").to_string_lossy().into_owned(); + let there = inside.join("card.vectorcraft").to_string_lossy().into_owned(); + let t = there.clone(); + app.services.exists = Some(Arc::new(move |p: &str| p == t)); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| { + let _ = app.run("file.save", json!({})); + }) + }); + picker.answer_saved(&typed, None); + poll(&mut app); + assert_eq!(replace_asked(&app).as_deref(), Some("card.vectorcraft")); + assert_eq!(app.file_asks.replace_access(), Some((true, true)), "(confined, as automation)"); + answer_replace(&mut app, true); + assert_eq!(*w.borrow(), [there]); +} + /// Save As to the type picked asks for that format's options: the .ai options (Version first), /// not VectorCraft's. #[test]