File dialogs: a replace confirmation runs under the file access of the request that asked

A file dialog's answer runs its continuation under the file-access
scope and automation flag of the request that opened the dialog. The
questions that follow a request did not keep them, and ran what OK
allows in the unconfined UI frame:

- the Replace question after a save picker names an existing file
  (file_asks::ask_replace);
- the question whether a save or export may replace the files it
  writes beside the one picked (confirm::ask_replace_files), also when
  a Background Save or Export asks it after the request has ended;
- a confirmation whose OK runs a command (confirm::ask), such as the
  question before a save loses data.

A save, export or open started by a request confined to its automation
roots could then reach files outside those roots once the person
answered OK, and it no longer ran as automation. Each question now
captures ScopeHandle::capture() and automation_asked() when it is
asked, and its OK runs under them, as a picker's answer does. A
background save or export captures them before it leaves the request.
This commit is contained in:
dotCooCoo committed 2026-11-25 09:15:23 -08:00
1 parent d0b332dc71
commit 3a0bfba325
6 files changed
+174 -16

No files matched your search

+34 -6
View File
@@ -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::<Question>())
&& 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::<Asked>()
&& 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::<Question>()?.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::<Asked>()?;
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<Vec<String>> {
app.dialogs()?.with(|host| host.get::<ReplaceFilesPrompt>().and_then(|q| q.0.tag_as::<ReplaceFiles>().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::<ReplaceFilesPrompt>()?.0.tag_as::<ReplaceFiles>()?;
Some((tag.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), tag.automated))
})
}
+11 -5
View File
@@ -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,
}
@@ -155,7 +159,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 +312,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::<StandardPrompt>(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::<StandardPrompt>(r.dialog).is_some() => open.push(r),
// Neither open nor holding a result: closed from outside.
@@ -317,8 +322,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
host.take::<ReplaceFilesPrompt>()
});
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 +333,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
{
let all: Vec<String> = 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);
}
}
+3 -1
View File
@@ -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<String> = 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()),
+20 -4
View File
@@ -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;
@@ -811,9 +812,22 @@ pub(super) fn checks_replaced(app: &mut VectorcraftApp) -> (Option<crate::Exists
/// Ask before a save or export of the document `doc` (its uid) replaces `files`, files that are
/// there beside the one picked in the save panel (a file per artboard, a linked image), which the
/// panel did not ask about. OK runs `command` with `params` again, replacing them and `allowed`
/// (those an earlier OK allowed); Cancel writes nothing → `{pending}`.
pub(super) fn ask_to_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[String], allowed: &[String], command: &str, params: &Value) -> 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 +1031,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 +1115,7 @@ fn write_plan(
// Nothing written either: asked first.
if let Some(files) = r.get("replaces").and_then(Value::as_array) {
let files: Vec<String> = 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);
+74
View File
@@ -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() {
+32
View File
@@ -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");