fix: preserve Actions dialog ownership and picker limits

This commit is contained in:
yoriswind committed 2026-11-02 11:07:35 -08:00
1 parent 848c6aa6ca
commit dd1f34a57d
14 files changed
+359 -17

No files matched your search

+6
View File
@@ -35,6 +35,12 @@ pub fn read_file_with(path: &Path, chunk: usize) -> io::Result<Vec<u8>> {
read_path(path, chunk, MAX_OPEN_BYTES)
}
/// Read a picked file within the caller's limit, before allocation and throughout any growth.
/// The global [`MAX_OPEN_BYTES`] ceiling and regular-file checks still apply.
pub fn read_file_limited(path: &Path, max: u64) -> io::Result<Vec<u8>> {
read_path(path, READ_CHUNK, max.min(MAX_OPEN_BYTES))
}
/// [`read_file_with`] with a chosen total limit (tests use small ones).
fn read_path(path: &Path, chunk: usize, max: u64) -> io::Result<Vec<u8>> {
#[cfg(unix)]
+2
View File
@@ -10,3 +10,5 @@ mod frame_stroke;
mod layer_labels;
mod roundtrip;
mod smart_contents;
mod read_limits;
+17
View File
@@ -0,0 +1,17 @@
//! Caller-specific file limits reuse the regular-file reader and preserve the default ceiling.
/// Exact, over-limit, empty, and default reads use tiny regular files rather than large allocations.
#[test]
fn picked_read_limit_checks_before_allocating_and_preserves_default_reader() {
let dir = super::common::temp_dir("picked-read-limit");
let path = dir.join("small.atn");
std::fs::write(&path, b"12345").unwrap();
assert_eq!(photocraft_format::read::read_file_limited(&path, 5).unwrap(), b"12345");
assert_eq!(photocraft_format::read::read_file_limited(&path, 4).unwrap_err().kind(), std::io::ErrorKind::FileTooLarge);
assert_eq!(photocraft_format::read_file(&path).unwrap(), b"12345");
std::fs::write(&path, b"").unwrap();
assert!(photocraft_format::read::read_file_limited(&path, 0).unwrap().is_empty());
assert!(photocraft_format::read::read_file_limited(&dir, 5).is_err());
std::fs::remove_file(path).unwrap();
std::fs::remove_dir(dir).unwrap();
}
+4
View File
@@ -170,12 +170,16 @@ fn run_waiting(app: &mut PhotocraftApp, wait: bool, run: impl FnOnce(&mut Photoc
const SHELL_DIALOG: &str = "shell";
pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
// Request identity, rather than an optional gate, determines programmatic playback.
let input = app.automation_input;
app.automation_input |= req.method == "engine.execute";
let saved = app.session.authorize;
if let Some(gate) = app.services.automation_authorize {
app.session.authorize = Some(gate);
}
let outcome = dispatch(app, ctx, req);
app.session.authorize = saved;
app.automation_input = input;
outcome
}
+27 -4
View File
@@ -231,11 +231,21 @@ impl PhotocraftApp {
&mut self,
extensions: &[&str],
then: impl FnOnce(&mut Self, String, Vec<u8>) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
self.pick_file_bytes_with_limit(extensions, None, then)
}
/// Pick a file with an optional caller limit; other pickers retain their existing read limit.
pub(crate) fn pick_file_bytes_with_limit(
&mut self,
extensions: &[&str],
max: Option<u64>,
then: impl FnOnce(&mut Self, String, Vec<u8>) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
let initial_dir = last_used_dir(&self.ui.recent_files);
let extensions = (!extensions.is_empty()).then(|| extensions.iter().map(|s| (*s).to_string()).collect());
self.ask_file(FileDialogRequest::Open { multiple: false, initial_dir, extensions }, move |app, answer| {
let (name, bytes) = read_picked(answer)?;
let (name, bytes) = read_picked(answer, max)?;
then(app, name, bytes)
})
}
@@ -377,18 +387,31 @@ pub(crate) fn last_used_dir(recent: &[String]) -> Option<String> {
}
/// The name and bytes of the single file an open dialog answered with.
fn read_picked(answer: FileDialogAnswer) -> Result<(String, Vec<u8>), String> {
match answer {
fn read_picked(answer: FileDialogAnswer, max: Option<u64>) -> Result<(String, Vec<u8>), String> {
let picked: Result<(String, Vec<u8>), String> = match answer {
FileDialogAnswer::Contents(name, bytes) => Ok((name, bytes)),
FileDialogAnswer::ContentsMany(files) => files.into_iter().next().ok_or_else(|| CANCELLED.into()),
FileDialogAnswer::Paths(paths) => {
let path = paths.into_iter().next().ok_or(CANCELLED)?;
let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| format!("{}: {e}", display_name(&path)))?;
let file = std::path::Path::new(&path);
let bytes = match max {
Some(max) => photocraft_format::read::read_file_limited(file, max),
None => photocraft_format::read_file(file),
}
.map_err(|e| format!("{}: {e}", display_name(&path)))?;
Ok((path, bytes))
}
FileDialogAnswer::FolderTo(_) => Err(UNEXPECTED.into()),
FileDialogAnswer::SaveTo(_) | FileDialogAnswer::Unavailable(_) => Err(UNEXPECTED.into()),
};
let (name, bytes) = picked?;
// Web answers already own their platform-provided bytes: refuse before callbacks can parse or copy them.
if let Some(max) = max
&& bytes.len() as u64 > max
{
return Err(format!("{}: the file is larger than {} bytes", display_name(&name), max));
}
Ok((name, bytes))
}
/// A fake dialog service for tests: answers each request with the next of `answers` (`None`:
+41
View File
@@ -1484,3 +1484,44 @@ fn import_variable_data_sets_menu_asks_for_a_csv_and_imports_it() {
app.poll_file_dialog(&ctx, None);
assert_eq!(app.session.active().map(|d| d.doc.variables.data_sets.len()), Some(2));
}
/// A tiny caller cap rejects picked paths and existing byte payloads before their callback runs.
#[test]
fn picked_file_limit_refuses_before_callback_and_keeps_other_callers_unchanged() {
let dir = tempfile::tempdir().unwrap();
let exact = dir.path().join("exact.atn");
let over = dir.path().join("over.atn");
std::fs::write(&exact, b"1234").unwrap();
std::fs::write(&over, b"12345").unwrap();
for (chosen, max, allowed) in [
(FileDialogAnswer::Paths(vec![exact.to_str().unwrap().into()]), Some(4), true),
(FileDialogAnswer::Paths(vec![over.to_str().unwrap().into()]), Some(4), false),
(FileDialogAnswer::Contents("exact.atn".into(), b"1234".to_vec()), Some(4), true),
(FileDialogAnswer::Contents("over.atn".into(), b"12345".to_vec()), Some(4), false),
(FileDialogAnswer::ContentsMany(vec![("over.atn".into(), b"12345".to_vec())]), Some(4), false),
(FileDialogAnswer::Paths(vec![over.to_str().unwrap().into()]), None, true),
(FileDialogAnswer::Contents("over.atn".into(), b"12345".to_vec()), None, true),
] {
let (mut app, open, _) = app();
let ctx = egui::Context::default();
let called = Rc::new(std::cell::Cell::new(false));
let callback = called.clone();
let then = move |_: &mut PhotocraftApp, _: String, bytes: Vec<u8>| {
callback.set(true);
Ok(json!({"bytes":bytes.len()}))
};
if let Some(max) = max {
app.pick_file_bytes_with_limit(&["atn"], Some(max), then).unwrap();
} else {
app.pick_file_bytes_filtered(&["atn"], then).unwrap();
}
app.poll_file_dialog(&ctx, None);
answer(&open, Some(chosen));
app.poll_file_dialog(&ctx, None);
assert_eq!(called.get(), allowed);
if !allowed {
assert!(app.ui.status_error);
assert!(app.ui.status.contains("larger"), "{}", app.ui.status);
}
}
}
+20 -3
View File
@@ -272,7 +272,8 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option<Value>)
} else {
crate::dialogs::open_command_dialog(app, id, &label)
};
let token = app.paused_playbacks.pause(action.name.clone(), i + 1, app.session.authorize);
let document = app.session.active().map(|st| st.doc.id);
let token = app.paused_playbacks.pause(action.name.clone(), i + 1, app.session.authorize, document);
if let Some(paused) = app.paused_playbacks.paused.get_mut(&token) {
paused.editor = Some((dialog, id.to_string()));
}
@@ -771,6 +772,8 @@ pub(crate) struct PausedPlayback {
action: String,
from: usize,
gate: Option<Gate>,
/// Stable document identity captured before this command's editor is shown.
document: Option<photocraft_doc::DocId>,
/// The real editor and fixed command; editable fields hold only its read-only resume token.
editor: Option<(u64, String)>,
/// The recording the paused call suspended: `{index, into, action, from}` (`into` is the
@@ -797,9 +800,9 @@ pub(crate) struct PausedPlaybacks {
}
impl PausedPlaybacks {
fn pause(&mut self, action: String, from: usize, gate: Option<Gate>) -> u64 {
fn pause(&mut self, action: String, from: usize, gate: Option<Gate>, document: Option<photocraft_doc::DocId>) -> u64 {
self.last = self.last.wrapping_add(1);
self.paused.insert(self.last, PausedPlayback { action, from, gate, editor: None, record: None, then: Vec::new(), ran: 0 });
self.paused.insert(self.last, PausedPlayback { action, from, gate, document, editor: None, record: None, then: Vec::new(), ran: 0 });
self.last
}
@@ -813,8 +816,19 @@ fn playback_editor(app: &PhotocraftApp, dialog: u64) -> Option<&PausedPlayback>
app.paused_playbacks.paused.values().find(|p| p.editor.as_ref().is_some_and(|(id, _)| *id == dialog))
}
/// A paused editor may evaluate and resume only on the document that opened it.
fn validate_playback_document(app: &PhotocraftApp, owner: &PausedPlayback) -> Result<(), String> {
if app.session.active().map(|st| st.doc.id) != owner.document {
return Err("the paused action belongs to a different document".into());
}
Ok(())
}
/// The read-only resume token may only settle its own real command editor.
pub(crate) fn validate_editor(app: &PhotocraftApp, dialog: u64, fields: &serde_json::Map<String, Value>) -> Result<(), String> {
if let Some(owner) = playback_editor(app, dialog) {
validate_playback_document(app, owner)?;
}
let Some(token) = fields.get(RESUME) else { return Ok(()) };
let owner = token
.as_u64()
@@ -834,6 +848,7 @@ pub(crate) fn validate_editor(app: &PhotocraftApp, dialog: u64, fields: &serde_j
pub(crate) fn authorize_preview(app: &PhotocraftApp, dialog: u64, command: &str, params: &Value) -> Result<(), String> {
record_again::authorize_preview(app, dialog, command, params)?;
if let Some(owner) = playback_editor(app, dialog) {
validate_playback_document(app, owner)?;
if owner.editor.as_ref().is_none_or(|(_, id)| id != command) {
return Err("the paused action preview command changed".into());
}
@@ -904,6 +919,8 @@ pub(crate) fn confirm_owned_dialog(app: &mut PhotocraftApp, dialog: u64, fields:
/// confirmed: a control request, synthetic Enter or OK, or a click.
pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>) -> Result<(), String> {
let Some(token) = fields.get(RESUME) else { return Ok(()) };
let owner = token.as_u64().and_then(|t| app.paused_playbacks.paused.get(&t)).ok_or("this dialog doesn't belong to a paused action")?;
validate_playback_document(app, owner)?;
let Some(paused) = app.paused_playbacks.take(token) else {
return Err("this dialog doesn't belong to a paused action".into());
};
@@ -27,9 +27,6 @@ pub(super) fn open(app: &mut PhotocraftApp) -> Result<Value, String> {
let target = json!({"action":action,"at":app.ui.actions.selected_step.map(|i|i.saturating_add(1))});
let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None });
let automated = app.automation_input || gate.is_some();
let mut params = target.clone();
params["id"] = json!("image.imageSize");
super::authorize_owned(app, COMMAND, &params, gate, automated)?;
let fields = json!({MARK:true,"__command":COMMAND,"__label":"Insert Menu Item","id":"image.imageSize"});
let dialog = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default());
app.held_insert_menu = Some(Held { dialog, revision: app.session.actions.rev, target, gate, automated });
+3 -4
View File
@@ -46,14 +46,11 @@ pub(super) fn open(app: &mut PhotocraftApp) -> Result<Value, String> {
let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None });
let automated = app.automation_input || gate.is_some();
authorize(app, &json!({"confirm": true}), gate, automated)?;
app.pick_file_bytes_filtered(&["atn"], move |app, name, bytes| {
app.pick_file_bytes_with_limit(&["atn"], Some(photocraft_engine::preset_import_cmds::MAX_FILE_BYTES), move |app, name, bytes| {
idle(app)?;
if app.session.actions.rev != revision || app.held_actions_replace.is_some() {
return Err(tl!("The actions changed. Request Replace Actions again.").into());
}
if bytes.len() as u64 > photocraft_engine::preset_import_cmds::MAX_FILE_BYTES {
return Err(tl!("The Actions file is too large.").into());
}
// Validate before asking to discard the library. The normal command parses this
// same immutable input again on confirmation, keeping dispatch authoritative.
let count = photocraft_engine::atn_cmds::import(&bytes)?.actions.len();
@@ -87,11 +84,13 @@ pub(crate) fn confirm(app: &mut PhotocraftApp, dialog: u64, fields: &Map<String,
}
idle(app)?;
authorize(app, &held.params, held.gate, held.automated)?;
let replaced_sets = photocraft_engine::actions_edit_cmds::set_names(&app.session);
let saved = app.session.authorize;
app.session.authorize = saved.or(held.gate);
let result = app.run(COMMAND, held.params);
app.session.authorize = saved;
let result = result?;
app.ui.actions.collapsed_sets.retain(|set| !replaced_sets.contains(set));
app.ui.actions.selected = (!app.session.actions.list.is_empty()).then_some(0);
app.ui.actions.selected_set = if app.session.actions.list.is_empty() {
result.get("set").and_then(Value::as_str).filter(|set| app.session.actions.sets.iter().any(|s| s == set)).map(str::to_string)
+7 -2
View File
@@ -34,8 +34,13 @@ pub(super) fn open(app: &mut PhotocraftApp) -> Result<Value, String> {
}
let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None });
let automated = app.automation_input || gate.is_some();
super::authorize_owned(app, COMMAND, &json!({"mode":"append","confirm":true}), gate, automated)?;
let fields = json!({MARK:true,"__command":COMMAND,"__label":"Reset Actions","mode":"append"});
let mode = if super::authorize_owned(app, COMMAND, &json!({"mode":"append","confirm":true}), gate, automated).is_ok() {
"append"
} else {
super::authorize_owned(app, COMMAND, &json!({"mode":"replace","confirm":true}), gate, automated)?;
"replace"
};
let fields = json!({MARK:true,"__command":COMMAND,"__label":"Reset Actions","mode":mode});
let dialog = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default());
app.held_actions_reset = Some(Held { dialog, revision: app.session.actions.rev, gate, automated });
Ok(json!({"dialog":dialog}))
@@ -120,3 +120,24 @@ fn stale_denied_or_retargeted_confirmations_never_clear_the_library() {
assert_eq!(h.state().session.active().unwrap().revision, revision, "{mode}");
}
}
/// Suspended recording, rather than a stale warning revision, prevents Clear All from losing a call.
#[test]
fn clear_confirmation_refuses_a_recording_suspended_at_a_step_dialog() {
let mut h = harness();
h.state_mut().background_jobs = false;
let a = &mut h.state_mut().session.actions.list[0];
a.steps = vec![("filter.blur.gaussianBlur".into(), json!({"radius":1}))];
a.dialogs.insert(0);
let warning = open(&mut h);
let revision = h.state().session.actions.rev;
h.state_mut().run("actions.record", json!({"action":"B"})).unwrap();
let paused = h.state_mut().run("actions.play", json!({"action":"A"})).unwrap();
assert!(paused["paused"]["dialog"].is_u64());
assert!(h.state().session.actions.recording.is_none());
assert_eq!(h.state().session.actions.rev, revision, "the original warning is still current");
let library = h.state().session.actions.list.clone();
let error = dialogs::confirm(h.state_mut(), warning).unwrap_err();
assert!(error.contains("step dialog"), "{error}");
assert_eq!(h.state().session.actions.list, library);
}
@@ -92,6 +92,20 @@ fn insert_menu_item_chooser_cancels_or_records_descriptor_free_filter_event() {
let dialog = played["paused"]["dialog"].as_u64().unwrap();
assert_eq!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields["__command"], "filter.blur.gaussianBlur");
dialogs::cancel(h.state_mut(), dialog).unwrap();
h.state_mut().run("paint.stroke", json!({"points":[[6,6]],"size":3,"hardness":1,"color":"#000000"})).unwrap();
let original = photocraft_compose::flatten(&h.state().session.active().unwrap().doc).into_px();
let mut expected = Session::new();
expected.add_document((*h.state().session.active().unwrap().doc).clone(), None);
expected.execute("filter.blur.gaussianBlur", json!({"radius":2})).unwrap();
let expected = photocraft_compose::flatten(&expected.active().unwrap().doc).into_px();
assert_ne!(expected, original, "the Gaussian fixture has a visible effect");
h.state_mut().session.actions.list[0].steps.push(("select.all".into(), json!({})));
let paused = h.state_mut().run("actions.play", json!({"action":"A"})).unwrap();
let dialog = paused["paused"]["dialog"].as_u64().unwrap();
h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("radius".into(), json!(2));
dialogs::confirm(h.state_mut(), dialog).unwrap();
assert_eq!(photocraft_compose::flatten(&h.state().session.active().unwrap().doc).into_px(), expected);
assert!(h.state().session.active().unwrap().doc.selection.is_some(), "confirmation resumes the following step");
}
/// The selected path is snapshotted without applying it to the document.
@@ -215,3 +229,41 @@ fn paused_menu_previews_and_picker_callbacks_keep_the_requesting_gate() {
assert_eq!(h.state().session.active().unwrap().revision, revision);
assert_eq!(h.state().session.actions.list[0].steps[0].1, json!({}));
}
/// Policy may permit the chosen filter while refusing Image Size and append mode.
fn chosen_only(id: &str, p: &Value) -> photocraft_engine::Result<()> {
if id == "image.imageSize"
|| id == "actions.insertMenuItem" && p.get("id").is_some_and(|v| v == "image.imageSize")
|| id == "actions.reset" && p.get("mode").is_some_and(|v| v == "append")
{
Err(EngineError::Other("choice denied".into()))
} else {
Ok(())
}
}
/// The chooser is not pre-authorized as the default command the user might never select.
#[test]
fn menu_chooser_authorizes_the_selected_command_without_default_probe() {
let mut h = harness();
h.state_mut().session.authorize = Some(chosen_only);
let dialog = open(&mut h, "Insert Menu Item…");
h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("id".into(), json!("filter.blur.gaussianBlur"));
dialogs::confirm(h.state_mut(), dialog).unwrap();
assert_eq!(h.state().session.actions.list[0].steps.len(), 1);
let dialog = open(&mut h, "Insert Menu Item…");
assert!(dialogs::confirm(h.state_mut(), dialog).is_err());
assert_eq!(h.state().session.actions.list[0].steps.len(), 1);
}
/// Replace must remain reachable when the policy refuses Reset's append option.
#[test]
fn reset_offers_allowed_replace_when_append_is_denied() {
let mut h = harness();
h.state_mut().session.authorize = Some(chosen_only);
let dialog = open(&mut h, "Reset Actions…");
assert_eq!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields["mode"], "replace");
dialogs::confirm(h.state_mut(), dialog).unwrap();
assert!(h.state().session.actions.list.is_empty());
assert_eq!(h.state().session.actions.sets, [actions_edit_cmds::DEFAULT_SET_PLACEHOLDER]);
}
@@ -177,3 +177,18 @@ fn another_dialog_cannot_consume_the_pending_replacement() {
assert_eq!(h.state().session.actions.list[0].name, "New");
assert_eq!(h.state().session.actions.list.len(), 1);
}
/// Replacing a library removes its collapsed set names even when the replacement reuses one.
#[test]
fn replacing_library_reveals_reused_set_names() {
let (mut h, picker) = harness();
h.state_mut().ui.actions.collapsed_sets = vec!["One".into(), "Two".into(), "Old Empty".into(), "Remember".into()];
pick(&mut h, &picker);
let action = Action::new("New", vec![("select.all".into(), json!({}))]);
let bytes = atn_cmds::export("One", &[&action], &[], false).unwrap().0;
answer(&mut h, &picker, Some(FileDialogAnswer::Contents("Replacement.atn".into(), bytes)));
let dialog = h.state().ui.dialogs.last().unwrap().id;
dialogs::confirm(h.state_mut(), dialog).unwrap();
assert_eq!(h.state().session.actions.list[0].set.as_deref(), Some("One"));
assert_eq!(h.state().ui.actions.collapsed_sets, ["Remember"]);
}
+144 -1
View File
@@ -1,7 +1,7 @@
//! Play a descriptor-free Image Size through its actual dialog and Actions continuation.
use egui_kittest::{Harness, kittest::Queryable};
use photocraft_engine::{EngineError, Session, actions_cmds::Action, atn_cmds};
use photocraft_ui_egui::{PhotocraftApp, dialogs};
use photocraft_ui_egui::{PhotocraftApp, actions, canvas, control, dialogs};
use serde_json::{Value, json};
/// Import a menu step and append a selection step to expose continuation ordering.
@@ -93,3 +93,146 @@ fn menu_item_confirmation_keeps_the_playback_gate_after_the_request_ends() {
assert_eq!(app.session.active().unwrap().revision, revision);
assert!(app.session.active().unwrap().doc.selection.is_none());
}
/// A retained policy does not itself make native playback programmatic.
fn permit(_: &str, _: &Value) -> photocraft_engine::Result<()> {
Ok(())
}
/// Real engine.execute requests refuse unconfigured menu intent even without an installed gate.
#[test]
fn control_menu_intent_requires_interaction_with_default_and_gated_services() {
for gated in [false, true] {
let mut app = app();
app.background_jobs = false;
if gated {
app.services.automation_authorize = Some(permit);
}
let revision = app.session.active().unwrap().revision;
let ctx = egui::Context::default();
let (request, _) = control::ControlRequest::new("engine.execute", json!({"command":"actions.play","params":{"action":"Menu"}}));
let control::Outcome::Done(response) = control::handle(&mut app, &ctx, &request) else { panic!("immediate action response") };
assert_eq!(response["ok"], true, "{response}");
let result = &response["result"];
assert!(result["failed"]["error"].as_str().is_some_and(|e| e.contains("interactive-required")), "{response}");
assert!(result.get("paused").is_none());
assert!(app.ui.dialogs.is_empty());
assert_eq!(app.session.active().unwrap().revision, revision);
app.session.authorize = Some(permit);
let paused = app.run("actions.play", json!({"action":"Menu"})).unwrap();
dialogs::cancel(&mut app, paused["paused"]["dialog"].as_u64().unwrap()).unwrap();
}
}
/// Recorded settings remain executable by the actual headless request path.
#[test]
fn control_recorded_settings_ignore_the_native_dialog_toggle() {
let mut app = app();
app.background_jobs = false;
app.session.actions.list[0].steps[0] = ("image.imageSize".into(), json!({"width":4,"height":3,"resample":"nearest"}));
app.session.actions.list[0].dialogs.insert(0);
let (request, _) = control::ControlRequest::new("engine.execute", json!({"command":"actions.play","params":{"action":"Menu"}}));
let control::Outcome::Done(result) = control::handle(&mut app, &egui::Context::default(), &request) else { panic!("immediate action response") };
assert_eq!(result["result"]["ran"], 2, "{result}");
assert!(app.ui.dialogs.is_empty());
assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(4, 3));
}
/// Window Arrange's real cell activation must not retarget a paused Image Size confirmation.
#[test]
fn arranged_document_switch_cannot_retarget_paused_menu_confirmation() {
let mut app = app();
app.background_jobs = false;
app.run("file.new", json!({"width":20,"height":10})).unwrap();
app.session.set_active(0);
app.ui.view.arrange = "twoUpVertical".into();
app.ui.tool = photocraft_ui_egui::state::Tool::Hand;
let mut h = Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
// The harness draws once before setup_context installs the app's named fonts.
if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
canvas::document_area(app, ui);
dialogs::show(app, ui.ctx());
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(3);
let paused = h.state_mut().run("actions.play", json!({"action":"Menu"})).unwrap();
let dialog = paused["paused"]["dialog"].as_u64().unwrap();
let fields = &mut h.state_mut().ui.dialog_mut(dialog).unwrap().fields;
fields.insert("width".into(), json!(4));
fields.insert("height".into(), json!(3));
let before: Vec<_> = h.state().session.documents().iter().map(|s| (s.doc.id, s.doc.size, s.revision)).collect();
let pos = egui::pos2(1050.0, 850.0);
h.event(egui::Event::PointerMoved(pos));
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
assert_eq!(h.state().session.active_index(), Some(1), "the real arranged-cell producer activated the other document");
assert!(dialogs::confirm(h.state_mut(), dialog).is_err());
assert_eq!(h.state().session.documents().iter().map(|s| (s.doc.id, s.doc.size, s.revision)).collect::<Vec<_>>(), before);
assert!(h.state().session.documents().iter().all(|s| s.doc.selection.is_none()));
h.state_mut().session.set_active(0);
dialogs::confirm(h.state_mut(), dialog).unwrap();
assert_eq!(h.state().session.documents()[0].doc.size, photocraft_doc::Size::new(4, 3));
assert!(h.state().session.documents()[0].doc.selection.is_some());
}
/// A stale resume cannot run its following selection on another document; later intentional New remains valid.
#[test]
fn paused_resume_checks_owner_before_later_document_changing_steps() {
let mut app = app();
app.background_jobs = false;
app.run("file.new", json!({"width":20,"height":10})).unwrap();
app.session.set_active(0);
app.session.actions.list[0].steps.insert(1, ("file.new".into(), json!({"width":3,"height":2})));
let paused = app.run("actions.play", json!({"action":"Menu"})).unwrap();
let dialog = paused["paused"]["dialog"].as_u64().unwrap();
let fields = app.ui.dialog_mut(dialog).unwrap().fields.clone();
app.session.set_active(1);
assert!(actions::resume(&mut app, &fields).is_err());
assert_eq!(app.session.documents().len(), 2);
assert!(app.session.active().unwrap().doc.selection.is_none());
app.session.set_active(0);
dialogs::confirm(&mut app, dialog).unwrap();
assert_eq!(app.session.documents().len(), 3);
assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(3, 2));
assert!(app.session.active().unwrap().doc.selection.is_some());
}
static PREVIEW_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// Count actual preview evaluations while retaining permission for the originating document.
fn count_preview(id: &str, _: &Value) -> photocraft_engine::Result<()> {
if id == "filter.blur.gaussianBlur" {
PREVIEW_CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
Ok(())
}
/// A paused filter preview cannot evaluate its parameters on a different active document.
#[test]
fn paused_filter_preview_stays_with_its_document() {
use std::sync::atomic::Ordering;
let mut app = app();
app.background_jobs = false;
app.run("file.new", json!({"width":20,"height":10})).unwrap();
app.session.set_active(0);
app.session.actions.list[0].steps[0].1["id"] = json!("filter.blur.gaussianBlur");
app.session.authorize = Some(count_preview);
let paused = app.run("actions.play", json!({"action":"Menu"})).unwrap();
let dialog = paused["paused"]["dialog"].as_u64().unwrap();
let ctx = egui::Context::default();
PhotocraftApp::setup_context(&ctx, Default::default());
PREVIEW_CALLS.store(0, Ordering::SeqCst);
assert!(canvas::ensure_texture(&mut app, &ctx, 0, None).is_some());
assert!(PREVIEW_CALLS.load(Ordering::SeqCst) > 0, "same-owner preview evaluated");
app.session.set_active(1);
PREVIEW_CALLS.store(0, Ordering::SeqCst);
canvas::ensure_texture(&mut app, &ctx, 1, None);
assert_eq!(PREVIEW_CALLS.load(Ordering::SeqCst), 0, "foreign document must not evaluate the paused filter");
assert!(dialogs::confirm(&mut app, dialog).is_err());
}