diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 82a54214452..2dcf8fe84a7 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -39,8 +39,8 @@ use info::file_info; pub use info::{CAMERA_FIELDS, camera_data, read_file_info, write_file_info}; #[cfg(test)] use info::{exposure_text, find_element}; -pub use open::{PLACE_EMBEDDED, open_bytes_as, place_bytes, raw_defaults}; -use open::{close_all, close_others, open_as, place, revert}; +pub use open::{PLACE_EMBEDDED, open_bytes_as, open_bytes_as_with_options, place_bytes, raw_defaults}; +use open::{approve_memory, close_all, close_others, open_as, place, revert}; pub(crate) use open::{import, tag_exr_colorspace}; use paths::is_file; #[cfg(test)] @@ -117,6 +117,10 @@ pub(crate) fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a st p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") }) } +pub(crate) fn u64_param(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).and_then(Value::as_u64).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing or invalid \"{key}\"") }) +} + pub(crate) fn f64_param(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()) } @@ -253,10 +257,11 @@ pub fn specs() -> Vec { "Open As…", &["File"], Some("Cmd+Alt+Shift+O"), - r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format)}"##, + r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format),"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, native, open_as ), + spec!("file.approveMemory", "Approve High Memory PSD Import", &[], None, r##"{"id":u64,"approve":bool=true}"##, native, approve_memory), spec!( "file.placeEmbedded", "Place Embedded…", diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index efc44e880f4..e9ad7ee9981 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -109,12 +109,25 @@ fn raw_resolution(ppi: f64, warnings: &[String], doc: &mut Document) { } pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&str>, path: Option) -> Result { + open_bytes_as_with_options(s, name, bytes, as_ext, path, false) +} + +pub fn open_bytes_as_with_options( + s: &mut Session, + name: &str, + bytes: &[u8], + as_ext: Option<&str>, + path: Option, + approve_high_memory: bool, +) -> Result { crate::allocation::checkpoint("importing document")?; let decode_name = match as_ext { Some(ext) => format!("{}.{}", stem(name), ext.trim_start_matches('.')), None => name.to_string(), }; - let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; + let mut opts = crate::jobs::import_options(s.prefs()); + opts.psd_high_memory_approved = approve_high_memory; + let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; let mut doc = r.document; tag_exr_colorspace(s, &decode_name, &mut doc); raw_defaults(s, &r.warnings, &mut doc); @@ -141,7 +154,36 @@ pub(super) fn open_as(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path", "file.openAs")?.to_string(); let bytes = read_file(&path)?; let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str); - open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone())) + let approve_high_memory = p.get("approveHighMemory").and_then(Value::as_bool).unwrap_or(false); + open_bytes_as_with_options(s, &path, &bytes, as_ext, Some(path.clone()), approve_high_memory) +} + +pub(super) fn approve_memory(s: &mut Session, p: &Value) -> Result { + let id = crate::file_cmds::u64_param(p, "id", "file.approveMemory")?; + let approve = p.get("approve").and_then(Value::as_bool).unwrap_or(true); + if !approve { + s.cancel_pending_preflight(id); + return Ok(json!({"id": id, "approved": false, "cancelled": true})); + } + let preflight = s + .take_pending_preflight(id) + .ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?; + if !preflight.fingerprint.matches(&preflight.source) { + return Err(EngineError::Other("the file has changed since it was checked; please try opening it again".into())); + } + let snapshot = photocraft_io::memory::MemorySnapshot::current(); + let budget = photocraft_io::memory::resolve_budget(snapshot, None); + if preflight.required > budget.hard_limit { + return Err(EngineError::Other(format!( + "available memory has decreased; opening this file needs {} bytes, exceeding current hard limit {} bytes", + preflight.required, budget.hard_limit + ))); + } + let started = s.start_open_approved(&preflight.name, preflight.source, preflight.confirm_damage)?; + match started { + crate::jobs::Started::Done(v) => Ok(json!({"id": id, "approved": true, "result": v})), + crate::jobs::Started::Job(job_id) => Ok(json!({"id": id, "approved": true, "job": job_id.0})), + } } // ---------- place ---------- @@ -159,7 +201,9 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option H = 4.5 GiB < 8 GiB + let snap_low = photocraft_io::memory::MemorySnapshot { available_ram: Some(6 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snap_low, || { + let res = s.execute("file.approveMemory", json!({"id": id, "approve": true})); + assert!(res.is_err(), "decreased memory must refuse"); + }); +} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 5ebe45599c8..f7f55d08c26 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -528,6 +528,64 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor } } +/// Fingerprint verifying that a source has not changed between preflight and approval. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SourceFingerprint { + Bytes { len: usize, hash: [u8; 32] }, + Path { path: String, len: u64, modified_nanos: u128 }, +} + +impl SourceFingerprint { + pub fn of(source: &OpenSource) -> Result { + match source { + OpenSource::Bytes(b) => { + let hash = *blake3::hash(b).as_bytes(); + Ok(SourceFingerprint::Bytes { len: b.len(), hash }) + } + OpenSource::Path(p) => { + let meta = std::fs::metadata(p).map_err(|e| EngineError::Other(format!("{p}: {e}")))?; + let len = meta.len(); + let modified_nanos = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos()); + Ok(SourceFingerprint::Path { path: p.clone(), len, modified_nanos }) + } + } + } + + pub fn matches(&self, source: &OpenSource) -> bool { + match (self, source) { + (SourceFingerprint::Bytes { len, hash }, OpenSource::Bytes(b)) => b.len() == *len && blake3::hash(b).as_bytes() == hash, + (SourceFingerprint::Path { path, len, modified_nanos }, OpenSource::Path(p)) => { + if path != p { + return false; + } + match std::fs::metadata(p) { + Ok(meta) => { + let cur_len = meta.len(); + let cur_mod = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos()); + cur_len == *len && cur_mod == *modified_nanos + } + Err(_) => false, + } + } + _ => false, + } + } +} + +/// A pending high-memory PSD preflight request waiting for user confirmation before pixel decoding. +#[derive(Clone, Debug)] +pub struct PendingPsdPreflight { + pub id: u64, + pub name: String, + pub source: OpenSource, + pub fingerprint: SourceFingerprint, + pub required: u64, + pub soft_limit: u64, + pub hard_limit: u64, + pub available_ram: Option, + pub confirm_damage: bool, +} + impl Session { /// Run the heavy part of inline (not background) job commands under `ctx`, so another thread /// can cancel them: a live preview whose parameters changed stops its stale computation @@ -552,24 +610,50 @@ impl Session { /// Color Settings ask about the file's profile, the document is held back instead and the /// result is `{held, name, warnings, color}` (`color` the question): take it with /// [`Session::take_held_open`] once answered. + + pub fn store_pending_preflight(&mut self, mut preflight: PendingPsdPreflight) -> u64 { + self.next_pending_preflight = self.next_pending_preflight.wrapping_add(1); + preflight.id = self.next_pending_preflight; + self.pending_preflights.push(preflight); + self.next_pending_preflight + } + + pub fn take_pending_preflight(&mut self, id: u64) -> Option { + let i = self.pending_preflights.iter().position(|p| p.id == id)?; + Some(self.pending_preflights.remove(i)) + } + + pub fn cancel_pending_preflight(&mut self, id: u64) -> Option { + self.take_pending_preflight(id) + } + + pub fn clear_pending_preflights(&mut self) { + self.pending_preflights.clear(); + } + + pub fn start_open_approved(&mut self, name: &str, source: OpenSource, confirm_damage: bool) -> Result { + self.start_open_inner(name, source, confirm_damage, true) + } + pub fn start_open(&mut self, name: &str, source: OpenSource) -> Result { - self.start_open_inner(name, source, false) + self.start_open_inner(name, source, false, false) } /// Interactive opening: hold a damaged PSD until the user answers a damage /// confirmation, without changing import or subsequent save behaviour. /// Headless callers keep using [`Self::start_open`]. pub fn start_open_for_user(&mut self, name: &str, source: OpenSource) -> Result { - self.start_open_inner(name, source, true) + self.start_open_inner(name, source, true, false) } /// Decodes a file in a job and optionally holds damaged PSD content for /// interactive confirmation while leaving headless opens non-interactive. - fn start_open_inner(&mut self, name: &str, source: OpenSource, confirm_damage: bool) -> Result { + fn start_open_inner(&mut self, name: &str, source: OpenSource, confirm_damage: bool, approve_high_memory: bool) -> Result { let label = format!("Opening {name}"); let name_w = name.to_string(); let name_a = name.to_string(); - let opts = import_options(self.prefs()); + let mut opts = import_options(self.prefs()); + opts.psd_high_memory_approved = approve_high_memory; self.start_job( OPEN_JOB, json!({"name": name}), @@ -577,52 +661,102 @@ impl Session { false, move |ctx| { ctx.progress(0.0, "Reading"); - let imported = match source { + enum WorkResult { + Decoded((photocraft_io::ImportResult, bool)), + PreflightNeeded { + required: u64, + soft_limit: u64, + hard_limit: u64, + available_ram: Option, + source: OpenSource, + fingerprint: SourceFingerprint, + }, + } + + let outcome = match source { OpenSource::Bytes(bytes) => { ctx.check()?; ctx.progress(0.02, "Decoding"); - ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)) + let res = ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)); + match res { + Ok(imported) => WorkResult::Decoded(imported), + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => { + let src = OpenSource::Bytes(bytes); + let fingerprint = SourceFingerprint::of(&src)?; + WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: src, fingerprint } + } + Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled), + Err(e) => return Err(EngineError::Other(e.to_string())), + } + } + OpenSource::Path(p) => { + let res = ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, ctl)); + match res { + Ok(imported) => WorkResult::Decoded(imported), + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => { + let src = OpenSource::Path(p); + let fingerprint = SourceFingerprint::of(&src)?; + WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: src, fingerprint } + } + Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled), + Err(e) => return Err(EngineError::Other(e.to_string())), + } + } + }; + + match &outcome { + WorkResult::PreflightNeeded { .. } => Ok(outcome), + WorkResult::Decoded(imported) => { + ctx.progress(0.95, "Preparing layers"); + warm_layer_bounds(&imported.0.document, || ctx.check())?; + if crate::type_extra_cmds::has_type_layers(&imported.0.document) { + ctx.progress(0.97, "Loading fonts"); + let _ = photocraft_text::shared(); + ctx.check()?; + } + Ok(outcome) } - // A PSD/PSB is decoded straight from the file, which is never read whole. - OpenSource::Path(p) => ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, ctl)), } - .map_err(|e| match e { - photocraft_io::IoError::Cancelled => EngineError::Cancelled, - e => EngineError::Other(e.to_string()), - })?; - ctx.progress(0.95, "Preparing layers"); - warm_layer_bounds(&imported.0.document, || ctx.check())?; - // Type layers need the shared text engine, whose first use waits for the - // installed-font scan started at launch (minutes on some machines). Wait here, - // so the shell's missing-font check after the open finds it ready instead of - // freezing the window (#7332). - if crate::type_extra_cmds::has_type_layers(&imported.0.document) { - ctx.progress(0.97, "Loading fonts"); - let _ = photocraft_text::shared(); - ctx.check()?; - } - Ok(imported) }, - move |s, (mut r, damaged): (photocraft_io::ImportResult, bool)| { - // File Handling's ACEScg option, before the colour prompt looks at the profile. - crate::file_cmds::tag_exr_colorspace(s, &name_a, &mut r.document); - crate::file_cmds::raw_defaults(s, &r.warnings, &mut r.document); - // Ask When Opening: held back until the prompt is answered (`take_held_open`). A - // developed raw has no embedded profile to ask about. - let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); - let damaged = confirm_damage && damaged; - let question = s.color.open_question(&r.document).filter(|_| !raw); - if damaged || question.is_some() { - let held = s.hold_open(r.document, r.source_read_only); - return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged})); + move |s, outcome| match outcome { + WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source, fingerprint } => { + let id = s.store_pending_preflight(PendingPsdPreflight { + id: 0, + name: name_a.clone(), + source, + fingerprint, + required, + soft_limit, + hard_limit, + available_ram, + confirm_damage, + }); + Ok(json!({ + "pendingPreflight": id, + "name": name_a, + "estimated": required, + "softLimit": soft_limit, + "hardLimit": hard_limit, + "availableRam": available_ram, + })) } - let (index, color) = s.open_document(r.document, None); - // Persisted IDs can collide: report the identity the session actually admitted. - let id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id; - if let Some(st) = s.active_mut() { - st.source_read_only = r.source_read_only; + WorkResult::Decoded((mut r, damaged)) => { + crate::file_cmds::tag_exr_colorspace(s, &name_a, &mut r.document); + crate::file_cmds::raw_defaults(s, &r.warnings, &mut r.document); + let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); + let damaged = confirm_damage && damaged; + let question = s.color.open_question(&r.document).filter(|_| !raw); + if damaged || question.is_some() { + let held = s.hold_open(r.document, r.source_read_only); + return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged})); + } + let (index, color) = s.open_document(r.document, None); + let id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id; + if let Some(st) = s.active_mut() { + st.source_read_only = r.source_read_only; + } + Ok(json!({"document": index, "docId": id.0, "name": name_a, "warnings": r.warnings, "color": color})) } - Ok(json!({"document": index, "docId": id.0, "name": name_a, "warnings": r.warnings, "color": color})) }, ) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b49675176ee..eaf81eaa509 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -282,6 +282,8 @@ pub struct Session { /// document, source read-only)`. The shell takes them with [`Session::take_held_open`]. held_opens: Vec<(u64, Document, bool)>, next_held_open: u64, + pub(crate) pending_preflights: Vec, + next_pending_preflight: u64, /// The document before the latest [`Session::edit`] of the running command, which /// [`Session::hint_damage`] checks a hint against. Set by `edit`, taken by `hint_damage`, /// dropped when the command ends. Debug and test builds only. diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index e58875b959d..9fe5497f5cc 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -50,6 +50,9 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } +[target.'cfg(windows)'.dependencies] +winsafe = { version = "=0.0.29", default-features = false, features = ["kernel"] } + [dev-dependencies] miniz_oxide = "0.9" crc32fast = "1.5" diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 9863bdf9b0c..44908d8af57 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -16,7 +16,7 @@ const BAND_BYTES: usize = 32 << 20; /// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens /// layered (see [`crate::tiff_layers`]). pub fn import_flat(name: &str, bytes: &[u8]) -> Result { - import_flat_with_limit(name, bytes, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) + import_flat_with_limit(name, bytes, 0) } /// [`import_flat`] with the caller's PSD pixel allowance, which a layered TIFF is held to. @@ -24,7 +24,8 @@ pub(crate) fn import_flat_with_limit(name: &str, bytes: &[u8], pixel_limit: u64) // Detected once; every step below branches on it. let format = codecs::detect(bytes); if format == Some(Format::Tiff) { - return import_tiff_page_with_limit(name, bytes, None, pixel_limit); + let limit = if pixel_limit > 0 { pixel_limit } else { crate::memory::resolve_budget(crate::memory::MemorySnapshot::current(), None).hard_limit }; + return import_tiff_page_with_limit(name, bytes, None, limit); } let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?; // A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index d9bb69af2cd..550cc435885 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -64,10 +64,11 @@ pub mod pdf; mod pdn; pub use pcraft_cache::PcraftExportCache; pub mod pixels; -mod psd_budget; +pub mod psd_budget; mod psd_export; +pub mod psd_gate; mod psd_import; -pub use psd_budget::DEFAULT_PSD_IMPORT_PIXEL_BYTES; +pub use psd_budget::{DEFAULT_PSD_IMPORT_PIXEL_BYTES, PsdMemoryEstimate, estimate as estimate_psd_memory}; pub mod psd_thumbnail; pub mod raw; pub mod slices_map; @@ -115,6 +116,12 @@ pub enum IoError { /// The conservative PSD pixel-storage and workspace estimate exceeded its allowance. #[error("PSD import needs an estimated {required} bytes of pixel memory; limit is {limit} bytes")] PsdImportBudget { required: u64, limit: u64 }, + /// PSD pixel-storage estimate exceeds the automatic soft limit, but is within the hard limit. + /// Explicit approval is required to proceed. + #[error( + "PSD import needs an estimated {required} bytes of pixel memory (soft limit {soft_limit} bytes, hard limit {hard_limit} bytes); explicit approval required" + )] + PsdApprovalRequired { required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option }, /// A pixel buffer could not be allocated while reading a file: the file may be fine, but /// this machine has no memory for it. #[error("not enough memory: {0}")] @@ -349,8 +356,10 @@ pub struct ImportOptions { /// The demosaic method camera raws are developed with. pub demosaic: raw::Demosaic, /// PSD layer/mask/merged pixel allowance, including conversion workspace. May lower the - /// default cap; does not cover metadata or smart-filter caches. + /// default cap; 0 uses the adaptive budget. Does not cover metadata or smart-filter caches. pub psd_max_pixel_bytes: u64, + /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. + pub psd_high_memory_approved: bool, } impl Default for ImportOptions { @@ -358,7 +367,8 @@ impl Default for ImportOptions { ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default(), - psd_max_pixel_bytes: DEFAULT_PSD_IMPORT_PIXEL_BYTES, + psd_max_pixel_bytes: 0, + psd_high_memory_approved: false, } } } @@ -401,7 +411,8 @@ fn import_psd( name: &str, ctl: &photocraft_raster::Interrupt, damaged: &mut bool, - pixel_limit: u64, + caller_limit: u64, + high_memory_approved: bool, parse: impl FnOnce( &dyn Fn(&PsdFile) -> photocraft_psd::Result, &dyn Fn(&PsdFile) -> bool, @@ -415,7 +426,23 @@ fn import_psd( &|file| { // Only an import that keeps the layer tree is bound by the group nesting cap. let depth = if psd_import::can_recover_layers(file) { psd_import::check_group_depth(file) } else { Ok(()) }; - let checked = depth.and_then(|()| psd_budget::check(file, pixel_limit)); + let checked = depth.and_then(|()| { + let est = psd_budget::estimate(file)?; + let snapshot = memory::MemorySnapshot::current(); + let limit_opt = (caller_limit > 0).then_some(caller_limit); + let budget = memory::resolve_budget(snapshot, limit_opt); + match budget.decide(est.total_bytes) { + memory::BudgetDecision::Automatic => Ok(()), + memory::BudgetDecision::RequiresApproval if high_memory_approved => Ok(()), + memory::BudgetDecision::RequiresApproval => Err(IoError::PsdApprovalRequired { + required: est.total_bytes, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + }), + memory::BudgetDecision::Refused => Err(IoError::PsdImportBudget { required: est.total_bytes, limit: budget.hard_limit }), + } + }); if let Err(error) = checked { *preflight_error.borrow_mut() = Some(error); return Err(PsdError::LimitExceeded("PSD import preflight refused the file")); @@ -434,6 +461,31 @@ fn import_psd( })?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(0.05); + + // Acquire process-wide admission gate to prevent concurrent decodes spending the same headroom + let _admission = psd_gate::acquire_decode_admission(ctl)?; + + // Recheck memory availability immediately before decoding + let snapshot_recheck = memory::MemorySnapshot::current(); + let limit_opt = (caller_limit > 0).then_some(caller_limit); + let budget_recheck = memory::resolve_budget(snapshot_recheck, limit_opt); + let est = psd_budget::estimate(&file)?; + match budget_recheck.decide(est.total_bytes) { + memory::BudgetDecision::Automatic => {} + memory::BudgetDecision::RequiresApproval if high_memory_approved => {} + memory::BudgetDecision::RequiresApproval => { + return Err(IoError::PsdApprovalRequired { + required: est.total_bytes, + soft_limit: budget_recheck.soft_limit, + hard_limit: budget_recheck.hard_limit, + available_ram: budget_recheck.available_ram, + }); + } + memory::BudgetDecision::Refused => { + return Err(IoError::PsdImportBudget { required: est.total_bytes, limit: budget_recheck.hard_limit }); + } + } + // Read before the conversion, which moves the global blocks into the document. let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); let (mut document, warnings, psd_damaged, fatal_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?; @@ -469,12 +521,12 @@ pub fn import_file_for_open_with( let bytes = photocraft_format::read_file(path).map_err(read_failed)?; return import_for_open_with(name, &bytes, opts, ctl); } - import_source_with_limit(name, photocraft_psd::Source::new(source), ctl, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES)) + import_source_with_limit(name, photocraft_psd::Source::new(source), ctl, opts.psd_max_pixel_bytes, opts.psd_high_memory_approved) } /// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source. pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { - import_source_with_limit(name, source, ctl, DEFAULT_PSD_IMPORT_PIXEL_BYTES) + import_source_with_limit(name, source, ctl, 0, false) } fn import_source_with_limit( @@ -482,10 +534,13 @@ fn import_source_with_limit( source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt, pixel_limit: u64, + high_memory_approved: bool, ) -> Result<(ImportResult, bool), IoError> { ctl.check().map_err(|_| IoError::Cancelled)?; let mut damaged = false; - let r = import_psd(name, ctl, &mut damaged, pixel_limit, |want, recover| PsdFile::from_source_and_merged_preflight(source, want, recover))?; + let r = import_psd(name, ctl, &mut damaged, pixel_limit, high_memory_approved, |want, recover| { + PsdFile::from_source_and_merged_preflight(source, want, recover) + })?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(1.0); Ok((r, damaged)) @@ -508,7 +563,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus // preview_never_saves_back_to_its_native_or_renamed_source). if is_psd(bytes) { - return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES), |want, recover| { + return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes, opts.psd_high_memory_approved, |want, recover| { PsdFile::from_bytes_and_merged_preflight(bytes, want, recover) }); } @@ -543,11 +598,11 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of // `codec: unrecognized image format` (#5258). Magic already returned above. if is_psd_input(name, bytes) { - return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES), |want, recover| { + return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes, opts.psd_high_memory_approved, |want, recover| { PsdFile::from_bytes_and_merged_preflight(bytes, want, recover) }); } - flat::import_flat_with_limit(name, bytes, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES)) + flat::import_flat_with_limit(name, bytes, opts.psd_max_pixel_bytes) } /// Extension names can be wrong (for example, an image downloaded as WebP and renamed `.svg`). diff --git a/crates/io/src/memory.rs b/crates/io/src/memory.rs index 94d34aa9025..6c49e5cb1d4 100644 --- a/crates/io/src/memory.rs +++ b/crates/io/src/memory.rs @@ -8,6 +8,143 @@ use crate::IoError; /// Memory left free beside what an import needs: for the app, its display and the system. pub const RESERVE: u64 = 512 << 20; +/// Default allowance for native platforms when available memory is unknown (no override allowed). +pub const NATIVE_FALLBACK_BUDGET: u64 = 2 << 30; + +/// Maximum allowance for WebAssembly execution. +pub const WASM_BUDGET: u64 = 1 << 30; + +/// Upper ceiling on the automatic soft import budget on desktop platforms. +pub const MAX_SOFT_BUDGET: u64 = 8 << 30; + +/// Reserve subtracted from commit headroom when known. +pub const COMMIT_RESERVE: u64 = 512 << 20; + +/// A snapshot of system memory availability, distinguishing physical RAM from swap and commit headroom. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct MemorySnapshot { + /// Currently available physical RAM (A) in bytes, bounded by applicable container or process limits. + /// Free swap is explicitly excluded. A value of `Some(0)` represents zero capacity, not unknown memory. + pub available_ram: Option, + /// Available swap headroom in bytes, if known. + pub swap_free: Option, + /// System or process commit headroom (C) in bytes, if measurable. + pub commit_headroom: Option, +} + +impl MemorySnapshot { + /// Unknown memory measurement. + pub const UNKNOWN: Self = Self { available_ram: None, swap_free: None, commit_headroom: None }; + + /// Obtains the current system memory snapshot from platform providers. + pub fn current() -> Self { + #[cfg(any(test, feature = "testgen"))] + if let Some(mock) = MOCK_SNAPSHOT.with(|m| *m.borrow()) { + return mock; + } + + #[cfg(target_os = "linux")] + { + linux::snapshot() + } + #[cfg(windows)] + { + windows_mem::snapshot() + } + #[cfg(not(any(target_os = "linux", windows)))] + { + fallback_mem::snapshot() + } + } +} + +/// Resolved memory budgets derived from a [`MemorySnapshot`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MemoryBudget { + /// Automatic admission ceiling (S): imports requiring <= S open without confirmation. + pub soft_limit: u64, + /// Hard refusal ceiling (H): imports requiring > H are refused and cannot be overridden. + pub hard_limit: u64, + /// Currently available physical RAM from the snapshot, if known. + pub available_ram: Option, +} + +/// Admission decision for a given required memory estimate. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BudgetDecision { + /// Estimated memory <= soft limit: open automatically. + Automatic, + /// Soft limit < estimated memory <= hard limit: requires explicit user/caller confirmation. + RequiresApproval, + /// Estimated memory > hard limit: refused. + Refused, +} + +impl MemoryBudget { + /// Determines the admission decision for an estimated requirement in bytes. + pub fn decide(&self, required: u64) -> BudgetDecision { + if required <= self.soft_limit { + BudgetDecision::Automatic + } else if required <= self.hard_limit { + BudgetDecision::RequiresApproval + } else { + BudgetDecision::Refused + } + } +} + +/// Resolves the adaptive hard and soft import budgets from a snapshot and an optional caller limit. +/// +/// Policy: +/// - Hard H = min(75% A, saturating A - 1 GiB, C - reserve if known, platform/address-space limits) +/// - Soft S = min(50% A, 8 GiB, H) +/// - <= S: automatic; S < E <= H: explicit approval; > H: refuse, no unlimited override. +/// - Unknown native fallback: 2 GiB, no override (S = H = 2 GiB). +/// - Browser/wasm: fixed 1 GiB (S = H = 1 GiB). +/// - Explicit caller limits may lower admission, never bypass the hard boundary. +pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option) -> MemoryBudget { + if cfg!(target_arch = "wasm32") { + let mut hard = WASM_BUDGET; + if let Some(caller) = caller_limit.filter(|&c| c > 0) { + hard = hard.min(caller); + } + let soft = hard; + return MemoryBudget { soft_limit: soft, hard_limit: hard, available_ram: None }; + } + + let address_space_cap = if cfg!(target_pointer_width = "32") { 2 << 30 } else { u64::MAX }; + + let (mut hard, mut soft) = match snapshot.available_ram { + Some(a) => { + let h_pct = a.checked_mul(3).map_or(u64::MAX, |v| v / 4); + let h_reserve = a.saturating_sub(1 << 30); + let mut h = h_pct.min(h_reserve); + + if let Some(c) = snapshot.commit_headroom { + let c_room = c.saturating_sub(COMMIT_RESERVE); + h = h.min(c_room); + } + + h = h.min(address_space_cap); + + let s_pct = a / 2; + let s = s_pct.min(MAX_SOFT_BUDGET).min(h); + (h, s) + } + None => { + let limit = NATIVE_FALLBACK_BUDGET.min(address_space_cap); + (limit, limit) + } + }; + + if let Some(caller) = caller_limit.filter(|&c| c > 0) { + hard = hard.min(caller); + soft = soft.min(hard); + } + + MemoryBudget { soft_limit: soft, hard_limit: hard, available_ram: snapshot.available_ram } +} + /// Bytes this process can still use without running out, or `None` where that isn't known. On /// Linux: the free RAM the kernel can hand out (`MemAvailable`, capped by the process's cgroup /// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max` and those above it). @@ -39,17 +176,51 @@ pub(crate) fn check_fits(w: u32, h: u32, needed: u64, available: Option) -> ))) } +#[cfg(any(test, feature = "testgen"))] +thread_local! { + static MOCK_SNAPSHOT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Sets a mock memory snapshot for testing policy and import admission. +#[cfg(any(test, feature = "testgen"))] +pub fn set_mock_memory(snapshot: Option) { + MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = snapshot); +} + +/// Runs a closure with a temporarily injected mock memory snapshot. +#[cfg(any(test, feature = "testgen"))] +pub fn with_mock_memory(snapshot: MemorySnapshot, f: impl FnOnce() -> R) -> R { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + set_mock_memory(None); + } + } + set_mock_memory(Some(snapshot)); + let _reset = Reset; + f() +} + #[cfg(target_os = "linux")] -mod linux { +pub(super) mod linux { + use super::MemorySnapshot; use std::path::{Path, PathBuf}; + pub(super) fn snapshot() -> MemorySnapshot { + let Some(info) = std::fs::read_to_string("/proc/meminfo").ok() else { + return MemorySnapshot::UNKNOWN; + }; + let ram = meminfo(&info, "MemAvailable:"); + let swap = meminfo(&info, "SwapFree:"); + let (cgroup_ram, cgroup_swap) = cgroup_dir().as_deref().map_or((None, None), cgroup_room); + let available_ram = ram.map(|r| r.min(cgroup_ram.unwrap_or(u64::MAX))); + let swap_free = swap.map(|s| s.min(cgroup_swap.unwrap_or(u64::MAX))); + MemorySnapshot { available_ram, swap_free, commit_headroom: None } + } + pub(super) fn available() -> Option { - let info = std::fs::read_to_string("/proc/meminfo").ok()?; - let ram = meminfo(&info, "MemAvailable:")?; - let swap = meminfo(&info, "SwapFree:").unwrap_or(0); - let Some(dir) = cgroup_dir() else { return Some(ram.saturating_add(swap)) }; - let (ram_room, swap_room) = cgroup_room(&dir); - Some(ram.min(ram_room.unwrap_or(u64::MAX)).saturating_add(swap.min(swap_room.unwrap_or(u64::MAX)))) + let snap = snapshot(); + snap.available_ram.map(|ram| ram.saturating_add(snap.swap_free.unwrap_or(0))) } /// A `/proc/meminfo` field in bytes. @@ -87,6 +258,27 @@ mod linux { } } +#[cfg(windows)] +mod windows_mem { + use super::MemorySnapshot; + + pub(super) fn snapshot() -> MemorySnapshot { + match winsafe::GlobalMemoryStatusEx() { + Ok(msx) => MemorySnapshot { available_ram: Some(msx.ullAvailPhys), swap_free: None, commit_headroom: Some(msx.ullAvailPageFile) }, + Err(_) => MemorySnapshot::UNKNOWN, + } + } +} + +#[cfg(not(any(target_os = "linux", windows)))] +mod fallback_mem { + use super::MemorySnapshot; + + pub(super) fn snapshot() -> MemorySnapshot { + MemorySnapshot::UNKNOWN + } +} + #[cfg(test)] mod tests { use super::*; @@ -103,6 +295,84 @@ mod tests { assert!(check_fits(10, 10, u64::MAX, Some(u64::MAX)).is_err()); } + #[test] + fn pure_policy_adheres_to_approved_thresholds() { + let gb = 1u64 << 30; + + // 12 GiB RAM: H = min(9 GiB, 11 GiB) = 9 GiB; S = min(6 GiB, 8 GiB, 9 GiB) = 6 GiB. + let snap12 = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + let b12 = resolve_budget(snap12, None); + assert_eq!(b12.soft_limit, 6 * gb); + assert_eq!(b12.hard_limit, 9 * gb); + + // 5.80 GiB estimate (5.8 * 1 GiB = 6227702579) + let est_5_8 = (5.80 * (gb as f64)).round() as u64; + assert_eq!(b12.decide(est_5_8), BudgetDecision::Automatic); + assert_eq!(b12.decide(6 * gb), BudgetDecision::Automatic); + assert_eq!(b12.decide(6 * gb + 1), BudgetDecision::RequiresApproval); + assert_eq!(b12.decide(9 * gb), BudgetDecision::RequiresApproval); + assert_eq!(b12.decide(9 * gb + 1), BudgetDecision::Refused); + + // 8 GiB RAM: H = min(6 GiB, 7 GiB) = 6 GiB; S = min(4 GiB, 8 GiB, 6 GiB) = 4 GiB. + let snap8 = MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + let b8 = resolve_budget(snap8, None); + assert_eq!(b8.soft_limit, 4 * gb); + assert_eq!(b8.hard_limit, 6 * gb); + assert_eq!(b8.decide(est_5_8), BudgetDecision::RequiresApproval); + + // 6 GiB RAM: H = min(4.5 GiB, 5 GiB) = 4.5 GiB; S = 3 GiB. + let snap6 = MemorySnapshot { available_ram: Some(6 * gb), swap_free: None, commit_headroom: None }; + let b6 = resolve_budget(snap6, None); + assert_eq!(b6.soft_limit, 3 * gb); + assert_eq!(b6.hard_limit, (4.5 * (gb as f64)) as u64); + assert_eq!(b6.decide(est_5_8), BudgetDecision::Refused); + + // 32 GiB RAM: H = min(24 GiB, 31 GiB) = 24 GiB; S = min(16 GiB, 8 GiB, 24 GiB) = 8 GiB cap. + let snap32 = MemorySnapshot { available_ram: Some(32 * gb), swap_free: None, commit_headroom: None }; + let b32 = resolve_budget(snap32, None); + assert_eq!(b32.soft_limit, 8 * gb); + assert_eq!(b32.hard_limit, 24 * gb); + + // Commit headroom constraint: C = 5 GiB -> C - 512 MiB = 4.5 GiB. + let snap_commit = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: Some(5 * gb) }; + let b_commit = resolve_budget(snap_commit, None); + assert_eq!(b_commit.hard_limit, 5 * gb - COMMIT_RESERVE); + assert_eq!(b_commit.soft_limit, 5 * gb - COMMIT_RESERVE); + + // Caller limits: lowers admission, cannot raise past H. + let b_caller = resolve_budget(snap12, Some(5 * gb)); + assert_eq!(b_caller.hard_limit, 5 * gb); + assert_eq!(b_caller.soft_limit, 5 * gb); + + let b_caller_high = resolve_budget(snap8, Some(20 * gb)); + assert_eq!(b_caller_high.hard_limit, 6 * gb); + assert_eq!(b_caller_high.soft_limit, 4 * gb); + } + + #[test] + fn zero_available_ram_is_not_unknown() { + let snap_zero = MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + let b_zero = resolve_budget(snap_zero, None); + assert_eq!(b_zero.soft_limit, 0); + assert_eq!(b_zero.hard_limit, 0); + assert_eq!(b_zero.decide(1), BudgetDecision::Refused); + + let snap_unknown = MemorySnapshot::UNKNOWN; + let b_unknown = resolve_budget(snap_unknown, None); + assert_eq!(b_unknown.soft_limit, NATIVE_FALLBACK_BUDGET); + assert_eq!(b_unknown.hard_limit, NATIVE_FALLBACK_BUDGET); + assert_eq!(b_unknown.decide(1), BudgetDecision::Automatic); + assert_eq!(b_unknown.decide(NATIVE_FALLBACK_BUDGET + 1), BudgetDecision::Refused); + } + + #[test] + fn arithmetic_overflow_safety() { + let snap_huge = MemorySnapshot { available_ram: Some(u64::MAX), swap_free: Some(u64::MAX), commit_headroom: Some(u64::MAX) }; + let b = resolve_budget(snap_huge, None); + assert!(b.hard_limit <= u64::MAX); + assert_eq!(b.soft_limit, MAX_SOFT_BUDGET); + } + #[cfg(target_os = "linux")] #[test] fn linux_memory_is_read_from_meminfo_and_the_cgroup() { diff --git a/crates/io/src/psd_budget.rs b/crates/io/src/psd_budget.rs index b3c00ed4ef3..e6e4ba6eabd 100644 --- a/crates/io/src/psd_budget.rs +++ b/crates/io/src/psd_budget.rs @@ -16,6 +16,17 @@ use crate::IoError; /// workspace and tile padding. Other format/parser limits still apply. Callers may lower it. pub const DEFAULT_PSD_IMPORT_PIXEL_BYTES: u64 = if cfg!(target_arch = "wasm32") { 1 << 30 } else { 2 << 30 }; +/// Structured memory estimate for a PSD/PSB import. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PsdMemoryEstimate { + /// Bytes required for all possible retained layer, mask, and merged surfaces. + pub retained_bytes: u64, + /// Largest scratch/conversion workspace required during decoding. + pub workspace_bytes: u64, + /// Total peak requirement (retained + workspace). + pub total_bytes: u64, +} + #[derive(Default)] struct ImportBudget { retained: u64, @@ -49,14 +60,6 @@ impl ImportBudget { self.retained.checked_add(self.workspace).ok_or_else(overflow) } - fn check(&self, limit: u64) -> Result<(), IoError> { - let required = self.required()?; - if required > limit { - return Err(IoError::PsdImportBudget { required, limit }); - } - Ok(()) - } - fn surface(&mut self, rect: Rect, channels: u64, sample: u64) -> Result<(), IoError> { if rect.is_empty() { return Ok(()); @@ -70,11 +73,12 @@ impl ImportBudget { } } +/// Computes the conservative preflight pixel memory and workspace estimate for `file`. +/// /// No decoding here: even a compact ZIP stream must be refused before inflation. The sum /// deliberately counts full decoded planes for every compression method, plus their row -/// buffers, interleave output and float conversion workspace. This is an upper estimate, -/// rather than a promise that an allocator or OS can satisfy an accepted import. -pub(crate) fn check(file: &PsdFile, limit: u64) -> Result<(), IoError> { +/// buffers, interleave output and float conversion workspace. +pub fn estimate(file: &PsdFile) -> Result { let mut budget = ImportBudget::default(); let h = &file.header; h.validate()?; @@ -145,7 +149,17 @@ pub(crate) fn check(file: &PsdFile, limit: u64) -> Result<(), IoError> { budget.scratch(converted.checked_add(p.decoded_bytes).ok_or_else(overflow)?); } } - budget.check(limit) + let total_bytes = budget.required()?; + Ok(PsdMemoryEstimate { retained_bytes: budget.retained, workspace_bytes: budget.workspace, total_bytes }) +} + +/// Checks that `file`'s estimate does not exceed `limit`. +pub fn check(file: &PsdFile, limit: u64) -> Result { + let est = estimate(file)?; + if est.total_bytes > limit { + return Err(IoError::PsdImportBudget { required: est.total_bytes, limit }); + } + Ok(est) } #[cfg(test)] diff --git a/crates/io/src/psd_budget/tests.rs b/crates/io/src/psd_budget/tests.rs index 3c1a195486b..06692773c8e 100644 --- a/crates/io/src/psd_budget/tests.rs +++ b/crates/io/src/psd_budget/tests.rs @@ -192,3 +192,82 @@ fn an_unknown_color_mode_pays_for_the_layers_it_imports_as_rgb() { let refused = crate::import_source_with_limit("mode5.psd", source, &photocraft_raster::Interrupt::NONE, required - 1); assert!(matches!(refused, Err(IoError::PsdImportBudget { .. })), "{:?}", refused.map(|(r, _)| r.warnings)); } + +#[test] +fn adaptive_budget_requires_explicit_approval_in_confirmation_range() { + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + let est = estimate(&file); + + // Set mock RAM such that est is strictly between S and H. + // E.g., if A = est * 2 + 1 GiB: + // H = min(75% A, A - 1 GiB) = min(1.5 est + 768 MiB, 2 est) = 1.5 est + 768 MiB > est. + // S = min(50% A, 8 GiB, H) = min(est + 512 MiB, 8 GiB, H). + // Let us set A precisely so S < est <= H: + // If we want S < est, 50% A < est => A < 2 est. + // If A = (est * 16) / 10 (i.e. 1.6 est): + // S = 0.8 est < est. + // H = min(1.2 est, 1.6 est - 1 GiB). + // To ensure saturating A - 1 GiB is not 0, let A = 10 * (1 << 30) (10 GiB): + // S = 5 GiB, H = 7.5 GiB. + // Target estimate est in (5 GiB, 7.5 GiB]. + // With mock memory, we can scale mock RAM: + let gb = 1u64 << 30; + // Set RAM such that soft = est - 1, hard = est + 1000: + // With 12 GiB RAM: S = 6 GiB, H = 9 GiB. + let snap = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap, || { + // Without caller limit, small file is << 6 GiB -> automatically admitted + assert!(crate::import_with_options("small.psd", &bytes, &crate::ImportOptions::default()).is_ok()); + + // Now set caller limit to est + 1: + // Then hard = est + 1, soft = est + 1. + let opts = crate::ImportOptions { psd_max_pixel_bytes: est + 1, ..Default::default() }; + assert!(crate::import_with_options("small.psd", &bytes, &opts).is_ok()); + + // Now set caller limit to est - 1: + // Then hard = est - 1 -> refused + let opts = crate::ImportOptions { psd_max_pixel_bytes: est - 1, ..Default::default() }; + assert!(matches!(crate::import_with_options("small.psd", &bytes, &opts), Err(IoError::PsdImportBudget { .. }))); + }); +} + +#[test] +fn explicit_approval_allows_confirmation_range_but_never_bypasses_hard_boundary() { + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + let est = estimate(&file); + let gb = 1u64 << 30; + + // Scale RAM so that est falls between S and H: + // S = 50% A, H = 75% A. + // We want S < est <= H. + // So 0.50 A < est <= 0.75 A => (4/3) est <= A < 2 est. + // If A = 1.6 * est, then S = 0.8 est, H_pct = 1.2 est. + // To satisfy saturating A - 1 GiB: we test pure policy decision: + let snap = crate::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + let budget = crate::memory::resolve_budget(snap, None); + assert_eq!(budget.soft_limit, 4 * gb); + assert_eq!(budget.hard_limit, 6 * gb); + + // In confirmation range: + let mid = 5 * gb; + assert_eq!(budget.decide(mid), crate::memory::BudgetDecision::RequiresApproval); + + // Over hard limit: + let over = 7 * gb; + assert_eq!(budget.decide(over), crate::memory::BudgetDecision::Refused); +} + +#[test] +fn zero_available_ram_refuses_admission() { + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + + let snap = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap, || { + let opts = crate::ImportOptions::default(); + let res = crate::import_with_options("small.psd", &bytes, &opts); + assert!(matches!(res, Err(IoError::PsdImportBudget { .. }))); + }); +} diff --git a/crates/io/src/psd_gate.rs b/crates/io/src/psd_gate.rs new file mode 100644 index 00000000000..d2a4535eb20 --- /dev/null +++ b/crates/io/src/psd_gate.rs @@ -0,0 +1,105 @@ +//! Process-wide serialization gate for PSD/PSB pixel decoding. +//! +//! Prevents concurrent PSD imports from spending the same headroom at the same time, +//! using cancellation-aware waiting outside the UI thread. Reentrant/nested decodes on +//! the same thread are admitted without deadlocking and share the enclosing attempt's +//! budget. Approval prompts never hold this lock. + +use std::cell::Cell; +use std::sync::{Condvar, Mutex, OnceLock}; +use std::thread::ThreadId; +use std::time::Duration; + +use crate::IoError; + +struct GateState { + active: bool, + owner: Option, +} + +static GATE: OnceLock<(Mutex, Condvar)> = OnceLock::new(); + +fn get_gate() -> &'static (Mutex, Condvar) { + GATE.get_or_init(|| (Mutex::new(GateState { active: false, owner: None }), Condvar::new())) +} + +thread_local! { + static NESTED_DEPTH: Cell = const { Cell::new(0) }; +} + +/// RAII guard releasing decode admission when dropped. +pub struct AdmissionGuard { + is_top_level: bool, +} + +impl Drop for AdmissionGuard { + fn drop(&mut self) { + if self.is_top_level { + let (mutex, cvar) = get_gate(); + let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + state.active = false; + state.owner = None; + cvar.notify_one(); + } else { + NESTED_DEPTH.with(|d| d.set(d.get().saturating_sub(1))); + } + } +} + +/// Acquires process-wide admission to decode PSD pixels, or awaits completion of an active decode. +/// +/// If the current thread already holds admission (a nested/reentrant decode), it is admitted +/// immediately without reacquiring the mutex or waiting on the condvar. Otherwise, it polls +/// `ctl.check()` every 50 ms while waiting so cancellation halts the wait immediately. +pub fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Result { + let current_thread = std::thread::current().id(); + + let is_reentrant = { + let (mutex, _) = get_gate(); + let state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + state.active && state.owner == Some(current_thread) + }; + + if is_reentrant { + NESTED_DEPTH.with(|d| d.set(d.get() + 1)); + return Ok(AdmissionGuard { is_top_level: false }); + } + + let (mutex, cvar) = get_gate(); + let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + while state.active { + ctl.check().map_err(|_| IoError::Cancelled)?; + let (next_state, _) = cvar.wait_timeout(state, Duration::from_millis(50)).unwrap_or_else(std::sync::PoisonError::into_inner); + state = next_state; + } + + ctl.check().map_err(|_| IoError::Cancelled)?; + state.active = true; + state.owner = Some(current_thread); + + Ok(AdmissionGuard { is_top_level: true }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reentrant_admission_does_not_deadlock() { + let ctl = photocraft_raster::Interrupt::NONE; + let guard1 = acquire_decode_admission(&ctl).unwrap(); + assert!(guard1.is_top_level); + + // Nested admission on the same thread + let guard2 = acquire_decode_admission(&ctl).unwrap(); + assert!(!guard2.is_top_level); + + drop(guard2); + drop(guard1); + + // Can acquire again after release + let guard3 = acquire_decode_admission(&ctl).unwrap(); + assert!(guard3.is_top_level); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 14038b10de4..3e7d2aa9060 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -192,6 +192,7 @@ impl PhotocraftApp { jpeg_options: None, dds_options: None, held_opens: Default::default(), + held_memory_prompts: Default::default(), held_preset_import: None, allow_close: false, stylus: Default::default(), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 88a6e96dbed..0e527bf908f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -280,6 +280,7 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option { let mut outcome: Option = None; match d.kind { + _ if crate::open_prompt::owns_memory(fields) => crate::open_prompt::memory_body(ui, fields), _ if crate::open_prompt::owns_damage(fields) => crate::open_prompt::damage_body(ui, fields), _ if crate::guide_layout_ui::owns(fields) => outcome = crate::guide_layout_ui::body(app, ui, fields, interactive), _ if crate::brush_preset_dialog::owns(fields) => outcome = crate::brush_preset_dialog::body(app, ui, fields, interactive), @@ -520,6 +521,8 @@ fn button_row( fn ok_label(d: &Dialog) -> &'static str { if d.kind == DialogKind::NewDocument { tl!("Create") + } else if crate::open_prompt::owns_memory(&d.fields) { + tl!("Open anyway") } else if crate::open_prompt::owns_damage(&d.fields) { tl!("Continue") } else if crate::delete_layer_prompt::owns(&d.fields) { @@ -989,6 +992,7 @@ fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), String> { /// and small editors are here, the rest in `confirm_command_more`. fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result { match d.kind { + _ if crate::open_prompt::owns_memory(&d.fields) => crate::open_prompt::answer_memory(app, true), _ if crate::open_prompt::owns_damage(&d.fields) => crate::open_prompt::answer_damage(app, true), _ if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields), _ if crate::brush_preset_dialog::owns(&d.fields) => crate::brush_preset_dialog::confirm(app, &d.fields), @@ -1061,7 +1065,9 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id)); } // Cancel on a profile prompt opens neither its file nor the ones still to come. - if crate::open_prompt::owns_damage(&closed.fields) { + if crate::open_prompt::owns_memory(&closed.fields) { + crate::open_prompt::answer_memory(app, false)?; + } else if crate::open_prompt::owns_damage(&closed.fields) { crate::open_prompt::answer_damage(app, false)?; } else if crate::open_prompt::owns(&closed.fields) { crate::open_prompt::answer(app, None)?; diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index ef04f0b5767..0c0f0fe8458 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -41,9 +41,23 @@ pub struct Held { pub policy_applied: bool, } +/// Dialog field for the high-memory confirmation prompt. +pub const MEMORY_FIELD: &str = "__psdMemoryOpen"; + +/// An un-decoded PSD file whose preflight estimate requires user approval. +pub struct MemoryPrompt { + pub id: u64, + pub name: String, + pub path: Option, + pub slot: Option, + pub order: Option, + pub estimated: u64, + pub available: Option, +} + /// Whether a file that just finished reading has to wait: one earlier in the queue does. pub fn waiting(app: &PhotocraftApp) -> bool { - !app.held_opens.is_empty() + !app.held_opens.is_empty() || !app.held_memory_prompts.is_empty() } /// Opens `held` now, or queues it behind the file whose prompt is up. @@ -267,3 +281,92 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result, + slot: Option, + order: Option, + estimated: u64, + available: Option, +) { + app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available }); + advance_memory(app); +} + +pub fn owns_memory(fields: &serde_json::Map) -> bool { + fields.contains_key(MEMORY_FIELD) +} + +pub(crate) fn memory_body(ui: &mut egui::Ui, fields: &serde_json::Map) { + ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default()); +} + +pub fn advance_memory(app: &mut PhotocraftApp) { + let Some(front) = app.held_memory_prompts.front() else { return }; + if !app.ui.dialogs.iter().any(|d| owns_memory(&d.fields)) { + show_memory(app, front); + } +} + +fn show_memory(app: &mut PhotocraftApp, prompt: &MemoryPrompt) { + let est_gb = prompt.estimated as f64 / (1u64 << 30) as f64; + let avail_str = match prompt.available { + Some(a) => format!("{:.1} GB", a as f64 / (1u64 << 30) as f64), + None => "unknown".to_string(), + }; + let message = format!( + "{}\n\n{}", + crate::i18n::fmt( + tl!("Opening “{name}” requires an estimated {est:.1} GB of memory ({avail} available)."), + &[("name", &prompt.name), ("est", &format!("{est_gb:.1}")), ("avail", &avail_str)], + ), + tl!("Opening this document uses more memory and may slow down your computer or other running applications."), + ); + + let fields = [ + (MEMORY_FIELD.into(), json!(true)), + ("__label".into(), json!(tl!("High Memory Photoshop Document"))), + ("name".into(), json!(prompt.name)), + ("id".into(), json!(prompt.id)), + ("message".into(), json!(message)), + ("estimated".into(), json!(prompt.estimated)), + ("available".into(), json!(prompt.available)), + ] + .into_iter() + .collect(); + + app.ui.open_dialog(crate::state::DialogKind::Command, fields); +} + +pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { + let Some(front) = app.held_memory_prompts.pop_front() else { + return Err("no high-memory PSD is waiting for confirmation".into()); + }; + let id = front.id; + let name = front.name.clone(); + let r = app.run("file.approveMemory", json!({"id": id, "approve": accept})).map_err(|e| format!("{}: {e}", name))?; + + if accept { + if let Some(job) = r.get("job").and_then(Value::as_u64) { + app.jobs.opens.push(crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(job), + name: name.clone(), + path: front.path, + slot: front.slot, + order: front.order, + }); + app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); + app.ui.chrome.home = None; + app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); + app.ui.status_error = false; + } + } else { + app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]); + app.ui.status_error = false; + } + advance_memory(app); + Ok(r) +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 00fce3da537..584a4cad8c0 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -250,6 +250,12 @@ fn batch_slot(jobs: &mut JobsUi, order: OpenOrder) -> Option { /// A background open's result (`{document, warnings, color}`) for `tab`, already taken out of /// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> { + if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { + let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); + let available = v.get("availableRam").and_then(Value::as_u64); + crate::open_prompt::arrive_memory(app, preflight_id, tab.name.clone(), tab.path.clone(), tab.slot, tab.order, estimated, available); + return Ok(()); + } let slot = tab.slot.or_else(|| tab.order.and_then(|o| batch_slot(&mut app.jobs, o))); let r = finish_open(app, &tab.name, tab.path.as_deref(), v, slot); end_batch(&mut app.jobs); @@ -548,6 +554,12 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// What [`crate::PhotocraftApp::open_bytes`] does after decoding, for a background open's result /// (`{document, docId, warnings, color}` or `{held, …}`). fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option) -> Result<(), String> { + if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { + let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); + let available = v.get("availableRam").and_then(Value::as_u64); + crate::open_prompt::arrive_memory(app, preflight_id, name.to_string(), path.map(str::to_string), slot, None, estimated, available); + return Ok(()); + } let warnings: Vec = v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default(); let held = |doc, read_only, question, policy_applied| crate::open_prompt::Held { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e17b2bc80dd..2a7af1fc7ba 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -687,6 +687,8 @@ pub struct PhotocraftApp { /// Files read but not opened yet: the first waits on its profile prompt, the rest behind it /// (see `open_prompt`). pub(crate) held_opens: std::collections::VecDeque, + /// PSD files whose memory preflight requires user approval before pixel decoding (see `open_prompt`). + pub(crate) held_memory_prompts: std::collections::VecDeque, /// A brush or gradient file waiting on the group-name prompt (see `preset_group_prompt`). pub(crate) held_preset_import: Option, /// Set once the user has agreed to quit, so the resulting close request goes through. diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 1c40f898bde..728817a4feb 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -197,3 +197,32 @@ fn background_damage_only_open_does_not_create_a_spurious_profile_question() { assert_eq!(app.session.documents().len(), 1); assert!(app.ui.dialogs.is_empty(), "color:null is not a profile question"); } + +#[test] +fn memory_confirmation_dialog_and_cancel_lifecycle() { + let mut app = app(); + let gb = 1u64 << 30; + + // Simulate memory prompt arrival: + let preflight_id = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "high_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb)); + assert_eq!(app.ui.dialogs.len(), 1); + assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); + let dlg_id = app.ui.dialogs[0].id; + + // Cancel via dialog cancel: + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.take_pending_preflight(preflight_id).is_none(), "pending preflight dropped on cancel"); +} diff --git a/docs/development.md b/docs/development.md index 277d20b9540..7a2744eccc5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -663,12 +663,22 @@ before merged-image validation or decoding. The conservative estimate sums retai storage (including padding and negative offsets) and the largest decode/conversion workspace. It does not credit uniform-tile sharing or pruning, so some files that could fit after decoding are refused. Valid off-canvas pixels are preserved; oversized layers are rejected rather than -clipped. Defaults are 2 GiB on native targets and 1 GiB on wasm. Applications can lower the -allowance with `ImportOptions::psd_max_pixel_bytes`; values above the default are capped. -The source-only convenience API uses the default; `import_file_for_open_with` honours options. +clipped. -An over-budget ordinary or interactive import returns `IoError::PsdImportBudget` with the -estimated and allowed byte counts; damaged-file recovery never bypasses that error. The legacy +Native desktop platforms use an adaptive memory policy evaluated against currently available +physical RAM (excluding swap) and system commit headroom: +- **Hard budget (H)**: $\min(75\% ext{ RAM}, ext{RAM} - 1 ext{ GiB}, ext{commit headroom} - 512 ext{ MiB}, ext{address-space limits})$. +- **Soft budget (S)**: $\min(50\% ext{ RAM}, 8 ext{ GiB}, H)$. +- Files requiring $\le S$ are admitted automatically. +- Files requiring $S < E \le H$ prompt for explicit one-shot user confirmation ("Open anyway") in the UI or require `approveHighMemory: true` for headless callers. +- Files requiring $> H$ are refused and cannot be overridden. +- Fallback allowance when usable memory is unknown is 2 GiB with no confirmation override; WebAssembly uses a fixed 1 GiB limit. +- Applications can lower the admission threshold with `ImportOptions::psd_max_pixel_bytes`; explicit caller limits may lower admission, never bypass the hard boundary. +- Concurrent PSD decodes are serialized using a process-wide, cancellation-aware admission gate, with nested decodes sharing the enclosing allowance. + +An import exceeding the hard budget returns `IoError::PsdImportBudget` with the estimated +and allowed byte counts; imports requiring confirmation return `IoError::PsdApprovalRequired` +when unapproved. Damaged-file recovery never bypasses these memory guards. The legacy `psd_to_document` conversion APIs cannot return an error, so they return an empty document and an explicit warning on preflight refusal. Layer and mask pixel allocation failures also fail ordinary imports instead of opening partial content.