Merge remote-tracking branch 'upstream/main' into pr-5332

This commit is contained in:
FredApps committed 2026-11-03 11:16:12 +01:00
commit 66e9325379
52 files changed
+7359 -576

No files matched your search

Generated
+42 -129
View File
@@ -93,8 +93,8 @@ dependencies = [
"accesskit_consumer",
"hashbrown 0.17.1",
"static_assertions",
"windows 0.62.2",
"windows-core 0.62.2",
"windows",
"windows-core",
]
[[package]]
@@ -1021,7 +1021,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -2372,8 +2372,8 @@ dependencies = [
"read-fonts",
"roxmltree 0.21.1",
"smallvec",
"windows 0.62.2",
"windows-core 0.62.2",
"windows",
"windows-core",
"yeslogic-fontconfig-sys",
]
@@ -2572,7 +2572,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix 1.1.5",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -2774,7 +2774,7 @@ dependencies = [
"log",
"presser",
"thiserror 2.0.21",
"windows 0.62.2",
"windows",
]
[[package]]
@@ -2998,7 +2998,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.62.2",
"windows-core",
]
[[package]]
@@ -3402,7 +3402,7 @@ dependencies = [
"simd_cesu8",
"thiserror 2.0.21",
"walkdir",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -3752,7 +3752,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -4841,7 +4841,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -5082,6 +5082,7 @@ dependencies = [
"photocraft-format",
"photocraft-geom",
"photocraft-io",
"photocraft-psd",
"photocraft-raster",
"photocraft-raw",
"rmcp",
@@ -5380,6 +5381,7 @@ dependencies = [
"rayon",
"serde",
"sysinfo",
"winsafe",
]
[[package]]
@@ -7381,16 +7383,16 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.37.2"
version = "0.40.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16607d5caffd1c07ce073528f9ed972d88db15dd44023fa57142963be3feb11f"
checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8"
dependencies = [
"libc",
"memchr",
"ntapi",
"objc2-core-foundation",
"objc2-io-kit",
"windows 0.61.3",
"windows",
]
[[package]]
@@ -8664,9 +8666,9 @@ dependencies = [
"web-sys",
"wgpu-naga-bridge",
"wgpu-types",
"windows 0.62.2",
"windows-core 0.62.2",
"windows-result 0.4.1",
"windows",
"windows-core",
"windows-result",
]
[[package]]
@@ -8732,38 +8734,16 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows"
version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections 0.2.0",
"windows-core 0.61.2",
"windows-future 0.2.1",
"windows-link 0.1.3",
"windows-numerics 0.2.0",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core 0.61.2",
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
@@ -8772,20 +8752,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
"windows-core",
]
[[package]]
@@ -8796,20 +8763,9 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-future"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
"windows-threading 0.1.0",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
@@ -8818,9 +8774,9 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
@@ -8845,36 +8801,20 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
]
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-core",
"windows-link",
]
[[package]]
@@ -8883,18 +8823,9 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link 0.1.3",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
@@ -8903,16 +8834,7 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link 0.1.3",
"windows-link",
]
[[package]]
@@ -8921,7 +8843,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -8948,7 +8870,7 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -8967,22 +8889,13 @@ dependencies = [
"windows_x86_64_msvc",
]
[[package]]
name = "windows-threading"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -9108,8 +9021,8 @@ dependencies = [
"strum",
"tar",
"thiserror 2.0.21",
"windows 0.62.2",
"windows-core 0.62.2",
"windows",
"windows-core",
"windows-implement",
"xml",
]
@@ -9282,7 +9195,7 @@ dependencies = [
"thiserror 2.0.21",
"url",
"widestring",
"windows 0.62.2",
"windows",
"xcb",
"zbus",
]
+12
View File
@@ -95,6 +95,9 @@ pub(crate) struct ConvertArgs {
/// Allow an <OUT> that is the <IN> file, replacing the original
#[arg(long)]
pub(crate) in_place: bool,
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
#[command(flatten)]
pub(crate) export: ExportArgs,
}
@@ -106,6 +109,9 @@ pub(crate) struct InfoArgs {
/// One line of JSON instead of pretty-printed
#[arg(long)]
pub(crate) compact: bool,
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
}
/// Open a file (or start a new document), run engine commands in order, save the result
@@ -134,6 +140,9 @@ pub(crate) struct RunArgs {
/// Allow an --out that is the <FILE>, replacing the original
#[arg(long)]
pub(crate) in_place: bool,
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
#[command(flatten)]
pub(crate) export: ExportArgs,
/// `--cmd` and `--params` values in command-line order, set by [`parse`].
@@ -173,6 +182,9 @@ pub(crate) struct BatchArgs {
/// originals; --in-place allows it
#[arg(long)]
pub(crate) in_place: bool,
/// Explicitly approve high-memory PSD/PSB imports within the hard memory budget
#[arg(long)]
pub(crate) approve_high_memory: bool,
#[command(flatten)]
pub(crate) export: ExportArgs,
}
+1 -1
View File
@@ -81,7 +81,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
// Steps that play another action find it in the set; the session's playback stack
// stops an action that calls itself.
h.session.actions.list = set.clone();
h.open(input)?;
h.open_with_approval(input, a.approve_high_memory)?;
for (id, p) in &actions {
if photocraft_engine::actions_cmds::shell_view_command(id)
|| photocraft_engine::actions_cmds::shell_save_command(id)
+4 -3
View File
@@ -30,7 +30,8 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write
let (input, output) = (&a.input, &a.output);
let opts = ExportOptions::from(&a.export);
refuse_overwriting_input(a.in_place, input, output)?;
let mut o = files::open(input)?;
let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() };
let mut o = files::open_with_options(input, &import_opts)?;
// Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw.
photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document);
warn_all(err, &o.warnings);
@@ -43,7 +44,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write
pub(crate) fn info(a: &InfoArgs, out: &mut dyn Write) -> Result {
let file = &a.file;
let mut h = Headless::trusted_local();
let opened = h.open(file)?;
let opened = h.open_with_approval(file, a.approve_high_memory)?;
let mut doc = h.inspect(None)?;
let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default();
if let Some(st) = h.session.active() {
@@ -86,7 +87,7 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) ->
if let Some(out) = &a.out {
refuse_overwriting_input(a.in_place, file, out)?;
}
let o = h.open(file)?;
let o = h.open_with_approval(file, a.approve_high_memory)?;
let ws: Vec<String> = serde_json::from_value(o["warnings"].clone()).unwrap_or_default();
warn_all(err, &ws);
reported_fonts.extend(ws);
+4
View File
@@ -32,6 +32,10 @@ clap = { workspace = true }
photocraft-geom = { workspace = true }
# Synthetic camera raws (#7789).
photocraft-raw = { workspace = true, features = ["testgen"] }
# Tiny generated PSDs and the scoped estimate charge for the high-memory approval tests
# (no multi-gigabyte fixture or global override).
photocraft-io = { workspace = true, features = ["testgen"] }
photocraft-psd = { workspace = true, features = ["testgen"] }
rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
+16 -7
View File
@@ -18,17 +18,27 @@ pub struct Opened {
/// Decode a document that was read through a filesystem capability.
pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<Opened, AutomationError> {
open_bytes_with_options(name, bytes, &photocraft_io::ImportOptions::default())
}
/// Decode a document that was read through a filesystem capability with custom import options.
pub fn open_bytes_with_options(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<Opened, AutomationError> {
if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) {
let document = photocraft_format::load_from_bytes(bytes)?;
return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false });
}
let r = photocraft_io::import(name, bytes)?;
let r = photocraft_io::import_with_options(name, bytes, opts)?;
Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only })
}
/// Open a document from disk. Directory bundles and `.pcraft` ZIPs load
/// natively; everything else goes through `photocraft-io` (PSD, PNG, …).
pub fn open(path: &Path) -> Result<Opened, AutomationError> {
open_with_options(path, &photocraft_io::ImportOptions::default())
}
/// Open a document from disk with custom import options.
pub fn open_with_options(path: &Path, opts: &photocraft_io::ImportOptions) -> Result<Opened, AutomationError> {
if path.is_dir() {
let document = photocraft_format::load_path(path)?;
return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false });
@@ -38,17 +48,16 @@ pub fn open(path: &Path) -> Result<Opened, AutomationError> {
// convert or info of a 2 GB file does not hold the file in memory next to the document.
#[cfg(any(unix, windows))]
{
let r =
photocraft_io::import_file(&name, path, &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE).map_err(|e| match e {
photocraft_io::IoError::Read(msg) => AutomationError::Io(msg),
e => e.into(),
})?;
let r = photocraft_io::import_file(&name, path, opts, &photocraft_raster::Interrupt::NONE).map_err(|e| match e {
photocraft_io::IoError::Read(msg) => AutomationError::Io(msg),
e => e.into(),
})?;
Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only })
}
#[cfg(not(any(unix, windows)))]
{
let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
open_bytes(&name, &bytes)
open_bytes_with_options(&name, &bytes, opts)
}
}
+15 -3
View File
@@ -90,14 +90,25 @@ impl Headless {
/// Open a file and make it the active document.
pub fn open(&mut self, path: &Path) -> Result<Value, AutomationError> {
self.open_with_approval(path, false)
}
/// Open a file with optional high-memory approval and make it the active document.
pub fn open_with_approval(&mut self, path: &Path, approve_high_memory: bool) -> Result<Value, AutomationError> {
let opts = photocraft_io::ImportOptions { psd_high_memory_approved: approve_high_memory, ..Default::default() };
self.open_with_options(path, &opts)
}
/// Open a file with custom import options and make it the active document.
pub fn open_with_options(&mut self, path: &Path, opts: &photocraft_io::ImportOptions) -> Result<Value, AutomationError> {
let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
let mut o = match &self.filesystem {
Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())),
Filesystem::TrustedLocal => files::open(path)?,
Filesystem::TrustedLocal => files::open_with_options(path, opts)?,
Filesystem::Workspace(workspace) => {
let bytes = workspace.read(requested)?;
let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(requested);
files::open_bytes(name, &bytes)?
files::open_bytes_with_options(name, &bytes, opts)?
}
};
// Preferences › Raw Defaults › Resolution, as the app's File › Open applies it.
@@ -129,7 +140,8 @@ impl Headless {
/// Place a file into a document as a Smart Object layer: the capability-scoped counterpart
/// of `file.placeEmbedded`, which reads an ambient path and is therefore refused in
/// automation (#2810). `path` resolves beneath the read root the way `open` resolves one,
/// and `params` carries the command's own options (`scale`, `fit`, `center`).
/// and `params` carries the command's own options (`scale`, `fit`, `center`,
/// `approveHighMemory`).
pub fn place(&mut self, index: Option<usize>, path: &str, params: &Value) -> Result<Value, AutomationError> {
self.on_doc(index, |this| {
let mut opts = params.as_object().cloned().unwrap_or_default();
+49 -3
View File
@@ -61,6 +61,36 @@ pub const METHODS: &[&str] = &[
"methods",
];
/// Adds the structured memory fields (`required`, soft and hard limits and measured capacity)
/// from a typed admission error to a JSON error object, so clients can offer approval.
fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) {
match err {
AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram })
| AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram, .. }) => {
if let Some(m) = obj.as_object_mut() {
m.insert("required".into(), json!(required));
m.insert("soft".into(), json!(soft_limit));
m.insert("softLimit".into(), json!(soft_limit));
m.insert("hard".into(), json!(hard_limit));
m.insert("hardLimit".into(), json!(hard_limit));
if let Some(avail) = available_ram {
m.insert("available".into(), json!(avail));
m.insert("availableRam".into(), json!(avail));
}
}
}
AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit })
| AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, .. }) => {
if let Some(m) = obj.as_object_mut() {
m.insert("required".into(), json!(required));
m.insert("hard".into(), json!(limit));
m.insert("hardLimit".into(), json!(limit));
}
}
_ => {}
}
}
fn bad(msg: impl Into<String>) -> AutomationError {
AutomationError::BadRequest(msg.into())
}
@@ -107,10 +137,18 @@ impl Headless {
"session.list" => Ok(self.session_list()),
"doc.open" => {
let path = str_of(&p, "path").ok_or_else(|| bad("doc.open needs `path`"))?;
self.open(&PathBuf::from(path))
let approve = match p.get("approveHighMemory") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(_) => return Err(bad("`approveHighMemory` must be a boolean")),
};
self.open_with_approval(&PathBuf::from(path), approve)
}
"doc.place" => {
let path = str_of(&p, "path").ok_or_else(|| bad("doc.place needs `path`"))?;
if p.get("approveHighMemory").is_some_and(|v| !v.is_boolean()) {
return Err(bad("`approveHighMemory` must be a boolean"));
}
let mut opts = p.as_object().cloned().unwrap_or_default();
opts.remove("path");
opts.remove("index");
@@ -230,7 +268,11 @@ impl Headless {
let was_error = r.is_err();
let result = match r {
Ok(v) => json!({"ok": true, "result": v}),
Err(e) => json!({"ok": false, "error": e.to_string()}),
Err(e) => {
let mut obj = json!({"ok": false, "error": e.to_string()});
attach_memory_error_details(&mut obj, &e);
obj
}
};
if let Err(error) = reply_budget.charge(&result) {
failed += 1;
@@ -268,7 +310,11 @@ pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error: `{method}` panicked"))));
match r {
Ok(v) => json!({"id": id, "ok": true, "result": v}),
Err(e) => json!({"id": id, "ok": false, "error": e.to_string()}),
Err(e) => {
let mut obj = json!({"id": id, "ok": false, "error": e.to_string()});
attach_memory_error_details(&mut obj, &e);
obj
}
}
}
+85
View File
@@ -1028,3 +1028,88 @@ fn invalid_document_index_is_rejected_not_the_active_document() {
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(count(&h), 1);
}
#[test]
fn approve_high_memory_rejects_invalid_types_and_formats_structured_error() {
let h = session();
// Non-boolean approveHighMemory is rejected strictly
let reply = respond(&h, r#"{"method":"doc.open","params":{"path":"test.psd","approveHighMemory":"yes"}}"#);
assert_eq!(reply["ok"], false);
assert!(reply["error"].as_str().unwrap().contains("must be a boolean"));
let reply_place = respond(&h, r#"{"method":"doc.place","params":{"path":"test.psd","approveHighMemory":123}}"#);
assert_eq!(reply_place["ok"], false);
assert!(reply_place["error"].as_str().unwrap().contains("must be a boolean"));
// Verify attach_memory_error_details adds machine-readable fields
let mut err_obj = json!({"id": 1, "ok": false, "error": "test"});
let auto_err = crate::AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired {
required: 5000,
soft_limit: 2000,
hard_limit: 8000,
available_ram: Some(10000),
});
super::attach_memory_error_details(&mut err_obj, &auto_err);
assert_eq!(err_obj["required"], 5000);
assert_eq!(err_obj["soft"], 2000);
assert_eq!(err_obj["softLimit"], 2000);
assert_eq!(err_obj["hard"], 8000);
assert_eq!(err_obj["hardLimit"], 8000);
assert_eq!(err_obj["available"], 10000);
assert_eq!(err_obj["availableRam"], 10000);
// An engine-command hard refusal (Open As / Place go through `EngineError`) keeps its typed
// fields, and only the fields an approval request has: no soft limit and no capacity, since
// no approval can raise the ceiling.
let mut hard_obj = json!({"id": 2, "ok": false, "error": "test"});
let hard = crate::AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { name: "big.psd".into(), required: 9000, limit: 8000 });
super::attach_memory_error_details(&mut hard_obj, &hard);
assert_eq!(hard_obj["required"], 9000);
assert_eq!(hard_obj["hard"], 8000);
assert_eq!(hard_obj["hardLimit"], 8000);
for absent in ["soft", "softLimit", "available", "availableRam"] {
assert!(hard_obj.get(absent).is_none(), "a hard refusal has no {absent}: {hard_obj}");
}
}
/// #10897: `doc.place` forwards the strict one-shot high-memory approval on both routes: the
/// read-root route (the bytes are imported in-process) and trusted local (the ambient
/// `file.placeEmbedded` command reads the path). A tiny PSD plus the scoped estimate charge
/// reaches the real approval window without allocating anything close to a gigabyte.
#[test]
fn doc_place_forwards_high_memory_approval() {
if cfg!(target_pointer_width = "32") {
return; // the 3 GiB charge would exceed a 32-bit process cap
}
let gb = 1u64 << 30;
let root = std::env::temp_dir().join(format!("pc-doc-place-approval-{}", std::process::id()));
std::fs::create_dir_all(&root).unwrap();
let psd = photocraft_psd::testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap();
std::fs::write(root.join("high.psd"), &psd).unwrap();
// Known 5 GiB RAM: S = 2.5 GiB, H = 3.75 GiB. A 3 GiB estimate charge lands in (S, H].
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None };
let trial = |h: &mut Headless, path: &str| {
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
photocraft_io::memory::with_mock_memory(snap, || {
let refused = h.handle("doc.place", json!({"path": path})).unwrap_err();
assert!(
matches!(refused, crate::AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { .. })),
"an unapproved high-memory place must ask for approval: {refused}"
);
let placed = h.handle("doc.place", json!({"path": path, "approveHighMemory": true})).unwrap();
assert!(placed["layer"].as_u64().is_some(), "the approval lets the same place proceed: {placed}");
});
});
};
let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());
h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap();
trial(&mut h, "high.psd");
// Release directory capabilities before cleanup on Windows.
drop(h);
let mut t = Headless::trusted_local();
t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap();
let absolute = root.join("high.psd").to_string_lossy().into_owned();
trial(&mut t, &absolute);
drop(t);
std::fs::remove_dir_all(root).unwrap();
}
+132 -16
View File
@@ -50,6 +50,9 @@ pub struct DocIndex {
pub struct OpenParams {
/// Path beneath the configured automation read root: relative (forward slashes) or absolute.
pub path: String,
/// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget.
#[serde(default)]
pub approve_high_memory: bool,
}
#[derive(Debug, Default, Deserialize, JsonSchema)]
@@ -69,6 +72,9 @@ pub struct PlaceParams {
/// Centre of the placed layer, in document pixels.
#[serde(default)]
pub center: Option<[f64; 2]>,
/// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget.
#[serde(default)]
pub approve_high_memory: bool,
}
#[derive(Debug, Default, Deserialize, JsonSchema)]
@@ -484,13 +490,64 @@ fn png_result(png: &[u8], note: String) -> CallToolResult {
bounded_tool_result(CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note)]))
}
/// Adds the typed byte counts of a memory refusal to an error object: an approval request keeps
/// its soft limit, hard limit and (when known) capacity; a hard refusal keeps only its required
/// and hard amounts, because no approval can raise that ceiling.
fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) {
let Some(obj) = obj.as_object_mut() else { return };
match err {
AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram })
| AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram, .. }) => {
obj.insert("required".into(), json!(required));
obj.insert("soft".into(), json!(soft_limit));
obj.insert("softLimit".into(), json!(soft_limit));
obj.insert("hard".into(), json!(hard_limit));
obj.insert("hardLimit".into(), json!(hard_limit));
if let Some(avail) = available_ram {
obj.insert("available".into(), json!(avail));
obj.insert("availableRam".into(), json!(avail));
}
}
AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit })
| AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, .. }) => {
obj.insert("required".into(), json!(required));
obj.insert("hard".into(), json!(limit));
obj.insert("hardLimit".into(), json!(limit));
}
_ => {}
}
}
fn to_result(r: Result<Value, AutomationError>) -> Result<CallToolResult, McpError> {
Ok(match r {
Ok(v) => ok_json(&v),
Err(e) => fail(e),
Err(e) => {
let mut obj = json!({"error": e.to_string()});
attach_memory_error_details(&mut obj, &e);
let text = serde_json::to_string(&obj).unwrap_or_else(|_| e.to_string());
CallToolResult::error(vec![Content::text(text)])
}
})
}
/// A `doc_place` call's command options, including the explicit high-memory approval.
fn place_options(p: &PlaceParams) -> Value {
let mut opts = serde_json::Map::new();
if let Some(v) = p.scale {
opts.insert("scale".into(), json!(v));
}
if let Some(v) = p.fit {
opts.insert("fit".into(), json!(v));
}
if let Some(v) = p.center {
opts.insert("center".into(), json!(v));
}
if p.approve_high_memory {
opts.insert("approveHighMemory".into(), json!(true));
}
Value::Object(opts)
}
fn bridge_only(name: &str) -> Result<CallToolResult, McpError> {
Ok(fail(format!(
"`{name}` drives the live GUI and needs bridge mode: start the app with \
@@ -635,30 +692,25 @@ impl PhotocraftMcp {
#[tool(description = "Open an image or document file and make it active. Returns index, size and import warnings.")]
async fn doc_open(&self, Parameters(p): Parameters<OpenParams>) -> Result<CallToolResult, McpError> {
let path = PathBuf::from(&p.path);
if let Some(r) = self.headless_op(move |h| h.open(&path)).await {
let approve = p.approve_high_memory;
if let Some(r) = self.headless_op(move |h| h.open_with_approval(&path, approve)).await {
return to_result(r);
}
let Some(b) = self.bridge_client() else {
return Ok(no_backend());
};
to_result(b.call("app.open", json!({"path": p.path})).await)
let mut params = json!({"path": p.path});
if approve {
params["approveHighMemory"] = json!(true);
}
to_result(b.call("app.open", params).await)
}
#[tool(
description = "Place a file into the document as a Smart Object layer (Place Embedded), reading `path` beneath the read root. `scale` (percent), `fit` and `center` are the command's own."
description = "Place a file into the document as a Smart Object layer (Place Embedded), reading `path` beneath the read root. `scale` (percent), `fit`, `center` and `approve_high_memory` (one-shot PSD/PSB consent, default false) are the command's own."
)]
async fn doc_place(&self, Parameters(p): Parameters<PlaceParams>) -> Result<CallToolResult, McpError> {
let mut opts = serde_json::Map::new();
if let Some(v) = p.scale {
opts.insert("scale".into(), json!(v));
}
if let Some(v) = p.fit {
opts.insert("fit".into(), json!(v));
}
if let Some(v) = p.center {
opts.insert("center".into(), json!(v));
}
let opts = Value::Object(opts);
let opts = place_options(&p);
// Bridge mode runs the app on this machine, which reads the path itself like any command.
let mut bridge_params = opts.clone();
if let Some(o) = bridge_params.as_object_mut() {
@@ -943,7 +995,11 @@ impl PhotocraftMcp {
let was_error = response.is_err();
let result = match response {
Ok(value) => json!({"ok": true, "result": value}),
Err(error) => json!({"ok": false, "error": error.to_string()}),
Err(error) => {
let mut obj = json!({"ok": false, "error": error.to_string()});
attach_memory_error_details(&mut obj, &error);
obj
}
};
if let Err(error) = reply_budget.charge(&result) {
failed += 1;
@@ -1265,6 +1321,66 @@ mod tests {
assert_eq!(docs, 0, "the step after the budget ran out did not run");
}
#[tokio::test(flavor = "multi_thread")]
async fn mcp_doc_open_schema_and_structured_error() {
let schema = &PhotocraftMcp::tool_router().map["doc_open"].attr.input_schema;
assert_eq!(schema["properties"]["approve_high_memory"]["type"], "boolean");
let omitted: OpenParams = serde_json::from_value(json!({"path": "file.psd"})).unwrap();
assert!(!omitted.approve_high_memory);
let approved: OpenParams = serde_json::from_value(json!({"path": "file.psd", "approve_high_memory": true})).unwrap();
assert!(approved.approve_high_memory);
for invalid in [Value::Null, json!("true"), json!(1)] {
assert!(serde_json::from_value::<OpenParams>(json!({"path": "file.psd", "approve_high_memory": invalid})).is_err());
}
let err = AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired {
required: 6000,
soft_limit: 3000,
hard_limit: 9000,
available_ram: Some(12000),
});
let res = to_result(Err(err)).unwrap();
assert_eq!(res.is_error, Some(true));
let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text;
let v: Value = serde_json::from_str(text).unwrap();
assert_eq!(v["required"], 6000);
assert_eq!(v["soft"], 3000);
assert_eq!(v["hard"], 9000);
assert_eq!(v["available"], 12000);
}
/// #10897: the MCP `doc_place` tool takes the same strict, defaulted approval as `doc_open`
/// and forwards it as the command's `approveHighMemory` option. A hard refusal keeps its
/// typed `required`/`hardLimit` fields and claims nothing about a soft limit or capacity.
#[tokio::test(flavor = "multi_thread")]
async fn mcp_doc_place_schema_approval_and_structured_hard_error() {
let schema = &PhotocraftMcp::tool_router().map["doc_place"].attr.input_schema;
assert_eq!(schema["properties"]["approve_high_memory"]["type"], "boolean");
let omitted: PlaceParams = serde_json::from_value(json!({"path": "file.psd"})).unwrap();
assert!(!omitted.approve_high_memory);
assert!(place_options(&omitted).get("approveHighMemory").is_none(), "false is not forwarded");
let approved: PlaceParams = serde_json::from_value(json!({"path": "file.psd", "approve_high_memory": true})).unwrap();
assert!(approved.approve_high_memory);
assert_eq!(place_options(&approved)["approveHighMemory"], true);
let explicit_false: PlaceParams = serde_json::from_value(json!({"path": "file.psd", "approve_high_memory": false})).unwrap();
assert!(!explicit_false.approve_high_memory);
for invalid in [Value::Null, json!("true"), json!(1)] {
assert!(serde_json::from_value::<PlaceParams>(json!({"path": "file.psd", "approve_high_memory": invalid})).is_err(), "{invalid}");
}
let err = AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { name: "huge.psd".into(), required: 9_000, limit: 8_000 });
let res = to_result(Err(err)).unwrap();
assert_eq!(res.is_error, Some(true));
let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text;
let v: Value = serde_json::from_str(text).unwrap();
assert_eq!(v["required"], 9_000);
assert_eq!(v["hard"], 8_000);
assert_eq!(v["hardLimit"], 8_000);
for absent in ["soft", "softLimit", "available", "availableRam"] {
assert!(v.get(absent).is_none(), "a hard refusal has no {absent}: {v}");
}
}
/// The MCP server applies finished jobs before every tool call too (#503).
#[tokio::test(flavor = "multi_thread")]
async fn mcp_tools_see_a_finished_background_job() {
+40
View File
@@ -165,6 +165,18 @@ impl<'a> TiffBands<'a> {
self.p.lay.out_row().checked_mul(rows).ok_or_else(|| CodecError::LimitExceeded("band size".into()))
}
/// A conservative bound on the decoder's own scratch memory in a whole-image decode of this
/// page (as `decode_page` does it): one strip or tile per worker that decodes a band at
/// once. Zero when strips are decoded in place. Add the decoded image itself and any
/// extra-sample planes.
pub fn decode_scratch_bytes(&self) -> u64 {
#[cfg(not(target_arch = "wasm32"))]
let workers = rayon::current_num_threads() as u64;
#[cfg(target_arch = "wasm32")]
let workers = 1;
scratch_bound(self.p.lay.direct(), self.p.scratch_bytes as u64, self.p.band_rows, self.p.h, workers)
}
/// Decodes the image a group of bands at a time, in order, handing each group to `sink`
/// with the position of its top-left pixel in the image [`TiffBands::dimensions`] gives. A
/// group is about 64 MiB (at least one strip or row of tiles per worker, at most `max_alloc`;
@@ -219,6 +231,16 @@ impl<'a> TiffBands<'a> {
}
}
/// [`TiffBands::decode_scratch_bytes`]'s bound: none when chunks are decoded in place,
/// otherwise one chunk per worker that decodes a band, and never more chunks than the image has.
fn scratch_bound(direct: bool, chunk_bytes: u64, band_rows: usize, h: u32, workers: u64) -> u64 {
if direct {
return 0;
}
let bands = u64::from(h).div_ceil(band_rows.max(1) as u64).max(1);
chunk_bytes.saturating_mul(workers.min(bands))
}
/// The Orientation (1–8) of page `page` (`None`: the default page); 1 when absent, malformed
/// or out of range. Classic TIFF and BigTIFF.
pub(crate) fn orientation(bytes: &[u8], page: Option<usize>) -> u16 {
@@ -559,6 +581,9 @@ pub(super) struct Prepared {
extras_over_limit: usize,
/// Extra samples left out because they did not fit the allocation budget beside the image.
extras_dropped: u32,
/// Bytes one strip or tile decodes to, before clipping to the image: a worker's scratch
/// buffer. A strip is the full width; a tile keeps its declared size even at an edge.
scratch_bytes: usize,
}
impl Prepared {
@@ -803,6 +828,9 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
.and_then(|s| s.checked_mul(src.bytes()))
.ok_or_else(|| CodecError::LimitExceeded("tile size".into()))?;
let scratch_cap = chunk_bytes.saturating_mul(2).max(64 << 20).min(limits.alloc_usize());
// One chunk as the decoder actually reads it: a tile keeps its declared size at an edge,
// which can be more than the clipped image bytes above.
let scratch_bytes = cw.saturating_mul(ch).saturating_mul(chunk_spp).saturating_mul(src.bytes());
let (extra_at, extras_over_limit) = extra_sample_indices(spp as usize, color, alpha_at, out_layout.has_alpha());
let mut lay = Layout {
w: wu,
@@ -846,6 +874,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
extra_kinds: extra,
extras_over_limit,
extras_dropped,
scratch_bytes,
})
}
@@ -873,4 +902,15 @@ mod tests {
let whole = decode(&bytes, &tight).unwrap();
assert_eq!(whole.warnings, prepared_warnings(&p));
}
/// The scratch bound a whole-image decode reserves: none for chunks decoded in place, one
/// chunk per worker otherwise, never more chunks than the image has bands.
#[test]
fn whole_image_scratch_is_one_chunk_per_worker() {
assert_eq!(scratch_bound(true, 1 << 20, 16, 1024, 8), 0, "strips decoded in place need no scratch");
assert_eq!(scratch_bound(false, 1 << 20, 16, 1024, 8), 8 << 20, "one strip per worker");
assert_eq!(scratch_bound(false, 1 << 20, 16, 32, 8), 2 << 20, "never more strips than the image has");
assert_eq!(scratch_bound(false, 1 << 20, 0, 2, 8), 2 << 20, "a zero band height counts as one row");
assert_eq!(scratch_bound(false, u64::MAX, 1, 1, 8), u64::MAX, "the bound saturates");
}
}
+1
View File
@@ -61,6 +61,7 @@ photocraft-ipp = { workspace = true }
[dev-dependencies]
photocraft-affinity = { workspace = true, features = ["synth"] }
photocraft-io = { workspace = true, features = ["testgen"] }
# Synthetic camera raw files for the open tests.
photocraft-raw = { workspace = true, features = ["testgen"] }
photocraft-testkit = { workspace = true }
+28 -6
View File
@@ -39,9 +39,9 @@ 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(crate) use open::{import, tag_exr_colorspace};
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, import_with_options, tag_exr_colorspace};
use paths::is_file;
#[cfg(test)]
use paths::openable_name;
@@ -70,6 +70,10 @@ pub(crate) fn native(_: &Session) -> std::result::Result<(), String> {
if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) }
}
fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub(crate) fn native_doc(s: &Session) -> std::result::Result<(), String> {
native(s)?;
has_doc(s)
@@ -119,6 +123,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<u64> {
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<f64> {
p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite())
}
@@ -255,16 +263,30 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
// One-shot permission for one file, not something to replay later: never journaled or
// recorded in an action, since replaying it in another session/on another file would
// grant memory use nobody approved (#10897). It also releases the queued source on both
// answers, so it must not be replayed as a step that expects a missing preflight.
CommandSpec {
id: "file.approveMemory",
label: "Approve High Memory PSD Import",
menu: &[],
shortcut: None,
params: r##"{"id":u64,"approve":bool=true,"background":bool=true}"##,
enabled: always,
run: approve_memory,
journal: false,
},
spec!(
"file.placeEmbedded",
"Place Embedded…",
&["File"],
None,
r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?}"##,
r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##,
native_doc,
|s, p| place(s, p, false)
),
@@ -273,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place Linked…",
&["File"],
None,
r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?}"##,
r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##,
native_doc,
|s, p| place(s, p, true)
),
+110 -7
View File
@@ -5,7 +5,13 @@ use super::{
};
pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
import_result(name, bytes).map(|r| r.document)
import_with_options(name, bytes, &photocraft_io::ImportOptions::default())
}
/// [`import`] with the caller's import settings. Footage passes its PSD/layered-TIFF memory limit,
/// so a frame import cannot bypass the admission the rest of the open path applies.
pub(crate) fn import_with_options(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<Document> {
import_result_with(name, bytes, opts).map(|r| r.document)
}
/// [`import`] for a file that becomes a document of its own (Revert, Load Files into Stack;
@@ -23,8 +29,15 @@ pub(super) fn import_at_raw_ppi(raw_ppi: f64, name: &str, bytes: &[u8]) -> Resul
}
fn import_result(name: &str, bytes: &[u8]) -> Result<photocraft_io::ImportResult> {
import_result_with(name, bytes, &photocraft_io::ImportOptions::default())
}
/// The one import path every caller shares: allocation checkpoint, native `.pcraft` and format
/// dispatch through `photocraft_io::import_with_options`, typed memory refusals, and the
/// preview-only refusal wherever the import came from.
fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
crate::allocation::checkpoint("importing document")?;
let r = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?;
let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
// Auxiliary imports return only a document and cannot surface the preview's fidelity warning.
// Open has its own warning-preserving path; never silently place or process a thumbnail.
if r.preview_only {
@@ -109,12 +122,30 @@ 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<String>) -> Result<Value> {
open_bytes_as_with_options(s, name, bytes, as_ext, path, false)
}
/// [`open_bytes_as`] with the caller's high-memory approval for these bytes.
///
/// A one-shot approved estimate is deliberately not forwarded: these bytes may be a fresh copy
/// whose estimate was never approved, so approval applies only through the boolean flag.
pub fn open_bytes_as_with_options(
s: &mut Session,
name: &str,
bytes: &[u8],
as_ext: Option<&str>,
path: Option<String>,
approve_high_memory: bool,
) -> Result<Value> {
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;
opts.psd_approved_estimate = None;
let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| crate::error::io_open_error(&decode_name, e))?;
let mut doc = r.document;
tag_exr_colorspace(s, &decode_name, &mut doc);
raw_defaults(s, &r.warnings, &mut doc);
@@ -139,9 +170,69 @@ pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&
pub(super) fn open_as(s: &mut Session, p: &Value) -> Result<Value> {
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 = match p.get("approveHighMemory") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(_) => {
return Err(EngineError::BadParams { cmd: "file.openAs".into(), msg: "expected boolean for \"approveHighMemory\"".into() });
}
};
let bytes = read_file(&path)?;
open_bytes_as_with_options(s, &path, &bytes, as_ext, Some(path.clone()), approve_high_memory)
}
/// Answers a pending high-memory preflight: `approve` false cancels it; true rechecks the hard
/// limit and starts the approved open. The preflight is removed either way, so a refusal or a
/// later failure releases the source it held.
pub(super) fn approve_memory(s: &mut Session, p: &Value) -> Result<Value> {
let id = crate::file_cmds::u64_param(p, "id", "file.approveMemory")?;
let approve = match p.get("approve") {
None | Some(Value::Null) => true,
Some(Value::Bool(b)) => *b,
Some(_) => {
return Err(EngineError::BadParams { cmd: "file.approveMemory".into(), msg: "expected boolean for \"approve\"".into() });
}
};
let _background = match p.get("background") {
None | Some(Value::Null) => true,
Some(Value::Bool(b)) => *b,
Some(_) => {
return Err(EngineError::BadParams { cmd: "file.approveMemory".into(), msg: "expected boolean for \"background\"".into() });
}
};
if !approve {
s.cancel_pending_preflight(id)
.ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?;
return Ok(json!({"id": id, "approved": false, "cancelled": true}));
}
// Taking the preflight releases the source bytes it held: approval, refusal and a later
// failure all end the wait. The one-shot authorization is bound to this source and estimate;
// the import re-checks both against the handle it actually decodes.
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}") })?;
// The resolved policy is the platform's: desktop uses its measured adaptive budget, the web
// its 1 GiB automatic / 2 GiB hard product cap. Explicit consent is available on both; the
// hard ceiling is never raised by an approval. While the scratch disk is spilling, tile
// pixels may use its room too; this fast refusal grants the whole room (the pending prompt
// does not keep the tile share), and the import re-checks the exact split before decoding.
let budget = photocraft_io::memory::resolve_budget_with_scratch(photocraft_io::memory::MemorySnapshot::current(), None, u64::MAX);
if preflight.required > budget.hard_limit {
return Err(EngineError::PsdHardBudget { name: preflight.name, required: preflight.required, limit: budget.hard_limit });
}
let started = s.start_open_approved_with_background(
&preflight.name,
preflight.source,
preflight.confirm_damage,
Some(preflight.required),
Some(preflight.fingerprint),
_background,
)?;
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,8 +250,17 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec<u8>, linked: Option<S
let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64);
let fmt = d.doc.pixel_format();
let vector = photocraft_io::svg::is_svg(&bytes);
let opts = crate::jobs::import_options(s.prefs());
let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| EngineError::Other(format!("{name}: {e}")))?;
let approve = match p.get("approveHighMemory") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(_) => {
return Err(EngineError::BadParams { cmd: "file.placeEmbedded".into(), msg: "expected boolean for \"approveHighMemory\"".into() });
}
};
let mut opts = crate::jobs::import_options(s.prefs());
opts.psd_high_memory_approved = approve;
opts.psd_approved_estimate = None;
let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| crate::error::io_open_error(name, e))?;
if imported.preview_only {
return Err(EngineError::Other(format!(
"{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here"
@@ -214,6 +314,9 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec<u8>, linked: Option<S
pub(super) fn place(s: &mut Session, p: &Value, linked: bool) -> Result<Value> {
let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" };
if p.get("approveHighMemory").is_some_and(|v| !v.is_null() && !v.is_boolean()) {
return Err(EngineError::BadParams { cmd: cmd.into(), msg: "expected boolean for approveHighMemory".into() });
}
let path = str_param(p, "path", cmd)?.to_string();
let bytes = read_file(&path)?;
// The link is stored absolute: a relative one would later be taken from the document's
+320
View File
@@ -2042,3 +2042,323 @@ fn sanitize_keeps_windows_device_names_off_the_disk() {
assert_eq!(sanitize(name), name);
}
}
#[test]
fn approve_memory_validates_parameters_and_unknown_ids() {
let mut s = session(4, 4, 8);
assert!(matches!(s.execute("file.approveMemory", json!({})), Err(EngineError::BadParams { .. })));
assert!(matches!(s.execute("file.approveMemory", json!({"id": "not_a_number"})), Err(EngineError::BadParams { .. })));
assert!(matches!(s.execute("file.approveMemory", json!({"id": 12345})), Err(EngineError::BadParams { .. })));
assert!(
matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": false})), Err(EngineError::BadParams { .. })),
"unknown id on cancel must fail"
);
assert!(
matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": "true"})), Err(EngineError::BadParams { .. })),
"wrong approve type string must BadParams"
);
assert!(
matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": 1})), Err(EngineError::BadParams { .. })),
"wrong approve type int must BadParams"
);
assert!(
matches!(s.execute("file.openAs", json!({"path": "a.psd", "approveHighMemory": "true"})), Err(EngineError::BadParams { .. })),
"wrong approveHighMemory on openAs must BadParams"
);
assert!(
matches!(s.execute("file.placeEmbedded", json!({"path": "a.psd", "approveHighMemory": 1})), Err(EngineError::BadParams { .. })),
"wrong approveHighMemory on placeEmbedded must BadParams"
);
assert!(
matches!(s.execute("file.approveMemory", json!({"id": 12345, "background": "true"})), Err(EngineError::BadParams { .. })),
"wrong background type string must BadParams"
);
assert!(
matches!(s.execute("file.approveMemory", json!({"id": 12345, "background": 1})), Err(EngineError::BadParams { .. })),
"wrong background type int must BadParams"
);
}
#[test]
fn approve_memory_cancels_and_removes_pending_preflight() {
let mut s = Session::new();
let id = s
.store_pending_preflight(crate::jobs::PendingPsdPreflight {
id: 0,
name: "test.psd".into(),
source: crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3])),
fingerprint: crate::jobs::SourceFingerprint::of(&crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3]))).unwrap(),
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.unwrap();
let res = s.execute("file.approveMemory", json!({"id": id, "approve": false})).unwrap();
assert_eq!(res["approved"], false);
assert_eq!(res["cancelled"], true);
assert!(s.take_pending_preflight(id).is_none(), "preflight removed on cancel");
}
#[test]
fn approve_memory_refuses_when_source_changes_before_confirmation() {
let dir = tmp("fingerprint_test");
let path = join(&dir, "change.psd");
std::fs::write(&path, b"initial content").unwrap();
let mut s = Session::new();
let src = crate::jobs::OpenSource::Path(path.clone());
let fp = crate::jobs::SourceFingerprint::of(&src).unwrap();
let id = s
.store_pending_preflight(crate::jobs::PendingPsdPreflight {
id: 0,
name: "change.psd".into(),
source: src,
fingerprint: fp,
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.unwrap();
// Modify file on disk
std::fs::write(&path, b"changed content longer").unwrap();
let res = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false}));
assert!(matches!(res, Err(EngineError::SourceChanged { .. })), "changed file must fail identity verification: {res:?}");
}
#[test]
fn approve_memory_refuses_when_available_ram_decreases() {
let gb = 1u64 << 30;
let mut s = Session::new();
let src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]));
let fp = crate::jobs::SourceFingerprint::of(&src).unwrap();
let id = s
.store_pending_preflight(crate::jobs::PendingPsdPreflight {
id: 0,
name: "ram_drop.psd".into(),
source: src,
fingerprint: fp,
required: 8 * gb,
soft_limit: 6 * gb,
hard_limit: 9 * gb,
available_ram: Some(12 * gb),
confirm_damage: true,
})
.unwrap();
// Memory drops: only 6 GiB available -> 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");
});
}
#[test]
fn pending_preflights_cap_fails_closed() {
let mut s = Session::new();
let src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]));
let fp = crate::jobs::SourceFingerprint::of(&src).unwrap();
for i in 0..crate::Session::MAX_PENDING_PREFLIGHTS {
assert!(
s.store_pending_preflight(crate::jobs::PendingPsdPreflight {
id: 0,
name: format!("file_{i}.psd"),
source: src.clone(),
fingerprint: fp.clone(),
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.is_ok()
);
}
assert!(
s.store_pending_preflight(crate::jobs::PendingPsdPreflight {
id: 0,
name: "overflow.psd".into(),
source: src,
fingerprint: fp,
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.is_err()
);
}
/// A queued high-memory preflight for `source`, with fields a test can read.
fn memory_preflight(name: &str, source: crate::jobs::OpenSource) -> crate::jobs::PendingPsdPreflight {
let fingerprint = crate::jobs::SourceFingerprint::of(&source).unwrap();
crate::jobs::PendingPsdPreflight {
id: 0,
name: name.into(),
source,
fingerprint,
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
}
}
#[test]
fn pending_preflights_bound_retained_bytes_and_charge_a_shared_buffer_once() {
let mut s = Session::new();
let cap = 100;
let a_src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 40]));
let b_src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 40]));
let a_id = s.store_pending_preflight_with_limit(memory_preflight("a.psd", a_src.clone()), cap).unwrap();
let b_id = s.store_pending_preflight_with_limit(memory_preflight("b.psd", b_src), cap).unwrap();
assert_eq!(s.pending_preflight_bytes().unwrap(), 80);
// A second reference to the same allocation is already held: queued for free.
let a_again = s.store_pending_preflight_with_limit(memory_preflight("a-again.psd", a_src), cap).unwrap();
assert_eq!(s.pending_preflight_bytes().unwrap(), 80, "one shared buffer is charged once, not three times");
// A different buffer would carry the total over the cap: refused, and nothing is charged.
let c_src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 30]));
let err = s.store_pending_preflight_with_limit(memory_preflight("c.psd", c_src.clone()), cap).expect_err("a further 30 bytes must not fit beside 80");
assert!(err.to_string().contains("waiting for a memory approval"), "{err}");
assert_eq!(s.pending_preflight_bytes().unwrap(), 80, "a refused preflight adds no charge");
// Cancelling one released its buffer; the refused one now fits; clearing releases the rest.
assert!(s.cancel_pending_preflight(a_again).is_some());
assert_eq!(s.pending_preflight_bytes().unwrap(), 80, "the other live reference still holds the buffer");
assert!(s.cancel_pending_preflight(a_id).is_some());
assert_eq!(s.pending_preflight_bytes().unwrap(), 40);
let c_id = s.store_pending_preflight_with_limit(memory_preflight("c.psd", c_src), cap).unwrap();
assert_eq!(s.pending_preflight_bytes().unwrap(), 70);
s.clear_pending_preflights();
assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "clear releases every held buffer");
assert!(s.cancel_pending_preflight(b_id).is_none());
assert!(s.cancel_pending_preflight(c_id).is_none());
}
#[test]
fn pending_preflights_charge_the_retained_allocation_not_the_visible_length() {
let mut s = Session::new();
let cap = 100;
// Room for 128 bytes but one byte of contents: what stays resident is the allocation, so a
// cap that fits the contents must still refuse it.
let mut grown = Vec::with_capacity(128);
grown.push(7u8);
let held = grown.capacity() as u64;
assert!(held >= 128, "the buffer really has the larger allocation: {held}");
let big = std::sync::Arc::new(grown);
let err = s
.store_pending_preflight_with_limit(memory_preflight("big.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::clone(&big))), cap)
.expect_err("the held capacity, not the one byte of contents, must be charged");
assert!(err.to_string().contains("waiting for a memory approval"), "{err}");
assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "a refused preflight adds no charge");
// A cap that admits the whole allocation accepts it, and shared clones count once.
let id = s.store_pending_preflight_with_limit(memory_preflight("big.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::clone(&big))), held).unwrap();
let shared =
s.store_pending_preflight_with_limit(memory_preflight("shared.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::clone(&big))), held).unwrap();
assert_eq!(s.pending_preflight_bytes().unwrap(), held, "one shared allocation is charged once, whatever its length");
assert!(s.cancel_pending_preflight(shared).is_some());
assert_eq!(s.pending_preflight_bytes().unwrap(), held, "the other shared reference still holds the allocation");
assert!(s.cancel_pending_preflight(id).is_some());
assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "cancelling the last reference releases the allocation");
s.clear_pending_preflights();
// A buffer whose length was shrunk to zero still holds its allocation: the held capacity is
// measured, so it is charged even though `len()` says nothing is there.
let mut emptied = Vec::with_capacity(128);
emptied.push(1u8);
emptied.clear();
assert!(emptied.is_empty(), "the length is zero while the allocation stays");
let emptied = std::sync::Arc::new(emptied);
let emptied_held = emptied.capacity() as u64;
assert!(emptied_held >= 128, "clearing does not release the allocation: {emptied_held}");
let emptied_id = s
.store_pending_preflight_with_limit(memory_preflight("emptied.psd", crate::jobs::OpenSource::Bytes(emptied)), emptied_held)
.expect("the allocation fits the cap that admits it");
assert_eq!(s.pending_preflight_bytes().unwrap(), emptied_held, "an empty length is not zero bytes held");
s.clear_pending_preflights();
assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "clear releases every held allocation");
assert!(s.cancel_pending_preflight(emptied_id).is_none());
}
#[test]
fn approve_memory_is_neither_journaled_nor_recorded_in_an_action() {
let mut s = Session::new();
let id = s.store_pending_preflight(memory_preflight("cancel.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 4])))).unwrap();
s.execute("actions.record", json!({"name": "Memory approvals"})).unwrap();
let r = s.execute("file.approveMemory", json!({"id": id, "approve": false})).unwrap();
assert_eq!((r["approved"].clone(), r["cancelled"].clone()), (json!(false), json!(true)));
s.execute("actions.stop", json!({})).unwrap();
assert!(s.journal.iter().all(|(command, _)| command != "file.approveMemory"), "one-shot approval must not become a journal entry: {:?}", s.journal);
let action = s.actions.list.first().expect("the recorded action");
assert!(action.steps.iter().all(|(command, _)| command != "file.approveMemory"), "one-shot approval must not replay from an action: {:?}", action.steps);
}
#[test]
fn approve_memory_releases_the_preflight_when_the_hard_limit_refuses_it() {
let gb = 1u64 << 30;
let mut s = Session::new();
let preflight = crate::jobs::PendingPsdPreflight {
required: 8 * gb,
soft_limit: 6 * gb,
hard_limit: 9 * gb,
available_ram: Some(12 * gb),
..memory_preflight("ram_drop.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 16])))
};
let id = s.store_pending_preflight(preflight).unwrap();
let snap_low = photocraft_io::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None };
let expected_limit = photocraft_io::memory::resolve_budget(snap_low, None).hard_limit;
photocraft_io::memory::with_mock_memory(snap_low, || {
let err = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false})).unwrap_err();
match &err {
EngineError::PsdHardBudget { name, required, limit } => {
assert_eq!(name, "ram_drop.psd");
assert_eq!((*required, *limit), (8 * gb, expected_limit));
}
other => panic!("the hard refusal must keep its fields, got {other}"),
}
});
assert!(s.take_pending_preflight(id).is_none(), "a hard refusal releases the held source");
assert_eq!(s.pending_preflight_bytes().unwrap(), 0);
}
#[test]
fn open_as_and_place_keep_the_typed_hard_budget_fields() {
let gb = 1u64 << 30;
let dir = tmp("hard_budget");
let path = join(&dir, "big.psd");
let mut src = Session::new();
src.execute("file.new", json!({"width": 4, "height": 4, "depth": 8})).unwrap();
std::fs::write(&path, photocraft_io::export(&src.active().unwrap().doc, "x.psd", &Default::default()).unwrap().bytes).unwrap();
// An estimate over the resolved hard ceiling is refused, and no approval raises the ceiling.
// The estimate charge is a test seam so the fixture stays tiny.
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None };
let hard = photocraft_io::memory::resolve_budget(snap, None).hard_limit;
assert!(hard < u64::MAX);
photocraft_io::memory::with_mock_memory(snap, || {
photocraft_io::psd_budget::with_test_estimate_charge(hard + 1, || {
let mut s = Session::new();
let err = s.execute("file.openAs", json!({"path": path.clone(), "approveHighMemory": true})).unwrap_err();
match &err {
EngineError::PsdHardBudget { name, required, limit } => {
assert_eq!(name, &path);
assert!(*required > hard && *limit == hard);
}
other => panic!("openAs must keep name/required/limit, got {other}"),
}
let mut s = session(8, 8, 8);
let err = s.execute("file.placeEmbedded", json!({"path": path.clone(), "approveHighMemory": true})).unwrap_err();
match &err {
EngineError::PsdHardBudget { required, limit, .. } => assert!(*required > hard && *limit == hard),
other => panic!("place must keep required/limit, got {other}"),
}
});
});
}
+97 -11
View File
@@ -263,10 +263,90 @@ type ImportFrames = fn(
/// Frame storage one footage import may keep (whole tiles, all frames together).
const MAX_FOOTAGE_BYTES: u64 = 2 << 30;
/// The footage frame limit this import applies: the production cap, or a test scope's lowered
/// cap so a regression can reach the refusal without keeping gibibytes of frames.
fn footage_byte_limit() -> u64 {
#[cfg(test)]
if let Some(limit) = limits::max_footage_bytes() {
return limit;
}
MAX_FOOTAGE_BYTES
}
/// Import options for footage files. A test scope may lower the PSD/layered-TIFF memory limit,
/// which the user's preferences do not expose, to reach an admission refusal on a small file.
fn footage_import_options(s: &Session) -> photocraft_io::ImportOptions {
#[cfg(test)]
if let Some(limit) = limits::psd_max_pixel_bytes() {
return photocraft_io::ImportOptions { psd_max_pixel_bytes: limit, ..crate::jobs::import_options(s.prefs()) };
}
crate::jobs::import_options(s.prefs())
}
/// Per-thread test overrides for the footage import limits. A scope restores the previous values
/// on drop, and the thread-local keeps parallel tests from lowering each other's limits.
#[cfg(test)]
mod limits {
use std::cell::Cell;
#[derive(Clone, Copy, Default)]
struct Overrides {
psd_max_pixel_bytes: Option<u64>,
max_footage_bytes: Option<u64>,
}
thread_local! {
static CURRENT: Cell<Overrides> = const { Cell::new(Overrides { psd_max_pixel_bytes: None, max_footage_bytes: None }) };
}
/// Restores the previous overrides when dropped.
pub(crate) struct Scoped(Overrides);
impl Scoped {
/// Lowers the PSD/layered-TIFF memory admission limit for the current thread.
pub(crate) fn psd_max_pixel_bytes(limit: u64) -> Self {
Self::set(Overrides { psd_max_pixel_bytes: Some(limit), ..Default::default() })
}
/// Lowers the retained footage-frame limit for the current thread.
pub(crate) fn max_footage_bytes(limit: u64) -> Self {
Self::set(Overrides { max_footage_bytes: Some(limit), ..Default::default() })
}
fn set(next: Overrides) -> Self {
Self(CURRENT.with(|current| current.replace(next)))
}
}
impl Drop for Scoped {
fn drop(&mut self) {
CURRENT.with(|current| current.set(self.0));
}
}
pub(super) fn psd_max_pixel_bytes() -> Option<u64> {
CURRENT.with(|current| current.get().psd_max_pixel_bytes)
}
pub(super) fn max_footage_bytes() -> Option<u64> {
CURRENT.with(|current| current.get().max_footage_bytes)
}
}
/// The engine error for a failed page of a multi-page TIFF. A memory refusal keeps its typed form,
/// so the UI, control channel and agents still get the required and limit fields they need to
/// offer approval or explain the hard limit; any other failure keeps the page's text.
fn tiff_page_error(display: &std::path::Path, name: &str, page: usize, error: photocraft_io::IoError) -> EngineError {
match error {
photocraft_io::IoError::PsdApprovalRequired { .. } | photocraft_io::IoError::PsdImportBudget { .. } => crate::error::io_open_error(name, error),
error => EngineError::Other(format!("`{}` page {}: {error}", display.display(), page + 1)),
}
}
/// Load frames from `path`: a single image (1 frame, or every frame of an animated GIF or WebP), or a
/// directory of images (sorted = an image sequence). Each becomes a full raster frame in the
/// document's format.
fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result<Footage> {
fn load_frames(path: &str, fmt: photocraft_color::PixelFormat, opts: &photocraft_io::ImportOptions) -> Result<Footage> {
let p = std::path::Path::new(path);
let is_img = |f: &std::path::Path| {
matches!(
@@ -292,6 +372,7 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result<Footage
let mut delays = Vec::new();
// Each frame stores whole tiles however little it draws, so count the tiles kept so far.
let mut kept_bytes = 0u64;
let max_footage_bytes = footage_byte_limit();
let mut keep = |frames: &mut Vec<Surface>, surface: Surface| -> std::result::Result<(), String> {
// A frame of fully transparent pixels stores no tiles, so the count needs its own limit.
if frames.len() >= crate::timeline_cmds::MAX_DURATION {
@@ -299,8 +380,8 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result<Footage
}
let tile = u64::from(photocraft_geom::TILE_SIZE.unsigned_abs()).pow(2) * surface.format().bytes_per_pixel() as u64;
kept_bytes = kept_bytes.saturating_add(tile.saturating_mul(surface.tile_count() as u64));
if kept_bytes > MAX_FOOTAGE_BYTES {
return Err(format!("the footage needs more than {} MiB of frames", MAX_FOOTAGE_BYTES >> 20));
if kept_bytes > max_footage_bytes {
return Err(format!("the footage needs more than {} MiB of frames", max_footage_bytes >> 20));
}
frames.push(surface);
Ok(())
@@ -345,15 +426,20 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result<Footage
)));
}
for page in pages {
let doc = photocraft_io::import_tiff_page(&name, &bytes, Some(page))
.map_err(|e| EngineError::Other(format!("`{}` page {}: {e}", f.display(), page + 1)))?
// Same admission policy, caller limit and import settings as any other TIFF
// page import: a multi-page TIFF is not a way around the memory budget.
let doc = photocraft_io::import_tiff_page_with_options(&name, &bytes, Some(page), opts, &photocraft_raster::Interrupt::NONE)
.map_err(|e| tiff_page_error(f, &name, page, e))?
.document;
frames.push(crate::file_cmds::flattened(&doc, fmt));
// The page is flattened before admission of the next one, so the retained
// frames of every page count against the footage limit, as GIF and WebP
// frames do.
keep(&mut frames, crate::file_cmds::flattened(&doc, fmt)).map_err(|msg| EngineError::Other(format!("`{}`: {msg}", f.display())))?;
}
continue;
}
}
let mut doc = crate::file_cmds::import(&name, &bytes)?;
let mut doc = crate::file_cmds::import_with_options(&name, &bytes, opts)?;
// A Targa's alpha opens as a channel (as in Photoshop); a frame's alpha is transparency.
if f.extension().is_some_and(|e| e.eq_ignore_ascii_case("tga")) {
photocraft_io::tga_alpha_channel_to_transparency(&mut doc);
@@ -373,7 +459,7 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| EngineError::BadParams { cmd: "layer.videoLayers.newVideoLayerFromFile".into(), msg: "need `path`".into() })?
.to_string();
let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format();
let Footage { frames, fps: footage_fps } = load_frames(&path, fmt)?;
let Footage { frames, fps: footage_fps } = load_frames(&path, fmt, &footage_import_options(s))?;
// An explicit `fps` wins, then the rate the footage implies, then 30.
let fps = crate::timeline_cmds::fps_param("layer.videoLayers.newVideoLayerFromFile", p)?.or(footage_fps).unwrap_or(30.0);
let n = frames.len();
@@ -410,7 +496,7 @@ fn replace_footage(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| EngineError::BadParams { cmd: "layer.videoLayers.replaceFootage".into(), msg: "need `path`".into() })?
.to_string();
let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format();
let frames = load_frames(&path, fmt)?.frames;
let frames = load_frames(&path, fmt, &footage_import_options(s))?.frames;
edit_video(s, "Replace Footage", move |v, _| {
v.original_frames = Some(frames.clone());
v.frames = frames;
@@ -446,7 +532,7 @@ fn reload_frame(s: &mut Session, _p: &Value) -> Result<Value> {
};
// The footage path is stored in the document.
let file = crate::doc_path::resolve(&path).map_err(|why| crate::doc_path::refusal("the footage", &path, why))?;
let frames = load_frames(&file.to_string_lossy(), fmt)?.frames;
let frames = load_frames(&file.to_string_lossy(), fmt, &footage_import_options(s))?.frames;
edit_video(s, "Reload Frame", move |v, _| {
v.original_frames = Some(frames.clone());
v.frames = frames;
@@ -471,7 +557,7 @@ fn frames_to_layers(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| EngineError::BadParams { cmd: "file.import.videoFramesToLayers".into(), msg: "need `path`".into() })?
.to_string();
let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format();
let frames = load_frames(&path, fmt)?.frames;
let frames = load_frames(&path, fmt, &footage_import_options(s))?.frames;
let n = frames.len();
s.edit("Video Frames to Layers", |doc, active| {
let mut above = *active;
+162 -2
View File
@@ -99,6 +99,46 @@ fn write_tiff(path: &str, pages: &[(u32, u32, u8, u32)]) {
std::fs::write(path, f).unwrap();
}
/// A real layered TIFF from the exporter: two 8×6 raster layers and Photoshop layer data in tag
/// 37724, in one full-resolution page.
fn layered_tiff_bytes() -> Vec<u8> {
let mut doc = Document::new("layered", photocraft_geom::Size::new(8, 6), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
let fmt = doc.pixel_format();
for name in ["bottom", "top"] {
let mut surface = Surface::new(fmt);
surface.write_interleaved(photocraft_geom::Rect::new(0, 0, 8, 6), &vec![96u8; 8 * 6 * fmt.bytes_per_pixel()]);
doc.layers.push(Layer::new(name, LayerContent::Raster(surface)));
}
let bytes =
photocraft_io::export(&doc, "layered.tif", &photocraft_io::ExportOptions { tiff_layers: true, ..Default::default() }).expect("a layered TIFF").bytes;
assert_eq!(bytes.get(0..2), Some(&b"II"[..]), "the TIFF exporter writes little-endian files here");
assert_eq!(u16::from_le_bytes([bytes[2], bytes[3]]), 42, "a classic TIFF");
bytes
}
/// [`layered_tiff_bytes`] extended to two pages by appending a copy of its first directory as the
/// next one. The copied directory keeps the original tag and pixel offsets, so both pages carry
/// genuine layer data without hand-written Photoshop blocks; the file stays small, and the second
/// page is never decoded.
fn write_layered_multipage_tiff(path: &str) {
let bytes = layered_tiff_bytes();
let u16_at = |o: usize| u16::from_le_bytes([bytes[o], bytes[o + 1]]);
let first_ifd = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;
let count = u16_at(first_ifd) as usize;
let dir_len = 2 + count * 12 + 4;
let mut f = bytes.clone();
if f.len() % 2 == 1 {
f.push(0);
}
let second_ifd = f.len();
f.extend_from_slice(&bytes[first_ifd..first_ifd + dir_len]);
let second_next = second_ifd + 2 + count * 12;
f[second_next..second_next + 4].copy_from_slice(&0u32.to_le_bytes());
let first_next = first_ifd + 2 + count * 12;
f[first_next..first_next + 4].copy_from_slice(&u32::try_from(second_ifd).expect("a small TIFF").to_le_bytes());
std::fs::write(path, f).expect("write the two-page TIFF");
}
/// #6379: Video Frames to Layers takes every page of a multi-page TIFF, one layer each, in
/// order, as it takes a GIF's frames; a thumbnail is not a page. A single-page TIFF is one frame.
#[test]
@@ -145,6 +185,121 @@ fn video_frames_to_layers_refuses_a_tiff_with_an_incomplete_page_list() {
assert_eq!(s.active().unwrap().doc.layers.len(), before, "nothing imported");
}
/// #10897 review: a page refused by the PSD memory admission must reach the caller typed, so the
/// UI, control channel and agents can offer approval or explain the hard limit; a multi-page TIFF
/// is not a way to get a text-only refusal. Every other page failure keeps its file and page text.
#[test]
fn tiff_page_errors_keep_memory_refusals_typed_and_other_context() {
let display = std::path::Path::new("/tmp/footage/pages.tif");
let name = "/tmp/footage/pages.tif";
let refusal = photocraft_io::IoError::PsdApprovalRequired { required: 9_000, soft_limit: 8_000, hard_limit: 16_000, available_ram: Some(4_000) };
match tiff_page_error(display, name, 1, refusal) {
EngineError::PsdApprovalRequired { name: named, required, soft_limit, hard_limit, available_ram } => {
assert_eq!(named, name);
assert_eq!((required, soft_limit, hard_limit, available_ram), (9_000, 8_000, 16_000, Some(4_000)));
}
other => panic!("page 2 approval refusal lost its fields: {other:?}"),
}
let hard = photocraft_io::IoError::PsdImportBudget { required: 9_000, limit: 8_000 };
match tiff_page_error(display, name, 2, hard) {
EngineError::PsdHardBudget { name: named, required, limit } => {
assert_eq!(named, name);
assert_eq!((required, limit), (9_000, 8_000));
}
other => panic!("page 3 hard refusal lost its fields: {other:?}"),
}
let broken = photocraft_io::IoError::Unsupported("corrupt page".into());
let err = tiff_page_error(display, name, 0, broken);
assert!(matches!(err, EngineError::Other(_)), "{err:?}");
let msg = err.to_string();
assert!(msg.contains("pages.tif") && msg.contains("page 1") && msg.contains("corrupt page"), "{msg}");
}
/// #10897 review: a multi-page TIFF page with Photoshop layer data is admitted like a PSD. A tiny
/// explicit caller limit must reach the caller as the typed `PsdHardBudget`, with the file name,
/// required bytes and limit intact, and the document must be left untouched. A helper-only test
/// would still pass if the page loop turned that refusal into text.
#[test]
fn video_frames_to_layers_keeps_a_layered_tiff_page_refusal_typed() {
let dir = tmpdir("tiff-typed");
let path = format!("{dir}/layered.tif");
write_layered_multipage_tiff(&path);
let mut s = session();
let before_layers = s.active().unwrap().doc.layers.len();
let before_active = s.active().unwrap().active_layer;
let _limit = super::limits::Scoped::psd_max_pixel_bytes(1);
let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err();
match err {
EngineError::PsdHardBudget { name, required, limit } => {
assert_eq!(name, path);
assert_eq!(limit, 1);
assert!(required > limit, "the page estimate must be past the caller's limit: {required} > {limit}");
}
other => panic!("the layered page's refusal lost its typed fields: {other:?}"),
}
assert_eq!(s.active().unwrap().doc.layers.len(), before_layers, "no partial frame layers");
assert_eq!(s.active().unwrap().active_layer, before_active, "the active layer is unchanged");
}
/// #10897 review: every page of a multi-page TIFF goes through the footage `keep` budget, as a
/// GIF's frames do. Before, the pages were pushed straight into `frames`, so many large pages could
/// keep more than the cap without an error. A thread-local test scope lowers the cap, so the
/// regression needs a few tiles of memory rather than gibibytes.
#[test]
fn video_frames_to_layers_enforces_the_footage_limit_on_every_tiff_page() {
let dir = tmpdir("tiff-budget");
let path = format!("{dir}/pages.tif");
let mut s = session();
let fmt = s.active().unwrap().doc.pixel_format();
let tile = u64::from(photocraft_geom::TILE_SIZE.unsigned_abs()).pow(2) * fmt.bytes_per_pixel() as u64;
let budget = 1u64 << 20;
assert!(tile < budget, "one page must fit in the lowered budget");
// One more page than fits in the budget: only the accumulation can refuse it.
let pages = usize::try_from(budget / tile + 1).expect("a small page count");
write_tiff(&path, &vec![(16, 16, 40, 0); pages]);
let before = s.active().unwrap().doc.layers.len();
let _limit = super::limits::Scoped::max_footage_bytes(budget);
let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err().to_string();
assert!(err.contains("pages.tif") && err.contains("more than 1 MiB"), "{err}");
assert_eq!(s.active().unwrap().doc.layers.len(), before, "nothing imported");
}
/// #10897 review: a single-page layered TIFF does not take the multi-page branch, so it falls
/// through to the ordinary single-file import. That import must carry the footage import settings,
/// including the PSD/layered-TIFF memory limit the caller lowered; before, it called the default
/// import and ignored the limit, so this refusal was never typed (and a caller limit could be
/// bypassed). The same file imports as one frame when the limit is not lowered.
#[test]
fn video_frames_to_layers_uses_the_footage_limit_for_a_single_page_layered_tiff() {
let dir = tmpdir("tiff-single-typed");
let path = format!("{dir}/layered.tif");
std::fs::write(&path, layered_tiff_bytes()).expect("write the layered TIFF");
let mut s = session();
let before_layers = s.active().unwrap().doc.layers.len();
let before_active = s.active().unwrap().active_layer;
{
let _limit = super::limits::Scoped::psd_max_pixel_bytes(1);
let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err();
match err {
EngineError::PsdHardBudget { name, required, limit } => {
assert_eq!(name, path);
assert_eq!(limit, 1);
assert!(required > limit, "the page estimate must be past the caller's limit: {required} > {limit}");
}
other => panic!("the single-page layered TIFF's refusal lost its typed fields: {other:?}"),
}
}
assert_eq!(s.active().unwrap().doc.layers.len(), before_layers, "no partial frame layers");
assert_eq!(s.active().unwrap().active_layer, before_active, "the active layer is unchanged");
// The same page imports normally under the budget the footage command always applied.
let r = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap();
assert_eq!(r["layers"], 1, "one page is one frame");
assert_eq!(s.active().unwrap().doc.layers.len(), before_layers + 1);
}
#[test]
fn new_video_layer_from_image_sequence() {
let dir = tmpdir("seq");
@@ -382,8 +537,13 @@ fn tga_sequence_frames_keep_their_transparency() {
let dir = tmpdir("tga");
write_tga(&format!("{dir}/f01.tga"));
write_tga(&format!("{dir}/f02.tga"));
let frames =
load_frames(&dir, photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true)).unwrap().frames;
let frames = load_frames(
&dir,
photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true),
&photocraft_io::ImportOptions::default(),
)
.unwrap()
.frames;
assert_eq!(frames.len(), 2);
for f in &frames {
assert_eq!(f.pixel(2, 6), vec![1.0, 0.0, 0.0, 1.0]);
+39 -1
View File
@@ -1,7 +1,7 @@
use super::LayerId;
use crate::command_hints;
#[derive(Debug, thiserror::Error)]
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
pub enum EngineError {
/// Displays with the nearest registered ids, if any ([`command_hints`], #3674).
#[error("unknown command `{id}`{hint}", id = .0, hint = command_hints::unknown_command_hint(.0))]
@@ -18,6 +18,17 @@ pub enum EngineError {
/// ids are not positions (#5058).
#[error("no such layer {}; {known}", id.0)]
UnknownLayer { id: LayerId, known: String },
/// Opening a PSD/PSB file requires explicit high-memory confirmation.
#[error("opening “{name}” requires explicit memory approval: {required} bytes required (soft limit {soft_limit}, hard limit {hard_limit})")]
PsdApprovalRequired { name: String, required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option<u64> },
/// The file's estimated memory cannot be admitted within the hard ceiling, which no approval
/// can raise. The requirement may equal the ceiling when the estimate saturated.
#[error("cannot open “{name}”: its estimated memory requirement of {required} bytes cannot be admitted within the {limit} byte hard limit on this machine")]
PsdHardBudget { name: String, required: u64, limit: u64 },
/// The file behind an opened handle is not the one whose memory estimate was approved.
/// The document is discarded and is not opened.
#[error("“{name}” changed since it was checked; open it again to approve the new file")]
SourceChanged { name: String },
#[error("{0}")]
Other(String),
/// A background job was cancelled (see [`jobs`]); nothing changed.
@@ -27,6 +38,33 @@ pub enum EngineError {
pub type Result<T> = std::result::Result<T, EngineError>;
impl EngineError {
/// Whether an approval-required error also carries the unknown-capacity warning: capacity was
/// unknown when the estimate was made and the estimate is above the warning threshold. A
/// fresh measurement or a known capacity never sets it, and no number is invented for a
/// capacity that could not be measured.
pub fn uncertain_capacity_warning(&self) -> bool {
match self {
Self::PsdApprovalRequired { required, available_ram, .. } => photocraft_io::memory::uncertain_capacity_warning(*required, *available_ram),
_ => false,
}
}
}
/// Maps an io open/import failure to the engine's typed errors, preserving the memory fields the
/// UI, control channel and agents need to answer or explain it.
pub(crate) fn io_open_error(name: &str, error: photocraft_io::IoError) -> EngineError {
use photocraft_io::IoError;
match error {
IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram } => {
EngineError::PsdApprovalRequired { name: name.to_string(), required, soft_limit, hard_limit, available_ram }
}
IoError::PsdImportBudget { required, limit } => EngineError::PsdHardBudget { name: name.to_string(), required, limit },
IoError::SourceChanged => EngineError::SourceChanged { name: name.to_string() },
error => EngineError::Other(format!("{name}: {error}")),
}
}
impl From<photocraft_raster::AllocationError> for EngineError {
fn from(error: photocraft_raster::AllocationError) -> Self {
Self::Other(format!("not enough memory for this operation ({error}); the document was not changed"))
+411 -57
View File
@@ -170,6 +170,11 @@ pub struct JobEvent {
pub label: String,
pub document: Option<DocId>,
pub outcome: JobOutcome,
/// The typed failure behind a failed `outcome`: a hard-budget refusal keeps its
/// name/required/limit, an approval request keeps its limits, a changed source keeps its
/// kind. `None` for done, cancelled and panics without a typed error. Not serialized;
/// `JobInfo::error` remains the display string on the wire.
pub error: Option<EngineError>,
}
/// A job's state for the UI, the control channel and MCP (`jobs.list`).
@@ -192,6 +197,10 @@ pub struct JobInfo {
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// The typed failure behind `error`, for callers in this process (not serialized: the wire
/// form is the message, as before).
#[serde(skip)]
pub error_kind: Option<EngineError>,
}
type Payload = Box<dyn Any + Send>;
@@ -273,6 +282,7 @@ impl Running {
elapsed_ms: now_ms() - self.started_ms,
result: None,
error: None,
error_kind: None,
}
}
}
@@ -340,16 +350,29 @@ fn independent_of_document(id: &str) -> bool {
PREFIXES.iter().any(|p| id.starts_with(p)) || IDS.contains(&id)
}
/// Imports the file at `path`, taking its identity from the very handle it decodes.
///
/// `expected` is the identity approved for this file, if any. It is checked against the opened
/// handle before decoding and again when the memory preflight pauses for approval, so the
/// document opened is the approved file even if the path is replaced meanwhile. `opened` receives
/// the handle's identity as soon as it is known, including when the import stops for approval.
#[cfg(not(target_arch = "wasm32"))]
fn import_path(
name: &str,
path: &str,
opts: &photocraft_io::ImportOptions,
expected: Option<&SourceFingerprint>,
ctl: &photocraft_raster::Interrupt,
opened: &mut Option<photocraft_io::FileIdentity>,
) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> {
let expected = match expected {
None => None,
Some(SourceFingerprint::Path { identity, .. }) => Some(identity),
Some(SourceFingerprint::Bytes { .. }) => return Err(photocraft_io::IoError::SourceChanged),
};
// Bounded reads, and a clear error for a file larger than memory (#375); a PSD/PSB is
// parsed from the open file instead of being read whole.
photocraft_io::import_file_for_open_with(name, std::path::Path::new(path), opts, ctl)
// streamed from the open file instead of being read whole.
photocraft_io::import_file_for_open_verified(name, std::path::Path::new(path), expected, opts, ctl, opened)
}
#[cfg(target_arch = "wasm32")]
@@ -357,7 +380,9 @@ fn import_path(
_: &str,
path: &str,
_: &photocraft_io::ImportOptions,
_: Option<&SourceFingerprint>,
_: &photocraft_raster::Interrupt,
_: &mut Option<photocraft_io::FileIdentity>,
) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> {
Err(photocraft_io::IoError::Read(format!("cannot open paths on the web: {path}")))
}
@@ -540,6 +565,76 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor
}
}
/// Fingerprint verifying that a source has not changed between preflight and approval.
///
/// A path's fingerprint is the [`photocraft_io::FileIdentity`] of an opened handle, never a path
/// stat made before a separate open: the importer takes it from the very handle it decodes
/// (`photocraft_io::import_file_for_open_verified`), so a path replaced or rewritten between
/// the estimate and the approval is refused with [`EngineError::SourceChanged`]. The Unix
/// identity includes the inode change time and nanoseconds, so restoring a modification time
/// cannot hide a same-size rewrite.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SourceFingerprint {
Bytes { len: usize, identity: usize },
Path { path: String, identity: photocraft_io::FileIdentity },
}
impl SourceFingerprint {
/// Fingerprint of `source`.
///
/// An in-memory source's identity is its shared buffer. A path is inspected here for
/// discovery only; the decode path re-reads its identity from the handle it opens. Fails
/// closed when the identity data cannot be read.
pub fn of(source: &OpenSource) -> Result<Self> {
match source {
OpenSource::Bytes(b) => Ok(SourceFingerprint::Bytes { len: b.len(), identity: Arc::as_ptr(b) as usize }),
OpenSource::Path(p) => {
Ok(Self::path(p.clone(), photocraft_io::FileIdentity::of_path(std::path::Path::new(p)).map_err(|e| EngineError::Other(format!("{p}: {e}")))?))
}
}
}
/// Fingerprint of the file identity read from an opened handle for `path`.
pub fn path(path: String, identity: photocraft_io::FileIdentity) -> Self {
SourceFingerprint::Path { path, identity }
}
/// The handle identity a path fingerprint compares against, if this is one.
pub fn file_identity(&self) -> Option<&photocraft_io::FileIdentity> {
match self {
SourceFingerprint::Path { identity, .. } => Some(identity),
SourceFingerprint::Bytes { .. } => None,
}
}
/// Whether both fingerprints capture the same source identity (and, for a path, the same path).
pub fn matches(&self, other: &Self) -> bool {
self == other
}
/// Re-reads `source`'s fingerprint and compares it with this one; an unreadable source does not match.
pub fn matches_source(&self, source: &OpenSource) -> bool {
match Self::of(source) {
Ok(cur) => self.matches(&cur),
Err(_) => 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<u64>,
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
@@ -555,6 +650,137 @@ impl Session {
self.dispatch(id, params, true)
}
pub const MAX_PENDING_PREFLIGHTS: usize = 32;
/// Most bytes of file data pending approvals may keep alive together.
///
/// This is a retention bound for the *sources* of files waiting for an answer, not a pixel
/// budget and not an admission limit: only an [`OpenSource::Bytes`] source holds data (a path
/// streams from its file once opened), the allocation's capacity is charged rather than its
/// contents, and one shared buffer counts once however many preflights refer to it. 1 GiB is
/// chosen conservatively: it is below the 2 GiB web hard
/// product cap, so even a web session that queues several large dropped files cannot spend
/// the whole hard budget on data it has not decoded, and a native session keeps a comparable
/// amount out of the adaptive allowance. A file that would exceed the cap cannot become
/// pending: it is refused with an error instead of being decoded, and the caller can answer
/// or cancel queued prompts and try again, rather than holding an unbounded amount of memory
/// for unanswered prompts. The record count
/// ([`Self::MAX_PENDING_PREFLIGHTS`]) stays as a separate bound, so many small files are
/// bounded too.
pub const MAX_PENDING_PREFLIGHT_BYTES: u64 = 1 << 30;
/// Queues an approval prompt, assigning its id, and enforces both the pending-count and
/// retained-byte limits.
pub fn store_pending_preflight(&mut self, preflight: PendingPsdPreflight) -> Result<u64> {
self.store_pending_preflight_with_limit(preflight, Self::MAX_PENDING_PREFLIGHT_BYTES)
}
/// [`Self::store_pending_preflight`] with an explicit retention cap (tests use a tiny one so
/// the boundary is exercised without holding a gigabyte).
pub(crate) fn store_pending_preflight_with_limit(&mut self, mut preflight: PendingPsdPreflight, byte_limit: u64) -> Result<u64> {
if self.pending_preflights.len() >= Self::MAX_PENDING_PREFLIGHTS {
return Err(EngineError::Other("too many pending high-memory preflights waiting for confirmation".into()));
}
let held = self.pending_preflight_bytes_with(&preflight.source)?;
if held > byte_limit {
return Err(EngineError::Other(format!(
"too much memory is already held by files waiting for a memory approval ({held} bytes, limit {byte_limit}); answer or cancel one of them and try again"
)));
}
loop {
self.next_pending_preflight = self.next_pending_preflight.checked_add(1).unwrap_or(1);
if self.next_pending_preflight != 0 && !self.pending_preflights.iter().any(|p| p.id == self.next_pending_preflight) {
break;
}
}
preflight.id = self.next_pending_preflight;
self.pending_preflights.push(preflight);
Ok(self.next_pending_preflight)
}
/// Bytes held alive by the queued preflights, counting an `Arc<Vec<u8>>` shared by several of
/// them once. Computed from the queue, so approving, cancelling, refusing or clearing always
/// releases the charge; a rejected preflight never adds one.
pub fn pending_preflight_bytes(&self) -> Result<u64> {
Self::retained_source_bytes(self.pending_preflights.iter().map(|p| &p.source))
}
/// [`Self::pending_preflight_bytes`] as if `incoming` were queued too, so accepting it can be
/// checked before the list is changed.
fn pending_preflight_bytes_with(&self, incoming: &OpenSource) -> Result<u64> {
let mut sources: Vec<&OpenSource> = self.pending_preflights.iter().map(|p| &p.source).collect();
sources.push(incoming);
Self::retained_source_bytes(sources)
}
/// Total retained capacity of distinct in-memory sources, counting a shared buffer once.
///
/// Capacity, not length, is charged because a truncated `Vec` keeps its allocation; overflow
/// is an error rather than a wrapped total.
fn retained_source_bytes<'a>(sources: impl IntoIterator<Item = &'a OpenSource>) -> Result<u64> {
let mut seen: Vec<usize> = Vec::new();
let mut total: u64 = 0;
for source in sources {
let OpenSource::Bytes(bytes) = source else { continue };
let identity = Arc::as_ptr(bytes) as usize;
// Distinct live allocations cannot share an address, so identity dedupes clones of
// one buffer without under-counting two different files with equal contents.
if seen.contains(&identity) {
continue;
}
seen.push(identity);
// The allocation is what stays resident, not its contents: a `Vec` that once held a
// large file keeps that capacity after being truncated, so charging `len()` would
// under-count the memory a pending prompt holds. Overflow is an error, never a wrap.
let held = u64::try_from(bytes.capacity()).unwrap_or(u64::MAX);
total = total.checked_add(held).ok_or_else(|| EngineError::Other("held file size overflow while counting pending memory approvals".into()))?;
}
Ok(total)
}
/// Removes and returns the pending preflight with `id`, releasing the source it held.
pub fn take_pending_preflight(&mut self, id: u64) -> Option<PendingPsdPreflight> {
let i = self.pending_preflights.iter().position(|p| p.id == id)?;
Some(self.pending_preflights.remove(i))
}
/// Cancels the pending preflight with `id` by removing it; `None` means no such prompt.
pub fn cancel_pending_preflight(&mut self, id: u64) -> Option<PendingPsdPreflight> {
self.take_pending_preflight(id)
}
/// Drops every pending preflight, releasing all retained source buffers.
pub fn clear_pending_preflights(&mut self) {
self.pending_preflights.clear();
}
/// Starts an open with high-memory approval already granted, on a background worker.
/// `expected_fingerprint`, when given, must still match the decoded source.
pub fn start_open_approved(
&mut self,
name: &str,
source: OpenSource,
confirm_damage: bool,
approved_estimate: Option<u64>,
expected_fingerprint: Option<SourceFingerprint>,
) -> Result<Started> {
self.start_open_approved_with_background(name, source, confirm_damage, approved_estimate, expected_fingerprint, true)
}
/// [`Self::start_open_approved`] with an explicit choice between a background worker and
/// inline work.
pub fn start_open_approved_with_background(
&mut self,
name: &str,
source: OpenSource,
confirm_damage: bool,
approved_estimate: Option<u64>,
expected_fingerprint: Option<SourceFingerprint>,
background: bool,
) -> Result<Started> {
self.start_open_inner(name, source, confirm_damage, true, approved_estimate, expected_fingerprint, background)
}
/// Open a file in the background: read (for a path) and decode on a worker, with progress
/// (per layer for PSD/PSB) and cancellation, then add the document like
/// [`Session::open_document`] (Color Settings policies apply). `name` names the document.
@@ -565,76 +791,175 @@ impl Session {
/// result is `{held, name, warnings, color}` (`color` the question): take it with
/// [`Session::take_held_open`] once answered.
pub fn start_open(&mut self, name: &str, source: OpenSource) -> Result<Started> {
self.start_open_inner(name, source, false)
self.start_open_inner(name, source, false, false, None, None, true)
}
/// 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<Started> {
self.start_open_inner(name, source, true)
self.start_open_for_user_with_background(name, source, true)
}
/// Interactive open with an explicit background/inline choice: damaged PSD content and
/// high-memory preflights wait for the user instead of opening non-interactively.
pub fn start_open_for_user_with_background(&mut self, name: &str, source: OpenSource, background: bool) -> Result<Started> {
self.start_open_inner(name, source, true, false, None, None, background)
}
/// 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<Started> {
// Keep the worker and apply closures together with their execution options.
#[allow(clippy::too_many_arguments)]
fn start_open_inner(
&mut self,
name: &str,
source: OpenSource,
confirm_damage: bool,
approve_high_memory: bool,
approved_estimate: Option<u64>,
expected_fingerprint: Option<SourceFingerprint>,
background: bool,
) -> Result<Started> {
let label = format!("Opening {name}");
let name_w = name.to_string();
let name_a = name.to_string();
let opts = import_options(self.prefs());
self.start_job(
let mut opts = import_options(self.prefs());
opts.psd_high_memory_approved = approve_high_memory;
opts.psd_approved_estimate = approved_estimate;
let test_memory_scope = photocraft_io::memory::TestMemoryScope::capture();
enum WorkResult {
Decoded(Box<(photocraft_io::ImportResult, bool)>),
PreflightNeeded { required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option<u64>, source: OpenSource, fingerprint: SourceFingerprint },
}
self.start_job_with_spawn(
OPEN_JOB,
json!({"name": name}),
&label,
false,
background,
move |ctx| {
let _test_memory = test_memory_scope.enter();
ctx.progress(0.0, "Reading");
let imported = match source {
// An in-memory source's identity is its shared buffer, known before decoding. A
// path's identity can only come from the handle the verified import opens, so
// that import compares it against `expected_fingerprint` itself, before reading
// any pixel and again after its memory preflight.
let initial_fingerprint = match &source {
OpenSource::Bytes(_) => Some(SourceFingerprint::of(&source)?),
OpenSource::Path(_) => None,
};
if let Some(expected) = &expected_fingerprint
&& let Some(current) = &initial_fingerprint
&& !expected.matches(current)
{
return Err(EngineError::SourceChanged { name: name_w.clone() });
}
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(Box::new(imported)),
Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => {
// The buffer cannot change while it is decoded, so the identity
// captured before reading is still exact.
let fingerprint = initial_fingerprint.clone().ok_or_else(|| EngineError::Other("missing source identity".into()))?;
WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: OpenSource::Bytes(bytes), fingerprint }
}
Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => {
return Err(EngineError::PsdApprovalRequired { name: name_w.clone(), required, soft_limit, hard_limit, available_ram });
}
Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled),
Err(e) => return Err(crate::error::io_open_error(&name_w, e)),
}
}
OpenSource::Path(p) => {
let mut opened = None;
let res = ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, expected_fingerprint.as_ref(), ctl, &mut opened));
match res {
Ok(imported) => WorkResult::Decoded(Box::new(imported)),
Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => {
// This identity is the one read from the handle that was
// estimated, and the verified import refused a handle that is
// not the approved file or changed while preflighting.
let identity = opened.ok_or_else(|| EngineError::Other(format!("{p}: the file's identity could not be read")))?;
let fingerprint = SourceFingerprint::path(p.clone(), identity);
WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: OpenSource::Path(p), fingerprint }
}
Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => {
return Err(EngineError::PsdApprovalRequired { name: name_w.clone(), required, soft_limit, hard_limit, available_ram });
}
Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled),
Err(e) => return Err(crate::error::io_open_error(&name_w, e)),
}
}
};
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 } => {
// The warning follows the capacity measured for this estimate: an unknown
// capacity carries no fabricated number, and above the threshold it also
// says the process or tab may run out of memory. The UI shows both.
let capacity_unknown = available_ram.is_none();
let uncertain_capacity = photocraft_io::memory::uncertain_capacity_warning(required, available_ram);
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,
"capacityUnknown": capacity_unknown,
"uncertainCapacityWarning": uncertain_capacity,
}))
}
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(imported) => {
let (mut r, damaged) = *imported;
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}))
},
)
}
@@ -653,9 +978,27 @@ impl Session {
work: impl FnOnce(&JobCtx) -> Result<T> + Send + 'static,
apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,
) -> Result<Started> {
self.jobs.spawn = true;
self.start_job_with_spawn(command, params, label, lock_document, true, work, apply)
}
// Keep the worker and apply closures together with their execution options.
/// [`Self::start_job`] with an explicit `spawn` flag: when false (or on wasm) the work runs
/// inline and its result is returned directly; otherwise it becomes a background job.
#[allow(clippy::too_many_arguments)]
pub fn start_job_with_spawn<T: Send + 'static>(
&mut self,
command: &str,
params: Value,
label: &str,
lock_document: bool,
spawn: bool,
work: impl FnOnce(&JobCtx) -> Result<T> + Send + 'static,
apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,
) -> Result<Started> {
let prev_spawn = self.jobs.spawn;
self.jobs.spawn = spawn && !cfg!(target_arch = "wasm32");
let r = run(self, label, lock_document, work, apply);
self.jobs.spawn = false;
self.jobs.spawn = prev_spawn;
let pending = self.jobs.pending.take();
match (r, pending) {
(Err(e), Some(job)) => {
@@ -720,7 +1063,9 @@ impl Session {
match self.jobs.recent.iter().rev().find(|j| j.id == id) {
Some(j) if j.state == "done" => Ok(j.result.clone().unwrap_or(Value::Null)),
Some(j) if j.state == "cancelled" => Err(EngineError::Cancelled),
Some(j) => Err(EngineError::Other(j.error.clone().unwrap_or_else(|| "the job failed".into()))),
// A typed failure keeps its fields for a caller that answers or explains it; the
// display string stays available through `jobs.list`.
Some(j) => Err(j.error_kind.clone().unwrap_or_else(|| EngineError::Other(j.error.clone().unwrap_or_else(|| "the job failed".into())))),
None => Err(EngineError::Other(format!("no job {}", id.0))),
}
}
@@ -1028,17 +1373,19 @@ impl Session {
/// Apply (or report the failure of) a job whose worker has delivered `r`.
fn finish_job(&mut self, mut job: Running, r: Result<Payload>) {
let apply = job.apply.take();
let outcome = match r {
Err(EngineError::Cancelled) => JobOutcome::Cancelled,
Err(e) => JobOutcome::Failed(e.to_string()),
Ok(_) if job.ctx.cancelled() => JobOutcome::Cancelled,
// Keep the typed error beside its display text, so `wait_job` and `JobEvent` can still
// report a hard budget's required/limit or an approval request's limits.
let (outcome, error) = match r {
Err(EngineError::Cancelled) => (JobOutcome::Cancelled, None),
Err(e) => (JobOutcome::Failed(e.to_string()), Some(e)),
Ok(_) if job.ctx.cancelled() => (JobOutcome::Cancelled, None),
Ok(payload) => match self.apply_job(&job, apply, payload) {
Ok(v) => JobOutcome::Done(v),
Err(EngineError::Cancelled) => JobOutcome::Cancelled,
Err(e) => JobOutcome::Failed(e.to_string()),
Ok(v) => (JobOutcome::Done(v), None),
Err(EngineError::Cancelled) => (JobOutcome::Cancelled, None),
Err(e) => (JobOutcome::Failed(e.to_string()), Some(e)),
},
};
self.end_job(&job, outcome);
self.end_job_with_error(&job, outcome, error);
}
fn apply_job(&mut self, job: &Running, apply: Option<Apply>, payload: Payload) -> Result<Value> {
@@ -1124,6 +1471,12 @@ impl Session {
}
fn end_job(&mut self, job: &Running, outcome: JobOutcome) {
self.end_job_with_error(job, outcome, None);
}
/// Records a finished job's terminal state (done, failed or cancelled) and optional typed
/// error in the recent-job list, invalidating any live preview.
fn end_job_with_error(&mut self, job: &Running, outcome: JobOutcome, error_kind: Option<EngineError>) {
// Every terminal path invalidates a preview, including worker errors, cancellation
// and discarded results whose document was closed or changed.
self.live_commit = None;
@@ -1136,6 +1489,7 @@ impl Session {
info.state = state;
info.result = result;
info.error = error;
info.error_kind = error_kind.clone();
if state == "done" {
info.progress = 1.0;
}
@@ -1144,7 +1498,7 @@ impl Session {
let extra = self.jobs.recent.len() - RECENT;
self.jobs.recent.drain(..extra);
}
self.jobs.events.push(JobEvent { id: job.id, command: job.command.clone(), label: job.label.clone(), document: job.doc, outcome });
self.jobs.events.push(JobEvent { id: job.id, command: job.command.clone(), label: job.label.clone(), document: job.doc, outcome, error: error_kind });
}
}
+204
View File
@@ -814,3 +814,207 @@ fn every_job_terminal_path_drops_a_live_commit_stroke() {
assert!(s.live_commit.is_none(), "terminal path {outcome} retained the preview");
}
}
#[cfg(unix)]
fn tmp_dir(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("photocraft-engine-jobs-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A tiny real PSD fixture, so an admission test never allocates anything near a threshold.
fn tiny_psd() -> Vec<u8> {
super::psd_open_fixture::make_psd(false)
}
#[cfg(target_pointer_width = "64")]
#[test]
fn approved_open_forwards_the_flag_and_the_bound_estimate() {
let gb = 1u64 << 30;
let bytes = Arc::new(tiny_psd());
// Known 8 GiB: S = 4 GiB, H = 6 GiB. The test charge puts the estimate just over S.
let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None };
photocraft_io::memory::with_mock_memory(snapshot, || {
photocraft_io::psd_budget::with_test_estimate_charge(4 * gb + 1, || {
let mut s = Session::new();
let started = s.start_open_for_user_with_background("tiny.psd", OpenSource::Bytes(Arc::clone(&bytes)), false).unwrap();
let v = match started {
Started::Done(v) => v,
Started::Job(id) => s.wait_job(id).unwrap(),
};
let id = v["pendingPreflight"].as_u64().unwrap_or_else(|| panic!("expected a memory preflight: {v}"));
assert!(v["estimated"].as_u64().unwrap() > 4 * gb, "the seam's charge is part of the estimate: {v}");
assert!(s.documents().is_empty());
// Approving forwards the one-shot flag and estimate through the real import path.
let r = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false})).unwrap();
assert_eq!(r["approved"], json!(true), "{r}");
assert!(r["result"].get("document").is_some(), "the approved import opened the document: {r}");
assert_eq!(s.documents().len(), 1);
assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "approval releases the held source bytes");
});
});
}
#[cfg(target_pointer_width = "64")]
#[test]
fn approval_is_bound_to_the_approved_estimate() {
let gb = 1u64 << 30;
let bytes = Arc::new(tiny_psd());
let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None };
photocraft_io::memory::with_mock_memory(snapshot, || {
photocraft_io::psd_budget::with_test_estimate_charge(4 * gb + 1, || {
let mut s = Session::new();
let source = OpenSource::Bytes(Arc::clone(&bytes));
let fingerprint = SourceFingerprint::of(&source).unwrap();
// Consent given for a much smaller estimate does not cover this file.
let err = s
.start_open_approved_with_background("tiny.psd", source, false, Some(1 << 20), Some(fingerprint), false)
.expect_err("a larger estimate needs fresh consent");
assert!(matches!(&err, EngineError::PsdApprovalRequired { .. }), "got {err:?}");
assert!(s.documents().is_empty());
});
});
}
#[cfg(target_pointer_width = "64")]
#[test]
fn unknown_capacity_metadata_never_invents_available_ram() {
let gb = 1u64 << 30;
let bytes = Arc::new(tiny_psd());
let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: None };
photocraft_io::memory::with_mock_memory(snapshot, || {
// Above both the 2 GiB unknown-capacity allowance and the 8 GiB warning threshold.
photocraft_io::psd_budget::with_test_estimate_charge(8 * gb + 1, || {
let mut s = Session::new();
let started = s.start_open_for_user_with_background("unknown.psd", OpenSource::Bytes(Arc::clone(&bytes)), false).unwrap();
let v = match started {
Started::Done(v) => v,
Started::Job(id) => s.wait_job(id).unwrap(),
};
assert!(v["availableRam"].is_null(), "no number is invented for an unmeasured capacity: {v}");
assert_eq!(v["capacityUnknown"], json!(true), "{v}");
assert_eq!(v["uncertainCapacityWarning"], json!(true), "{v}");
let id = v["pendingPreflight"].as_u64().unwrap();
assert!(s.take_pending_preflight(id).is_some());
});
});
}
#[test]
fn an_open_reports_a_typed_hard_budget_refusal() {
let gb = 1u64 << 30;
let bytes = Arc::new(tiny_psd());
// A measured 4 GiB gives a finite hard limit; a charge over it is refused.
let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None };
let hard = photocraft_io::memory::resolve_budget(snapshot, None).hard_limit;
assert!(hard < u64::MAX, "the test needs a finite hard limit");
photocraft_io::memory::with_mock_memory(snapshot, || {
photocraft_io::psd_budget::with_test_estimate_charge(hard + 1, || {
let mut s = Session::new();
let err = s.start_open_for_user_with_background("over.psd", OpenSource::Bytes(Arc::clone(&bytes)), false).unwrap_err();
match &err {
EngineError::PsdHardBudget { required, limit, .. } => assert!(*required > hard && *limit == hard),
other => panic!("the job must keep the hard-budget fields, got {other:?}"),
}
assert!(s.documents().is_empty());
});
});
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_failed_job_keeps_its_typed_error_for_wait_and_events() {
let mut s = Session::new();
let started = s
.start_job(
"test.hardBudget",
json!({}),
"Test hard budget",
false,
|_ctx| -> Result<()> { Err(EngineError::PsdHardBudget { name: "too-big.psd".into(), required: 9000, limit: 4000 }) },
|_, _| Ok(Value::Null),
)
.unwrap();
let id = job(started);
let err = s.wait_job(id).expect_err("the job fails");
assert!(
matches!(&err, EngineError::PsdHardBudget { name, required, limit } if name == "too-big.psd" && *required == 9000 && *limit == 4000),
"wait_job must not flatten the typed refusal: {err:?}"
);
let event = s.poll_jobs().into_iter().find(|e| e.id == id).expect("the job event");
assert!(
matches!(&event.error, Some(EngineError::PsdHardBudget { required, limit, .. }) if *required == 9000 && *limit == 4000),
"the event carries the typed refusal: {event:?}"
);
}
#[cfg(unix)]
#[test]
fn a_replaced_path_is_refused_with_the_source_identity_reason() {
let dir = tmp_dir("replaced");
let path = dir.join("source.psd");
let bytes = tiny_psd();
std::fs::write(&path, &bytes).unwrap();
let source = OpenSource::Path(path.to_string_lossy().into_owned());
let fingerprint = SourceFingerprint::of(&source).unwrap();
// A different inode with identical content and length: only the identity differs.
let replacement = dir.join("replacement.psd");
std::fs::write(&replacement, &bytes).unwrap();
std::fs::rename(&replacement, &path).unwrap();
let mut s = Session::new();
let err = s
.start_open_approved_with_background("source.psd", source.clone(), false, Some(1024), Some(fingerprint.clone()), false)
.expect_err("the handle is not the approved file");
assert!(matches!(&err, EngineError::SourceChanged { .. }), "the inline refusal must name the identity, not a parser failure: {err:?}");
assert!(s.documents().is_empty());
// The same check on the worker path: the job fails with the identity reason, not a decode error.
let started = s.start_open_approved_with_background("source.psd", source, false, Some(1024), Some(fingerprint), true).unwrap();
let Started::Job(id) = started else { panic!("expected a background job") };
let err = s.wait_job(id).expect_err("the worker's handle is not the approved file");
assert!(matches!(&err, EngineError::SourceChanged { .. }), "the background refusal must name the identity: {err:?}");
assert!(s.documents().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn a_same_size_rewrite_with_a_restored_mtime_is_refused_with_the_identity_reason() {
let dir = tmp_dir("rewrite");
let path = dir.join("source.psd");
let bytes = tiny_psd();
std::fs::write(&path, &bytes).unwrap();
let source = OpenSource::Path(path.to_string_lossy().into_owned());
let fingerprint = SourceFingerprint::of(&source).unwrap();
let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
std::thread::sleep(Duration::from_millis(10));
// Same inode, same length, same bytes, restored modification time: only ctime differs.
std::fs::write(&path, &bytes).unwrap();
std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_times(std::fs::FileTimes::new().set_modified(modified)).unwrap();
let mut s = Session::new();
let err = s
.start_open_approved_with_background("source.psd", source, false, Some(1024), Some(fingerprint), false)
.expect_err("the rewrite is not the file whose estimate was approved");
assert!(matches!(&err, EngineError::SourceChanged { .. }), "a restored mtime must not hide the rewrite: {err:?}");
assert!(s.documents().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn unix_fingerprint_detects_a_same_size_rewrite_with_a_restored_mtime() {
let dir = tmp_dir("ctime");
let path = dir.join("source.psd");
std::fs::write(&path, b"AAAAAAAAAA").unwrap();
let before = SourceFingerprint::of(&OpenSource::Path(path.to_string_lossy().into_owned())).unwrap();
let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
std::thread::sleep(Duration::from_millis(10));
std::fs::write(&path, b"BBBBBBBBBB").unwrap();
std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_times(std::fs::FileTimes::new().set_modified(modified)).unwrap();
let after = SourceFingerprint::of(&OpenSource::Path(path.to_string_lossy().into_owned())).unwrap();
let (b, a) = (before.file_identity().unwrap(), after.file_identity().unwrap());
assert_eq!((b.len, b.modified, b.ino), (a.len, a.modified, a.ino), "same length, modification time and inode");
assert_ne!((b.ctime_secs, b.ctime_nanos), (a.ctime_secs, a.ctime_nanos), "the Unix identity carries ctime, so a restored mtime cannot hide a rewrite");
assert_ne!(before, after, "a same-size rewrite with a restored mtime is a different source");
let _ = std::fs::remove_dir_all(&dir);
}
+2
View File
@@ -283,6 +283,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<jobs::PendingPsdPreflight>,
next_pending_preflight: u64,
/// Shared native memory supervision, owned and stopped by the last session using it.
scratch_runtime: Option<scratch::Runtime>,
/// [`photocraft_raster::spill::epoch`] when History's byte limits were last applied: a
+2
View File
@@ -14,6 +14,8 @@ workspace = true
corpus = []
# HEIC/HEIF decode (forwarded to photocraft-codecs; see its `heif` feature).
heif = ["photocraft-codecs/heif"]
# Test support for synthetic memory injection, estimate charges and verification across crates.
testgen = []
[dependencies]
photocraft-geom = { workspace = true }
+276 -30
View File
@@ -13,18 +13,62 @@ use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbe
/// Bytes per band when converting or exporting a band of rows at a time.
const BAND_BYTES: usize = 32 << 20;
#[cfg(test)]
thread_local! {
/// Called on this thread just before a layered TIFF's composite is decoded. A test proves
/// that admission refused a file without ever reaching that decode.
static TEST_BEFORE_COMPOSITE_DECODE: std::cell::RefCell<Option<std::rc::Rc<dyn Fn()>>> = const { std::cell::RefCell::new(None) };
}
/// Runs `f` with `hook` called on this thread just before a layered TIFF's composite is decoded.
#[cfg(test)]
pub(crate) fn with_before_composite_decode<R>(hook: std::rc::Rc<dyn Fn()>, f: impl FnOnce() -> R) -> R {
struct Reset(Option<std::rc::Rc<dyn Fn()>>);
impl Drop for Reset {
fn drop(&mut self) {
TEST_BEFORE_COMPOSITE_DECODE.with(|h| *h.borrow_mut() = self.0.take());
}
}
let prev = TEST_BEFORE_COMPOSITE_DECODE.with(|h| h.borrow_mut().replace(hook));
let _reset = Reset(prev);
f()
}
/// Runs the test hook installed by [`with_before_composite_decode`], if any.
#[cfg(test)]
fn before_composite_decode() {
if let Some(hook) = TEST_BEFORE_COMPOSITE_DECODE.with(|h| h.borrow().clone()) {
hook();
}
}
/// No-op outside tests: production decodes have no pre-composite hook.
#[cfg(not(test))]
fn before_composite_decode() {}
/// 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<ImportResult, IoError> {
import_flat_with_limit(name, bytes, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES)
import_flat_with_options(name, bytes, &crate::ImportOptions::default(), &photocraft_raster::Interrupt::NONE)
}
/// [`import_flat`] with the caller's PSD pixel allowance, which a layered TIFF is held to.
pub(crate) fn import_flat_with_limit(name: &str, bytes: &[u8], pixel_limit: u64) -> Result<ImportResult, IoError> {
/// [`import_flat`] with the user's import settings and the job's cancellation.
///
/// A layered TIFF's composite, layer and retained-image estimate is admitted through
/// [`crate::memory::evaluate_psd_admission`] with these settings; a zero
/// `psd_max_pixel_bytes` therefore means the adaptive budget, and
/// `psd_high_memory_approved`/`psd_approved_estimate` apply to it like to a PSD. The other flat
/// decoders keep their own limits.
pub(crate) fn import_flat_with_options(
name: &str,
bytes: &[u8],
opts: &crate::ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<ImportResult, IoError> {
// 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);
return import_tiff_page_with_options(name, bytes, None, opts, ctl);
}
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
@@ -234,47 +278,145 @@ pub fn tga_alpha_channel_to_transparency(doc: &mut Document) {
/// rows at a time straight into the layer's tiles, so it opens up to 300,000 px a side without
/// a second full-size copy (#8169), when the machine has the memory for it (see
/// [`crate::memory`]).
///
/// A layered page is admitted by the adaptive budget like a PSD, with
/// [`crate::ImportOptions`]' defaults: it can be refused with [`IoError::PsdApprovalRequired`]
/// or [`IoError::PsdImportBudget`]. Callers that can ask the user or carry cancellation use
/// [`import_tiff_page_with_options`].
pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option<usize>) -> Result<ImportResult, IoError> {
import_tiff_page_with_limit(name, bytes, page, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES)
import_tiff_page_with_options(name, bytes, page, &crate::ImportOptions::default(), &photocraft_raster::Interrupt::NONE)
}
fn import_tiff_page_with_limit(name: &str, bytes: &[u8], page: Option<usize>, pixel_limit: u64) -> Result<ImportResult, IoError> {
/// [`import_tiff_page`] with the user's import settings and the job's cancellation.
///
/// A layered page takes the same caller limit and high-memory approval as a PSD
/// (`ImportOptions::psd_*`): its composite, PSD layer model and retained decoded image are
/// estimated from the page's tags and admitted *before* the composite is decoded. A cancelled
/// job stops waiting for the PSD decode gate and between bands.
pub fn import_tiff_page_with_options(
name: &str,
bytes: &[u8],
page: Option<usize>,
opts: &crate::ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<ImportResult, IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let bands = codecs::TiffBands::open(bytes, page, &codecs::Limits::banded())?;
// A page with layers or extra samples (alpha and spot channels) is decoded whole: the layers
// and channels are built from the full image. Only one copy of the layer data is kept through
// that decode.
if bands.meta.photoshop_layers.as_deref().is_some_and(|l| !l.is_empty()) || bands.extra_samples() > 0 {
drop(bands);
return import_tiff_whole(name, bytes, page, pixel_limit);
// Photoshop layer data is decoded whole, so the layers can be built from the complete
// composite; the tags are read (not decoded) first, to admit the import before that decode.
if bands.meta.photoshop_layers.as_deref().is_some_and(|l| !l.is_empty()) {
return import_tiff_layered(name, bytes, page, bands, opts, ctl);
}
tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES)
// Extra samples (alpha and spot channels) are only available from a whole-image decode.
if bands.extra_samples() > 0 {
drop(bands);
return import_tiff_with_extras(name, bytes, page, ctl);
}
tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES, ctl)
}
/// A layered TIFF, or a flat one with extra samples, decoded whole: the layers are built from the
/// composite, the channels from the extra samples.
fn import_tiff_whole(name: &str, bytes: &[u8], page: Option<usize>, pixel_limit: u64) -> Result<ImportResult, IoError> {
/// A layered TIFF page: its layer tag and resources are read into a plan, the plan's estimate is
/// admitted, and only then is the composite decoded.
///
/// The admission guard is held across the composite decode and the PSD conversion that follows,
/// so nested decodes spend the same attempt's allowance and nothing here is charged twice.
fn import_tiff_layered(
name: &str,
bytes: &[u8],
page: Option<usize>,
bands: codecs::TiffBands<'_>,
opts: &crate::ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<ImportResult, IoError> {
let plan = crate::tiff_layers::preflight(&bands)?;
// A file this machine cannot open is refused here, before any composite pixel is decoded,
// and an eligible one rechecks a fresh measurement after the gate.
let _admission = tiff_admission(plan.required, plan.tiles, opts, ctl)?;
drop(bands);
before_composite_decode();
// The orientation is applied after the layer check: rotating the composite but not the
// layers would misalign them, so a layered TIFF keeps its stored orientation.
let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() };
let (mut img, orientation) = match page {
None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)),
Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)),
};
// The plan already holds both tags, parsed: a layered page drops the decoder's copies
// instead of keeping two of each through the conversion. A flattened fallback still needs
// the resources for its channels.
if plan.is_layered() {
img.meta.photoshop_layers = None;
img.meta.photoshop_resources = None;
}
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut r = crate::tiff_layers::import_layered(name, &img, plan, ctl)?;
if orientation != 1 {
r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string());
}
Ok(r)
}
/// Admits a layered TIFF import for `required` bytes, `spillable` of them tile pixels (see
/// [`crate::memory::evaluate_psd_admission`]), and holds decode admission for it.
///
/// A nested import of a different file spends the enclosing attempt's remaining allowance: it
/// never resolves a fresh budget, resets the parent or charges the parent's image again. A
/// top-level import is refused before waiting for the gate and rechecked with a fresh
/// measurement once admitted, so a memory drop during the wait is seen before pixels are
/// decoded. Cancellation is checked before an allowance is consumed, so a cancelled nested
/// import never spends its parent's budget.
fn tiff_admission(
required: u64,
spillable: u64,
opts: &crate::ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<crate::psd_gate::AdmissionGuard, IoError> {
let caller_limit = opts.psd_max_pixel_bytes;
let admit = |snapshot: crate::memory::MemorySnapshot| {
crate::memory::evaluate_psd_admission(required, spillable, caller_limit, opts.psd_high_memory_approved, opts.psd_approved_estimate, snapshot)
};
if crate::psd_gate::is_holding_admission() {
// A nested, independent TIFF: the same-file continuation never gets here, because
// `import_tiff_layered` admits once and `import_layered` does not admit again. It spends
// the enclosing attempt's remaining allowance, and the caller's explicit bounds still
// apply before that charge (a refused nested import leaves the parent untouched).
ctl.check().map_err(|_| IoError::Cancelled)?;
crate::memory::nested_import_local_bound(required, caller_limit, opts.psd_approved_estimate)?;
let guard = crate::psd_gate::acquire_decode_admission(ctl)?;
crate::psd_gate::consume_attempt_allowance(required)?;
return Ok(guard);
}
admit(crate::memory::MemorySnapshot::current())?;
let guard = crate::psd_gate::acquire_decode_admission(ctl)?;
let outcome = admit(crate::memory::MemorySnapshot::current())?;
crate::psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(required));
Ok(guard)
}
/// A flat TIFF page with extra samples, decoded whole: the composite becomes the layer, the
/// extra samples its channels.
fn import_tiff_with_extras(name: &str, bytes: &[u8], page: Option<usize>, ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() };
let (img, orientation) = match page {
None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)),
Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)),
};
if let Some(layers) = img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()) {
let mut r = crate::tiff_layers::import_layered(name, &img, layers, pixel_limit)?;
if orientation != 1 {
r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string());
}
return Ok(r);
}
ctl.check().map_err(|_| IoError::Cancelled)?;
image_to_document(name, &img.oriented(orientation)?)
}
/// A flat TIFF page as a single-layer document, decoded a group of rows at a time into the
/// layer's tiles: only one group exists beside the document. `available`: the memory this
/// process can still use (see [`crate::memory::available`]); `budget`: the source bytes per core
/// converted at a time ([`BAND_BYTES`]).
fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: impl FnOnce() -> Option<u64>, budget: usize) -> Result<ImportResult, IoError> {
/// converted at a time ([`BAND_BYTES`]); `ctl`: the job's cancellation, checked per group.
fn tiff_to_document(
name: &str,
mut bands: codecs::TiffBands<'_>,
available: impl FnOnce() -> Option<u64>,
budget: usize,
ctl: &photocraft_raster::Interrupt,
) -> Result<ImportResult, IoError> {
let (w, h) = bands.dimensions();
let (layout, sample) = (bands.layout(), bands.sample_type());
let f = document_format(layout, sample);
@@ -284,11 +426,13 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: imp
// The layer's tiles, plus a group as decoded, turned upright, converted and read into a
// worker's scratch buffer. Linux overcommits, so the tiles below are allocated even when
// they can't be backed, and writing them would have the process killed: refuse first.
let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64);
let layer = tiles(w).saturating_mul(tiles(h)).saturating_mul(bpp);
let group = bands.group_bytes()? as u64;
let group_px = group / (layout.channels() as u64 * sample.bytes() as u64).max(1);
let needed = layer.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp));
let surface = surface_bytes(w, h, fmt);
let needed = surface.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp));
// The layer is streamed into tiles a group at a time, so while the scratch disk is
// spilling the tiles it has room for need no RAM; the groups always do.
let needed = needed.saturating_sub(crate::memory::scratch_credit(surface));
crate::memory::check_fits(w, h, needed, available())?;
}
let mut s = Surface::new(fmt);
@@ -297,6 +441,7 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: imp
IoError::Unsupported(format!("not enough memory to open this {w} × {h} px image: it needs about {gb:.1} GB ({e})"))
};
bands.decode(|x, y, group: &Image| -> Result<(), IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let (gw, gh) = group.dimensions();
let (x, y) = (x as i32, y as i32);
let rect = |rows: &std::ops::Range<usize>| Rect::new(x, y + rows.start as i32, x.saturating_add(gw as i32), y + rows.end as i32);
@@ -326,6 +471,40 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: imp
Ok(single_layer_document(name, (w, h), f, layout.has_alpha(), s, bands.icc.take(), meta, warnings))
}
/// Bytes a `w` × `h` px document surface of `fmt` allocates: whole tiles, including the padding
/// of a partly covered edge tile, as [`Surface`] holds them.
fn surface_bytes(w: u32, h: u32, fmt: PixelFormat) -> u64 {
let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64);
tiles(w).saturating_mul(tiles(h)).saturating_mul(fmt.bytes_per_pixel() as u64)
}
/// Bytes a flat page that is decoded whole needs: the decoded image and its extra-sample planes,
/// the band buffers [`image_surface`] converts through when the document format differs from the
/// page's, the layer's tiles and, per extra sample, its channel's tiles and its copied plane.
///
/// A TIFF whose Photoshop layer tag cannot be read still opens its composite flattened; this
/// bounds that whole-image decode and its conversion before anything is allocated.
///
/// Every term saturates instead of wrapping: an estimate that overflows `u64` is the
/// `u64::MAX` sentinel, which admission always refuses (see
/// [`crate::memory::MemoryBudget::decide`]) rather than admitting a wrapped-around value.
pub(crate) fn flattened_import_bytes(w: u32, h: u32, layout: ChannelLayout, sample: CSample, extras: usize, scratch: u64) -> u64 {
let f = document_format(layout, sample);
let fmt = PixelFormat::new(f.mode, f.depth, true);
let pixels = u64::from(w).saturating_mul(u64::from(h));
let in_bps = sample.bytes() as u64;
let out_bps = f.sample.bytes() as u64;
let e = extras as u64;
let decoded = pixels.saturating_mul((layout.channels() as u64).saturating_add(e.saturating_mul(2))).saturating_mul(in_bps);
// A band of rows is copied, normalized to 32-bit floats and converted; a few bands' worth
// are live at once and the scratch pool reuses the rest within its own budget.
let convert = if layout == f.layout && sample == f.sample { 0 } else { (BAND_BYTES as u64).saturating_mul(16) };
let layer = surface_bytes(w, h, fmt);
let channel = surface_bytes(w, h, PixelFormat::new(ColorMode::Grayscale, f.depth, false));
let channels = e.saturating_mul(channel.saturating_add(pixels.saturating_mul(out_bps)));
layer.saturating_add(decoded).saturating_add(convert).saturating_add(channels).saturating_add(scratch)
}
/// Whether a `w` × `h` flat TIFF is checked against free memory before it opens: only the sizes
/// the whole-image decode refused, which only the banded decode opens. Every image that opened
/// before opens as it did, also on a small machine or in a container whose page cache fills.
@@ -1395,7 +1574,7 @@ mod tiff_banded_tests {
let img = Image::from_raw(64, 64, ChannelLayout::Rgb, CSample::U8, vec![77; 64 * 64 * 3]).unwrap();
let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap();
let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap();
let r = tiff_to_document("small.tif", bands.upright(), || Some(0), BAND_BYTES).unwrap();
let r = tiff_to_document("small.tif", bands.upright(), || Some(0), BAND_BYTES, &photocraft_raster::Interrupt::NONE).unwrap();
assert_eq!((r.document.size.width, r.document.size.height), (64, 64));
}
@@ -1411,7 +1590,7 @@ mod tiff_banded_tests {
let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap();
let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap();
let row = w as usize * layout.channels() * sample.bytes();
let r = tiff_to_document("rounds.tif", bands, || None, 3 * row).unwrap();
let r = tiff_to_document("rounds.tif", bands, || None, 3 * row, &photocraft_raster::Interrupt::NONE).unwrap();
let f = document_format(layout, sample);
let want = codecs::decode(&bytes).unwrap().convert(f.layout, f.sample);
let LayerContent::Raster(s) = &r.document.layers[0].content else { panic!("not a raster layer") };
@@ -1657,4 +1836,71 @@ mod streamed_png_tests {
assert!(streams_png(&doc(8000, 6000, SampleType::U16)));
assert!(streams_png(&doc(117_504, 22_464, SampleType::U8)));
}
/// A cancelled nested TIFF import never spends its parent's remaining allowance: the
/// cancellation check comes before the charge, and the reentrant guard is taken first.
#[test]
fn a_cancelled_nested_tiff_admission_leaves_the_parent_allowance_untouched() {
let _parent = crate::psd_gate::acquire_decode_admission(&Interrupt::NONE).expect("parent admission");
crate::psd_gate::set_active_attempt_budget(1000);
let yes = || true;
let cancelled = Interrupt::cancel_only(&yes);
match tiff_admission(100, 0, &crate::ImportOptions::default(), &cancelled) {
Err(IoError::Cancelled) => {}
other => panic!("expected a cancelled nested admission, got {:?}", other.map(|_| ())),
}
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(1000), "a cancelled nested import must not consume the parent's budget");
}
/// A nested TIFF import still enforces the caller's explicit bounds, before the parent's
/// allowance is charged; one within those bounds is charged exactly once.
#[test]
fn nested_tiff_admission_enforces_the_callers_local_bounds_before_charging_the_parent() {
let ctl = Interrupt::NONE;
let _parent = crate::psd_gate::acquire_decode_admission(&ctl).expect("parent admission");
let ample = 1000u64;
crate::psd_gate::set_active_attempt_budget(ample);
let lowered = crate::ImportOptions { psd_max_pixel_bytes: 99, ..Default::default() };
match tiff_admission(100, 0, &lowered, &ctl) {
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (100, 99)),
other => panic!("expected the caller's limit to refuse, got {:?}", other.map(|_| ())),
}
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample), "a refused nested import leaves the parent's allowance untouched");
let stale = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(99), ..Default::default() };
match tiff_admission(100, 0, &stale, &ctl) {
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (100, 99)),
other => panic!("expected the approved estimate bound to refuse, got {:?}", other.map(|_| ())),
}
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample), "a refused nested import leaves the parent's allowance untouched");
let allowed = crate::ImportOptions { psd_max_pixel_bytes: 100, psd_high_memory_approved: true, psd_approved_estimate: Some(100), ..Default::default() };
let guard = tiff_admission(100, 0, &allowed, &ctl).expect("within the caller's bounds");
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample - 100), "the nested import is charged once");
drop(guard);
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample - 100), "releasing the nested guard neither refunds nor resets the parent");
}
/// A layered TIFF estimate that overflowed `u64` saturates at `u64::MAX`. Unknown native
/// memory has `u64::MAX` as its hard limit, so approval used to admit the sentinel; it is
/// refused before the gate and before any composite is decoded.
#[test]
fn a_saturated_tiff_estimate_is_refused_before_any_decode() {
if cfg!(target_pointer_width = "32") {
return;
}
crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || {
for opts in [
crate::ImportOptions::default(),
crate::ImportOptions { psd_high_memory_approved: true, ..Default::default() },
crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(u64::MAX), ..Default::default() },
] {
match tiff_admission(u64::MAX, 0, &opts, &Interrupt::NONE) {
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (u64::MAX, u64::MAX)),
other => panic!("expected a hard refusal for {opts:?}, got {:?}", other.map(|_| ())),
}
}
});
}
}
+359 -41
View File
@@ -66,10 +66,11 @@ pub mod pdf;
mod pdn;
pub use pcraft_cache::PcraftExportCache;
pub mod pixels;
mod psd_budget;
pub mod psd_budget;
mod psd_export;
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;
@@ -90,8 +91,8 @@ use photocraft_psd::{PsdError, PsdFile};
pub use adjust_map::ADJUSTMENT_KEYS;
pub use flat::{
DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, document_to_image, file_encoding, import_gif_frames, import_tiff_page, import_webp_frames,
tga_alpha_channel_to_transparency, tga_default_bits,
DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, document_to_image, file_encoding, import_gif_frames, import_tiff_page, import_tiff_page_with_options,
import_webp_frames, tga_alpha_channel_to_transparency, tga_default_bits,
};
pub use psd_export::{PsdExportOptions, document_to_psd, document_to_psd_with};
pub use psd_import::{psd_to_document, psd_to_document_with};
@@ -117,6 +118,16 @@ 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<u64> },
/// The file behind the opened handle is not the one whose memory estimate was approved: it
/// was replaced, rewritten or resized since it was checked. Nothing was decoded.
#[error("the file changed since it was checked; approve it again to open the new file")]
SourceChanged,
/// 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}")]
@@ -161,6 +172,72 @@ pub struct ImportResult {
pub preview_only: bool,
}
/// Identity of the file behind an opened handle, read from that handle.
///
/// A one-shot high-memory approval is bound to a file, not to a path: the importer opens the
/// path once, takes this identity from the handle and refuses to decode unless it is the file the
/// estimate was approved for (`import_file_for_open_verified`). The Unix form includes the
/// device, inode, modification time and change time with nanoseconds, so a same-size rewrite
/// cannot hide behind a restored modification timestamp. The identity fails closed when any of
/// these cannot be read (see [`Self::of_handle`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileIdentity {
/// File length in bytes.
pub len: u64,
/// Last modification time.
pub modified: std::time::SystemTime,
/// Device holding the file (Unix).
#[cfg(unix)]
pub dev: u64,
/// Inode of the file (Unix).
#[cfg(unix)]
pub ino: u64,
/// Inode change time, seconds since the Unix epoch (Unix).
#[cfg(unix)]
pub ctime_secs: i64,
/// Nanosecond part of [`Self::ctime_secs`] (Unix).
#[cfg(unix)]
pub ctime_nanos: i64,
}
impl FileIdentity {
/// Identity of an open file handle.
///
/// Reads the handle's own metadata, never the path, so replacing the path cannot change what
/// this describes. A metadata field that cannot be read is an error: callers must fail closed
/// rather than decode under an approval they cannot verify.
pub fn of_handle(file: &std::fs::File) -> std::io::Result<Self> {
Self::of_metadata(&file.metadata()?)
}
/// Identity of the file currently at `path`.
///
/// For discovery only (a fingerprint kept while an estimate is made). The decode path must
/// open the file and compare the identity of that handle, since the path can change between
/// this call and the open.
pub fn of_path(path: &std::path::Path) -> std::io::Result<Self> {
Self::of_metadata(&std::fs::metadata(path)?)
}
/// Builds an identity from metadata already read from an open handle or path.
///
/// Unix adds the device, inode and inode-change time so a same-size rewrite with a restored
/// modification time is still detected; other platforms compare length and modification time.
fn of_metadata(metadata: &std::fs::Metadata) -> std::io::Result<Self> {
let len = metadata.len();
let modified = metadata.modified()?;
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Ok(Self { len, modified, dev: metadata.dev(), ino: metadata.ino(), ctime_secs: metadata.ctime(), ctime_nanos: metadata.ctime_nsec() })
}
#[cfg(not(unix))]
{
Ok(Self { len, modified })
}
}
}
/// The import note for a file whose horizontal and vertical resolutions (`x`, `y`, in pixels per
/// inch) differ: a document has one resolution, so it keeps the horizontal one and saves it on
/// both axes (#1018). Differences under 0.01 ppi are below what the warning can show.
@@ -418,9 +495,16 @@ pub struct ImportOptions {
pub max_group_depth: usize,
/// 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.
/// PSD layer/mask/merged pixel allowance, including conversion workspace, and the
/// equivalent allowance for a layered TIFF's composite and retained decoded image. May
/// lower the 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,
/// Optional estimate limit for high-memory approval. When set, approval only applies if
/// the fresh preflight estimate does not exceed this amount.
pub psd_approved_estimate: Option<u64>,
}
impl Default for ImportOptions {
@@ -428,7 +512,9 @@ 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,
psd_approved_estimate: None,
}
}
}
@@ -476,29 +562,83 @@ fn import_psd(
name: &str,
ctl: &photocraft_raster::Interrupt,
damaged: &mut bool,
pixel_limit: u64,
opts: &ImportOptions,
parse: impl FnOnce(
&dyn Fn(&PsdFile) -> photocraft_psd::Result<bool>,
&dyn Fn(&PsdFile) -> bool,
) -> photocraft_psd::Result<(PsdFile, Option<photocraft_psd::Result<Vec<u8>>>)>,
) -> Result<ImportResult, IoError> {
// A merged image the import reads is decoded with the parse: a ZIP one is inflated once.
// A failed read of the file (one parsed from its source) is a read error, as reading the
// whole file first would report it.
let preflight_error = std::cell::RefCell::new(None);
let admission_guard: std::cell::RefCell<Option<psd_gate::AdmissionGuard>> = std::cell::RefCell::new(None);
let parsed = parse(
&|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));
if let Err(error) = checked {
*preflight_error.borrow_mut() = Some(error);
return Err(PsdError::LimitExceeded("PSD import preflight refused the file"));
let preflight_check: Result<bool, IoError> = (|| {
depth?;
let est = psd_budget::estimate(file)?;
if psd_gate::is_holding_admission() {
// Nested import: it spends the enclosing attempt's remaining allowance and
// never resets or re-charges the parent. Cancellation is checked before the
// charge, and admission is reentrant here, so a cancelled or refused nested
// import leaves the parent's allowance untouched. The caller's explicit
// bounds (a lower allowance and a one-shot estimate) still apply before the
// parent is charged.
ctl.check().map_err(|_| IoError::Cancelled)?;
memory::nested_import_local_bound(est.total_bytes, opts.psd_max_pixel_bytes, opts.psd_approved_estimate)?;
let guard = psd_gate::acquire_decode_admission(ctl)?;
psd_gate::consume_attempt_allowance(est.total_bytes)?;
*admission_guard.borrow_mut() = Some(guard);
return Ok(psd_import::merged_needed(file));
}
// 1. Initial admission check BEFORE waiting on or acquiring the gate.
// Invalid or unapproved files fail fast without blocking other decodes or acquiring gate.
memory::evaluate_psd_admission(
est.total_bytes,
est.tile_bytes,
opts.psd_max_pixel_bytes,
opts.psd_high_memory_approved,
opts.psd_approved_estimate,
memory::MemorySnapshot::current(),
)?;
// 2. Cancellation-aware gate acquisition BEFORE any merged or layer pixel decoding/inflation.
let guard = psd_gate::acquire_decode_admission(ctl)?;
// 3. Re-evaluate adaptive budget immediately after gate acquisition.
// If available memory dropped while waiting for gate, this returns Err,
// guard is dropped (releasing gate immediately), and error is returned before prompting.
let outcome = memory::evaluate_psd_admission(
est.total_bytes,
est.tile_bytes,
opts.psd_max_pixel_bytes,
opts.psd_high_memory_approved,
opts.psd_approved_estimate,
memory::MemorySnapshot::current(),
)?;
// Initialize enclosing attempt allowance for any nested decodes.
psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes));
// Retain guard across parse and conversion
*admission_guard.borrow_mut() = Some(guard);
Ok(psd_import::merged_needed(file))
})();
match preflight_check {
Ok(want_merged) => Ok(want_merged),
Err(error) => {
*preflight_error.borrow_mut() = Some(error);
Err(PsdError::LimitExceeded("PSD import preflight refused the file"))
}
}
Ok(psd_import::merged_needed(file))
},
&psd_import::can_recover_layers,
);
if let Some(error) = preflight_error.into_inner() {
return Err(error);
}
@@ -509,6 +649,7 @@ fn import_psd(
})?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(0.05);
// 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)?;
@@ -535,54 +676,126 @@ pub fn import_file_for_open_with(
path: &std::path::Path,
opts: &ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<(ImportResult, bool), IoError> {
let mut identity = None;
import_file_for_open_verified(name, path, None, opts, ctl, &mut identity)
}
/// [`import_file_for_open_with`] bound to the identity of the file handle it decodes.
///
/// The path is opened exactly once. `identity_out` is set from that handle before any pixel is
/// read; a PSD/PSB is then streamed from the same handle (not read whole), anything else is read
/// from it within `photocraft_format::MAX_OPEN_BYTES`. When `expected` is given, the import
/// refuses with [`IoError::SourceChanged`] unless the opened file is that one. When the parse
/// stops for a high-memory approval, the identity is read again from a duplicate of the same
/// handle: a file rewritten in place while its estimate was checked is refused, so the approval
/// always refers to the bytes that will be decoded.
///
/// A missing or unreadable metadata field fails the open instead of decoding under an identity
/// that cannot be verified.
#[cfg(any(unix, windows))]
pub fn import_file_for_open_verified(
name: &str,
path: &std::path::Path,
expected: Option<&FileIdentity>,
opts: &ImportOptions,
ctl: &photocraft_raster::Interrupt,
identity_out: &mut Option<FileIdentity>,
) -> Result<(ImportResult, bool), IoError> {
let read_failed = |e: std::io::Error| IoError::Read(format!("{}: {e}", path.display()));
ctl.check().map_err(|_| IoError::Cancelled)?;
let source = photocraft_psd::FileSource::open(path).map_err(read_failed)?;
let metadata = source.file().metadata().map_err(read_failed)?;
if !metadata.is_file() {
return Err(IoError::Read(format!("{}: not a regular file", path.display())));
}
let identity = FileIdentity::of_metadata(&metadata).map_err(read_failed)?;
*identity_out = Some(identity.clone());
if expected.is_some_and(|expected| expected != &identity) {
return Err(IoError::SourceChanged);
}
// A duplicate of the same open file (not a fresh path lookup): the approval pause re-reads
// the identity from it after parsing, and never from a path that may point elsewhere now.
let watch = source.file().try_clone().map_err(read_failed)?;
let mut magic = [0u8; 4];
let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic);
if !psd {
drop(source);
let result = if psd {
import_source_with_options(name, photocraft_psd::Source::new(source), ctl, opts)
} else {
// Read from the handle that was just identified, not by opening the path again.
let mut file = source.file();
// Windows seek_read advances this handle during the format probe.
// Rewind the same verified handle before reading a non-PSD file.
std::io::Seek::rewind(&mut file).map_err(read_failed)?;
// A flat scanline EXR is decoded block by block straight into tiles; other EXR
// layouts, and EXR headers the band decoder refuses, are read whole below.
let mut streamed = None;
if !has_extension(name, photocraft_format::EXTENSION) && photocraft_codecs::detect(&magic) == Some(photocraft_codecs::Format::OpenExr) {
let before = photocraft_raster::spill::read_error_generation();
let mut file = std::fs::File::open(path).map_err(read_failed)?;
let original = file.metadata().map_err(read_failed)?;
if let Some(mut result) = exr_native::import(&mut file, ctl)? {
let current = std::fs::metadata(path).map_err(read_failed)?;
if current.len() != original.len() || current.modified().ok() != original.modified().ok() {
// A rewrite in place while the blocks were read must not become the document.
if FileIdentity::of_handle(&watch).map_err(read_failed)? != identity {
return Err(IoError::Read(format!("{}: the file changed while it was being opened; open it again", path.display())));
}
photocraft_raster::spill::check_since(before).map_err(IoError::Read)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
result.document.name = name.to_string();
return Ok((result, false));
streamed = Some(result);
} else {
std::io::Seek::rewind(&mut file).map_err(read_failed)?;
}
}
let bytes = photocraft_format::read_file(path).map_err(read_failed)?;
return import_for_open_with(name, &bytes, opts, ctl);
match streamed {
Some(result) => Ok((result, false)),
None => {
let bytes = photocraft_format::read::read_all(&mut file, photocraft_psd::ReadAt::len(&source)).map_err(read_failed)?;
import_for_open_with(name, &bytes, opts, ctl)
}
}
};
// An approval pause must describe a file that still has the identity it was estimated with;
// an approved resume must have decoded that file, not a rewrite that raced the decode.
if expected.is_some() || matches!(&result, Err(IoError::PsdApprovalRequired { .. })) {
let after = FileIdentity::of_handle(&watch).map_err(read_failed)?;
if after != identity {
return Err(IoError::SourceChanged);
}
*identity_out = Some(after);
}
import_source_with_limit(name, photocraft_psd::Source::new(source), ctl, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES))
result
}
/// [`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_options(name, source, ctl, &ImportOptions::default())
}
fn import_source_with_limit(
/// [`import_source_for_open_with`] with custom import options.
pub fn import_source_with_options(
name: &str,
source: photocraft_psd::Source,
ctl: &photocraft_raster::Interrupt,
opts: &ImportOptions,
) -> Result<(ImportResult, bool), IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut damaged = false;
let r = import_psd(name, ctl, &mut damaged, opts, |want, recover| PsdFile::from_source_and_merged_preflight(source, want, recover))?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(1.0);
Ok((r, damaged))
}
/// [`import_source_with_options`] with an explicit PSD pixel limit, for tests that exercise
/// admission without the default allowance.
#[cfg(test)]
pub(crate) fn import_source_with_limit(
name: &str,
source: photocraft_psd::Source,
ctl: &photocraft_raster::Interrupt,
pixel_limit: u64,
) -> 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))?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(1.0);
Ok((r, damaged))
let opts = ImportOptions { psd_max_pixel_bytes: pixel_limit, ..Default::default() };
import_source_with_options(name, source, ctl, &opts)
}
/// [`import_file_for_open_with`] without the damage flag.
@@ -602,9 +815,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| {
PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)
});
return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover));
}
if affinity::is_affinity(bytes) || affinity::has_extension(name) {
return affinity::import(name, bytes);
@@ -637,11 +848,9 @@ 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| {
PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)
});
return import_psd(name, ctl, damaged, opts, |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_options(name, bytes, opts, ctl)
}
/// Extension names can be wrong (for example, an image downloaded as WebP and renamed `.svg`).
@@ -998,6 +1207,53 @@ mod tests {
assert!(!result.source_read_only);
}
/// A nested PSD import still enforces the caller's explicit bounds before it spends the
/// parent's allowance, and one within those bounds is charged exactly once.
#[cfg(not(any(target_arch = "wasm32", target_pointer_width = "32")))]
#[test]
fn nested_psd_import_enforces_the_callers_local_bounds_before_charging_the_parent() {
let gb = 1u64 << 30;
let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();
let ctl = photocraft_raster::Interrupt::NONE;
let ample = 16 * gb;
let _parent = super::psd_gate::acquire_decode_admission(&ctl).expect("parent admission");
// The tiny fixture plus a thread-local charge lands in the approval band; nothing near a
// gigabyte is allocated.
super::psd_budget::with_test_estimate_charge(5 * gb, || {
// What the real nested import is charged, learned from one admitted run.
super::psd_gate::set_active_attempt_budget(ample);
super::import_with_options_and_interrupt("nested.psd", &bytes, &ImportOptions::default(), &ctl).expect("an admitted nested import");
let required = ample - super::psd_gate::active_attempt_remaining().expect("the parent attempt keeps an allowance");
assert!(required > 5 * gb, "the test charge is part of the estimate: {required}");
let cases = [
(ImportOptions { psd_max_pixel_bytes: required - 1, ..Default::default() }, "the caller's lower allowance"),
(
ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required - 1), ..Default::default() },
"the one-shot approved estimate",
),
];
for (opts, what) in cases {
super::psd_gate::set_active_attempt_budget(ample);
match super::import_with_options_and_interrupt("nested.psd", &bytes, &opts, &ctl) {
Err(super::IoError::PsdImportBudget { required: r, limit }) => {
assert_eq!((r, limit), (required, required - 1), "{what} must refuse with its exact fields")
}
other => panic!("expected {what} to refuse, got {:?}", other.map(|_| ())),
}
assert_eq!(super::psd_gate::active_attempt_remaining(), Some(ample), "{what} must not spend the parent's allowance");
}
super::psd_gate::set_active_attempt_budget(ample);
let bounded =
ImportOptions { psd_max_pixel_bytes: required, psd_high_memory_approved: true, psd_approved_estimate: Some(required), ..Default::default() };
let opened = super::import_with_options_and_interrupt("nested.psd", &bytes, &bounded, &ctl).expect("within the caller's bounds");
assert!(opened.document.size.area() > 0, "the bounded nested import really opened a document");
assert_eq!(super::psd_gate::active_attempt_remaining(), Some(ample - required), "the nested import is charged once");
});
}
#[test]
fn svg_extension_does_not_override_another_format_signature() {
let webp_header = b"RIFF\x04\0\0\0WEBP";
@@ -1023,6 +1279,68 @@ mod tests {
assert!(!super::is_psd(b"\0\xffKA"));
}
#[cfg(any(unix, windows))]
#[test]
fn verified_path_import_reads_a_flat_file_from_its_start() {
let dir = std::env::temp_dir().join(format!("photocraft-verified-png-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("verified.png");
let image = photocraft_codecs::Image::from_u8(2, 3, photocraft_codecs::ChannelLayout::Rgb, vec![64; 18]).unwrap();
let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
std::fs::write(&path, bytes).unwrap();
let mut identity = None;
let (opened, damaged) =
super::import_file_for_open_verified("verified.png", &path, None, &ImportOptions::default(), &photocraft_raster::Interrupt::NONE, &mut identity)
.unwrap();
assert_eq!((opened.document.size.width, opened.document.size.height), (2, 3));
assert!(!damaged);
assert_eq!(identity, Some(super::FileIdentity::of_path(&path).unwrap()));
std::fs::remove_dir_all(dir).unwrap();
}
/// The identity a verified open returns is the opened handle's, and a different inode with
/// identical content is refused with the dedicated reason before any pixel is decoded.
#[cfg(unix)]
#[test]
fn verified_import_binds_the_decoded_handle_identity() {
let dir = std::env::temp_dir().join(format!("photocraft-io-verified-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("source.psd");
let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();
std::fs::write(&path, &bytes).unwrap();
let expected = super::FileIdentity::of_path(&path).unwrap();
let mut opened = None;
let (result, _) = super::import_file_for_open_verified(
"source.psd",
&path,
Some(&expected),
&ImportOptions::default(),
&photocraft_raster::Interrupt::NONE,
&mut opened,
)
.unwrap();
assert!(!result.document.layers.is_empty());
assert_eq!(opened.as_ref(), Some(&expected), "the identity comes from the decoded handle");
// Replacement with identical bytes but a different inode: not the approved file.
let replacement = dir.join("replacement.psd");
std::fs::write(&replacement, &bytes).unwrap();
std::fs::rename(&replacement, &path).unwrap();
let mut opened = None;
let err = super::import_file_for_open_verified(
"source.psd",
&path,
Some(&expected),
&ImportOptions::default(),
&photocraft_raster::Interrupt::NONE,
&mut opened,
)
.expect_err("the path now names another file");
assert!(matches!(&err, super::IoError::SourceChanged), "got {err:?}");
assert!(opened.is_some(), "the refused handle's identity is still reported");
let _ = std::fs::remove_dir_all(&dir);
}
/// A common mislabeled download: PNG/JPEG bytes named `.psd` open from the signature,
/// as on main and in Photoshop.
#[test]
+1022 -87
View File
File diff suppressed because it is too large. Load diff
+119 -13
View File
@@ -16,10 +16,102 @@ 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,
/// The part of `retained_bytes` that is tile pixels (layer, mask, channel, fallback and
/// pattern surfaces). Tiles can be spilled to the scratch disk while it is on, so admission
/// does not bound them by physical RAM; the merged planes, pattern decodes and the workspace
/// are ordinary memory.
pub tile_bytes: u64,
}
#[derive(Default)]
struct ImportBudget {
retained: u64,
workspace: u64,
tiles: u64,
}
#[cfg(any(test, feature = "testgen"))]
thread_local! {
/// Extra bytes added to every estimate on this thread by [`with_test_estimate_charge`].
static TEST_ESTIMATE_CHARGE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// Extra tile-pixel bytes added by [`with_test_tile_charge`].
static TEST_TILE_CHARGE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Adds `bytes` to every PSD memory estimate made on this thread while `f` runs.
///
/// A test seam: an admission-threshold test can use a tiny fixture, so nothing near a gigabyte
/// is ever allocated, while still exercising the real import path with its approval flags and
/// gate ordering. Scoped to the thread and restored on return or panic.
///
/// The charge lives on the calling thread. A real import that runs on another thread (or a
/// worker the engine starts for it) does not see it unless the caller propagates an explicitly
/// captured scope: [`crate::memory::TestMemoryScope`] captures this charge together with the
/// fixed mock snapshot, so an engine worker that enters that scope makes the same estimates as
/// the test thread. This is the seam engine and UI dev-dependency tests use through the
/// `testgen` feature; it is never process-global.
#[cfg(any(test, feature = "testgen"))]
pub fn with_test_estimate_charge<R>(bytes: u64, f: impl FnOnce() -> R) -> R {
struct Reset(u64);
impl Drop for Reset {
fn drop(&mut self) {
TEST_ESTIMATE_CHARGE.with(|c| c.set(self.0));
}
}
let prev = TEST_ESTIMATE_CHARGE.with(|c| c.replace(bytes));
let _reset = Reset(prev);
f()
}
/// [`with_test_estimate_charge`] for tile pixels: `bytes` are added to every estimate made on
/// this thread while `f` runs, as spillable tile bytes ([`PsdMemoryEstimate::tile_bytes`]), so a
/// scratch-aware admission test needs no huge fixture. Captured by
/// [`crate::memory::TestMemoryScope`] like the plain charge.
#[cfg(any(test, feature = "testgen"))]
pub fn with_test_tile_charge<R>(bytes: u64, f: impl FnOnce() -> R) -> R {
struct Reset(u64);
impl Drop for Reset {
fn drop(&mut self) {
TEST_TILE_CHARGE.with(|c| c.set(self.0));
}
}
let prev = TEST_TILE_CHARGE.with(|c| c.replace(bytes));
let _reset = Reset(prev);
f()
}
/// The calling thread's current (plain, tile) estimate charges, for an explicit scope to capture.
#[cfg(any(test, feature = "testgen"))]
pub(crate) fn test_estimate_charge() -> (u64, u64) {
(TEST_ESTIMATE_CHARGE.with(|c| c.get()), TEST_TILE_CHARGE.with(|c| c.get()))
}
/// Enters captured estimate charges (an explicit [`crate::memory::TestMemoryScope`] worker) and
/// returns the charges they replaced, to restore after the scope ends.
#[cfg(any(test, feature = "testgen"))]
pub(crate) fn enter_test_estimate_charge(bytes: u64, tiles: u64) -> (u64, u64) {
(TEST_ESTIMATE_CHARGE.with(|c| c.replace(bytes)), TEST_TILE_CHARGE.with(|c| c.replace(tiles)))
}
/// The test seam's extra (plain, tile) charges; zero in every other build.
fn test_estimate_charge_value() -> (u64, u64) {
#[cfg(any(test, feature = "testgen"))]
{
test_estimate_charge()
}
#[cfg(not(any(test, feature = "testgen")))]
{
(0, 0)
}
}
fn overflow() -> IoError {
@@ -49,14 +141,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(());
@@ -66,15 +150,24 @@ impl ImportBudget {
// origin occupies four tiles. Widen first, including the exclusive right/bottom edge.
let nx = (i64::from(rect.right) - 1).div_euclid(tile) - i64::from(rect.left).div_euclid(tile) + 1;
let ny = (i64::from(rect.bottom) - 1).div_euclid(tile) - i64::from(rect.top).div_euclid(tile) + 1;
self.retain(mul(mul(mul(nx as u64, ny as u64)?, (TILE_SIZE as u64).pow(2))?, mul(channels, sample)?)?)
let bytes = mul(mul(mul(nx as u64, ny as u64)?, (TILE_SIZE as u64).pow(2))?, mul(channels, sample)?)?;
self.tile(bytes)
}
/// Retained tile pixels: spillable to the scratch disk.
fn tile(&mut self, bytes: u64) -> Result<(), IoError> {
self.retain(bytes)?;
self.tiles = self.tiles.checked_add(bytes).ok_or_else(overflow)?;
Ok(())
}
}
/// 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<PsdMemoryEstimate, IoError> {
let mut budget = ImportBudget::default();
let h = &file.header;
h.validate()?;
@@ -145,7 +238,20 @@ 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 (charge, tile_charge) = test_estimate_charge_value();
budget.retain(charge)?;
budget.tile(tile_charge)?;
let total_bytes = budget.required()?;
Ok(PsdMemoryEstimate { retained_bytes: budget.retained, workspace_bytes: budget.workspace, total_bytes, tile_bytes: budget.tiles })
}
/// Checks that `file`'s estimate does not exceed `limit`.
pub fn check(file: &PsdFile, limit: u64) -> Result<PsdMemoryEstimate, IoError> {
let est = estimate(file)?;
if est.total_bytes > limit {
return Err(IoError::PsdImportBudget { required: est.total_bytes, limit });
}
Ok(est)
}
#[cfg(test)]
+394 -8
View File
@@ -8,8 +8,7 @@ fn retained_storage_is_summed_but_workspace_is_reused() {
budget.retain(20).unwrap();
budget.scratch(30);
budget.scratch(10);
assert!(budget.check(90).is_ok());
assert!(matches!(budget.check(89), Err(IoError::PsdImportBudget { required: 90, limit: 89 })));
assert_eq!(budget.required().unwrap(), 90);
budget.retain(u64::MAX).unwrap_err();
budget.workspace = u64::MAX;
assert!(budget.required().is_err());
@@ -55,9 +54,16 @@ fn large_off_canvas_layer_is_rejected_without_decoding_its_tiny_data() {
// section. No enormous decoded plane is ever constructed by this test.
let mut bytes = file.to_bytes().unwrap();
bytes.truncate(bytes.len() - file.image_data.data.len() - 2);
assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdImportBudget { .. })));
let source = photocraft_psd::Source::new(bytes);
assert!(matches!(crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), Err(IoError::PsdImportBudget { .. })));
crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || {
// Unknown memory keeps a conservative automatic allowance, so this file is refused
// pending approval (or by the hard platform limit on 32-bit) before any pixel decode.
assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdApprovalRequired { .. } | IoError::PsdImportBudget { .. })));
let source = photocraft_psd::Source::new(bytes);
assert!(matches!(
crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE),
Err(IoError::PsdApprovalRequired { .. } | IoError::PsdImportBudget { .. })
));
});
}
#[test]
@@ -119,9 +125,12 @@ fn accepted_off_canvas_pixels_and_depths_are_preserved() {
fn legacy_conversion_reports_a_rejected_import_instead_of_decoding_it() {
let mut file = testgen::small(Version::Psd, Compression::Zip);
file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 20000, 20000);
let (doc, warnings) = crate::psd_to_document(&file);
assert!(doc.layers.is_empty());
assert!(warnings.iter().any(|warning| warning.contains("pixel memory")));
// Use fallback snapshot to ensure test does not depend on host available RAM
crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || {
let (doc, warnings) = crate::psd_to_document(&file);
assert!(doc.layers.is_empty());
assert!(warnings.iter().any(|warning| warning.contains("pixel memory")));
});
}
fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> photocraft_psd::TaggedBlock {
@@ -192,3 +201,380 @@ 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() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return; // the 6 GiB hard limit is above the 32-bit aggregate cap
}
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() {
if cfg!(target_arch = "wasm32") {
return; // the web policy ignores a host snapshot; it has its own tests
}
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 { .. })));
});
}
#[test]
fn preflight_rejection_and_approval_files_release_gate() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let mut file = testgen::small(Version::Psd, Compression::Zip);
file.header.width = 1;
file.header.height = 1;
file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 30_000, 30_000);
let bytes = file.to_bytes().unwrap();
let gb = 1u64 << 30;
// Set RAM such that this large layer exceeds hard limit
let snap = crate::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(snap, || {
assert!(!crate::psd_gate::is_holding_admission());
let res = crate::import_with_options("huge.psd", &bytes, &crate::ImportOptions::default());
assert!(matches!(res, Err(IoError::PsdImportBudget { .. })));
// Gate must not be held after rejection
assert!(!crate::psd_gate::is_holding_admission());
});
// Set RAM such that file falls in confirmation range
let est = estimate(&file);
let snap_mid = crate::memory::MemorySnapshot { available_ram: Some(est * 2), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(snap_mid, || {
assert!(!crate::psd_gate::is_holding_admission());
let res = crate::import_with_options("mid.psd", &bytes, &crate::ImportOptions::default());
assert!(matches!(res, Err(IoError::PsdApprovalRequired { .. })));
// Gate must not be held when requiring approval
assert!(!crate::psd_gate::is_holding_admission());
});
}
#[test]
fn retry_estimate_cap_rejects_altered_or_enlarged_file() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let snap = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None };
// S = 6 GiB, H = 9 GiB
// 1. Within approved_estimate: passes
let res = crate::memory::evaluate_psd_admission(7 * gb, 0, 0, true, Some(7 * gb), snap);
assert!(res.is_ok());
// 2. Fresh requirement exceeds approved_estimate: requires fresh approval
let res = crate::memory::evaluate_psd_admission(8 * gb, 0, 0, true, Some(7 * gb), snap);
assert!(matches!(res, Err(IoError::PsdApprovalRequired { required, .. }) if required == 8 * gb));
// 3. Exceeds hard limit: refused completely regardless of approval
let res = crate::memory::evaluate_psd_admission(10 * gb, 0, 0, true, Some(10 * gb), snap);
assert!(matches!(res, Err(IoError::PsdImportBudget { required, limit }) if required == 10 * gb && limit == 9 * gb));
}
#[test]
fn caller_zero_and_lower_caps_cannot_bypass_hard_boundary() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let snap = crate::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None };
// S = 4 GiB, H = 6 GiB
// 0 uses adaptive budget
let b_zero = crate::memory::resolve_budget(snap, Some(0));
assert_eq!(b_zero.hard_limit, 6 * gb);
assert_eq!(b_zero.soft_limit, 4 * gb);
// Lower cap lowers both hard and soft
let b_lower = crate::memory::resolve_budget(snap, Some(3 * gb));
assert_eq!(b_lower.hard_limit, 3 * gb);
assert_eq!(b_lower.soft_limit, 3 * gb);
// Higher cap cannot raise above hard limit
let b_higher = crate::memory::resolve_budget(snap, Some(20 * gb));
assert_eq!(b_higher.hard_limit, 6 * gb);
assert_eq!(b_higher.soft_limit, 4 * gb);
}
#[test]
fn test_memory_scope_propagates_to_worker_thread() {
let gb = 1u64 << 30;
let mock = crate::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(mock, || {
let scope = crate::memory::TestMemoryScope::capture();
let handle = std::thread::spawn(move || {
scope.run(|| {
assert_eq!(crate::memory::MemorySnapshot::current().available_ram, Some(4 * gb));
});
});
handle.join().unwrap();
});
}
#[test]
fn test_memory_scope_propagates_the_estimate_charge_to_a_worker() {
let gb = 1u64 << 30;
let file = std::sync::Arc::new(testgen::small(Version::Psd, Compression::Zip));
let bare = estimate(&file);
with_test_estimate_charge(2 * gb, || {
assert_eq!(estimate(&file), bare + 2 * gb, "the charge is part of the estimate on this thread");
let scope = crate::memory::TestMemoryScope::capture();
let worker_file = std::sync::Arc::clone(&file);
std::thread::spawn(move || {
scope.run(|| assert_eq!(estimate(&worker_file), bare + 2 * gb, "a captured scope carries the charge to its worker"));
})
.join()
.unwrap();
});
assert_eq!(estimate(&file), bare, "the charge is restored on this thread");
let detached = std::sync::Arc::clone(&file);
assert_eq!(std::thread::spawn(move || estimate(&detached)).join().unwrap(), bare, "a worker outside the scope never sees it");
}
#[test]
fn nested_imports_consume_from_shared_allowance_and_do_not_reset_parent() {
let gb = 1u64 << 30;
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = crate::psd_gate::acquire_decode_admission(&ctl).unwrap();
// Simulate top-level attempt authorized total of 5 GB with 2 GB remaining allowance
crate::psd_gate::set_active_attempt_budget(2 * gb);
// First nested consume fits within 2 GB
assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok());
// Second nested consume exceeds remaining 1 GB
let err = crate::psd_gate::consume_attempt_allowance(2 * gb).unwrap_err();
assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == 2 * gb && limit == gb));
// Allowance is still 1 GB (failed attempt does not reset or corrupt parent)
assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok());
assert!(crate::psd_gate::consume_attempt_allowance(1).is_err());
}
#[test]
fn nested_tiff_layer_import_consumes_composite_and_estimate_without_resetting_parent() {
let gb = 1u64 << 30;
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = crate::psd_gate::acquire_decode_admission(&ctl).unwrap();
crate::psd_gate::set_active_attempt_budget(3 * gb);
assert!(crate::psd_gate::is_holding_admission());
assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok());
assert!(crate::psd_gate::consume_attempt_allowance(2 * gb).is_ok());
assert!(crate::psd_gate::consume_attempt_allowance(1).is_err());
}
/// A real import carries the approval flag and its estimate bound into admission: the fixture is
/// tiny, and a thread-local test charge puts it in the confirmation band without allocating
/// gigabytes.
#[test]
fn real_import_propagates_high_memory_approval_and_its_estimate_bound() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let file = testgen::small(Version::Psd, Compression::Zip);
let bytes = file.to_bytes().unwrap();
let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(snapshot, || {
let automatic_layers =
crate::import_with_options("approval.psd", &bytes, &crate::ImportOptions::default()).expect("small file is automatic").document.layers.len();
with_test_estimate_charge(7 * gb, || {
let required = match crate::import_with_options("approval.psd", &bytes, &crate::ImportOptions::default()) {
Err(IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => {
assert_eq!((soft_limit, hard_limit), (6 * gb, 9 * gb));
assert_eq!(available_ram, Some(12 * gb));
required
}
other => panic!("expected an approval request, got {other:?}"),
};
assert!((7 * gb..=9 * gb).contains(&required), "the charge lands in the approval band: {required}");
let approved = crate::ImportOptions { psd_high_memory_approved: true, ..Default::default() };
assert_eq!(
crate::import_with_options("approval.psd", &bytes, &approved).expect("approved").document.layers.len(),
automatic_layers,
"an approved import decodes the same document as an automatic one"
);
let bounded = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required), ..Default::default() };
assert!(crate::import_with_options("approval.psd", &bytes, &bounded).is_ok());
let stale = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required - 1), ..Default::default() };
assert!(matches!(crate::import_with_options("approval.psd", &bytes, &stale), Err(IoError::PsdApprovalRequired { .. })));
let lowered = crate::ImportOptions { psd_high_memory_approved: true, psd_max_pixel_bytes: required - 1, ..Default::default() };
assert!(matches!(
crate::import_with_options("approval.psd", &bytes, &lowered),
Err(IoError::PsdImportBudget { required: r, limit: l }) if r == required && l == required - 1
));
});
});
}
/// Available memory can drop while an import waits for the decode gate. The post-gate recheck
/// must then refuse before anything is decoded. A per-attempt provider, shared with this test
/// only, changes the measurement while the worker is blocked; nothing near a gigabyte is
/// allocated, and the real document is never opened.
#[test]
fn memory_drop_while_waiting_for_the_gate_refuses_before_decoding() {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let file = testgen::small(Version::Psd, Compression::Zip);
let bytes = file.to_bytes().unwrap();
// Hold the gate so the worker stops after its first admission check.
let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE).expect("active decode");
let available = Arc::new(AtomicU64::new(32 * gb));
let prechecked = Arc::new(AtomicBool::new(false));
let (tx, rx) = std::sync::mpsc::channel();
let handle = {
let available = Arc::clone(&available);
let prechecked = Arc::clone(&prechecked);
std::thread::spawn(move || {
let provider = std::rc::Rc::new(move || {
prechecked.store(true, Ordering::SeqCst);
crate::memory::MemorySnapshot { available_ram: Some(available.load(Ordering::SeqCst)), swap_free: None, commit_headroom: None }
});
let result =
crate::memory::with_mock_memory_provider(provider, || crate::import_with_options("drop.psd", &bytes, &crate::ImportOptions::default()));
tx.send(result.map(|r| r.document.layers.len())).ok();
})
};
// The provider's first call is the pre-gate admission check.
let deadline = Instant::now() + Duration::from_secs(10);
while !prechecked.load(Ordering::SeqCst) {
assert!(Instant::now() < deadline, "the import never reached its admission check");
std::thread::yield_now();
}
// The precheck admitted it; now the machine has nothing left. Release the gate afterwards.
available.store(0, Ordering::SeqCst);
drop(_guard);
let result = rx.recv_timeout(Duration::from_secs(10)).expect("the post-gate recheck must refuse instead of decoding");
match result {
Err(IoError::PsdImportBudget { required, limit: 0 }) => assert!(required > 0),
other => panic!("expected the post-gate recheck to refuse with a zero budget, got {other:?}"),
}
handle.join().expect("worker thread");
}
/// A real import counts its tile pixels as spillable: with a spilling scratch disk they are
/// admitted against RAM plus its room, while non-spillable working memory still needs RAM, and
/// with spilling off the RAM-only policy applies unchanged. Nothing near a gigabyte is allocated.
#[test]
fn real_import_admits_tile_pixels_against_scratch_room_only_while_spilling() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let file = testgen::small(Version::Psd, Compression::Zip);
let bytes = file.to_bytes().unwrap();
let est = estimate(&file);
let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None };
let import = |opts: &crate::ImportOptions| crate::import_with_options("scratch.psd", &bytes, opts);
crate::memory::with_mock_memory(snapshot, || {
assert!(super::estimate(&file).unwrap().tile_bytes > 0, "layer surfaces are tile pixels");
with_test_tile_charge(18 * gb, || {
let charged = super::estimate(&file).unwrap();
assert_eq!(charged.total_bytes, est + 18 * gb);
// Spilling off (or paused): 18 GiB of tiles is over H = 9 GiB.
crate::memory::with_mock_scratch(None, || {
assert!(matches!(import(&Default::default()), Err(IoError::PsdImportBudget { limit, .. }) if limit == 9 * gb));
});
// Spilling with room for every tile: automatic, no approval.
crate::memory::with_mock_scratch(Some(40 * gb), || {
assert!(import(&Default::default()).is_ok());
});
// Room for only part of the tiles: the rest must fit RAM.
crate::memory::with_mock_scratch(Some(4 * gb), || {
assert!(matches!(import(&Default::default()), Err(IoError::PsdImportBudget { .. })));
});
});
// Non-spillable memory gets no scratch credit: 7 GiB still asks for approval.
with_test_estimate_charge(7 * gb, || {
crate::memory::with_mock_scratch(Some(40 * gb), || match import(&Default::default()) {
Err(IoError::PsdApprovalRequired { required, soft_limit, .. }) => {
let tiles = super::estimate(&file).unwrap().tile_bytes;
assert_eq!(soft_limit, 6 * gb + tiles);
assert!(required > soft_limit);
}
other => panic!("expected an approval request, got {other:?}"),
});
});
});
}
+265
View File
@@ -0,0 +1,265 @@
//! 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.
//!
//! Nested callers check cancellation and take the reentrant guard before calling
//! `consume_attempt_allowance`, so a cancelled or refused nested import never spends its
//! parent's remaining allowance; a failed charge deducts nothing.
use std::cell::Cell;
use std::marker::PhantomData;
use std::sync::{Condvar, Mutex, OnceLock};
use std::thread::ThreadId;
#[cfg(any(test, not(target_arch = "wasm32")))]
use std::time::Duration;
use crate::IoError;
struct GateState {
active: bool,
owner: Option<ThreadId>,
}
static GATE: OnceLock<(Mutex<GateState>, Condvar)> = OnceLock::new();
/// Returns the process-wide decode gate, creating its mutex and condition variable on first use.
fn get_gate() -> &'static (Mutex<GateState>, Condvar) {
GATE.get_or_init(|| (Mutex::new(GateState { active: false, owner: None }), Condvar::new()))
}
thread_local! {
static NESTED_DEPTH: Cell<usize> = const { Cell::new(0) };
static ATTEMPT_ALLOWANCE: Cell<Option<u64>> = const { Cell::new(None) };
}
/// RAII guard releasing decode admission when dropped.
/// Non-Send and non-Sync to prevent cross-thread leakage or premature release.
pub(crate) struct AdmissionGuard {
_marker: PhantomData<*const ()>,
}
impl Drop for AdmissionGuard {
fn drop(&mut self) {
let depth = NESTED_DEPTH.with(|d| {
let val = d.get().saturating_sub(1);
d.set(val);
val
});
if depth == 0 {
ATTEMPT_ALLOWANCE.with(|a| a.set(None));
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();
}
}
}
/// Returns whether the current thread currently holds decode admission.
pub(crate) fn is_holding_admission() -> bool {
NESTED_DEPTH.with(|d| d.get() > 0)
}
/// Sets the remaining memory allowance for the active import attempt on the current thread.
pub(crate) fn set_active_attempt_budget(allowance: u64) {
ATTEMPT_ALLOWANCE.with(|a| a.set(Some(allowance)));
}
/// Consumes `bytes` from the enclosing attempt's remaining allowance, or returns
/// [`IoError::PsdImportBudget`] if the required amount exceeds what remains.
///
/// `u64::MAX` is a format estimate's saturated overflow sentinel, not a requirement: it is
/// refused even when the remaining allowance is also `u64::MAX` (the native unknown-memory
/// attempt cap), and a refusal never spends the parent's allowance.
pub(crate) fn consume_attempt_allowance(bytes: u64) -> Result<(), IoError> {
ATTEMPT_ALLOWANCE.with(|a| match a.get() {
Some(remaining) => {
if bytes == u64::MAX || bytes > remaining {
return Err(IoError::PsdImportBudget { required: bytes, limit: remaining });
}
a.set(Some(remaining - bytes));
Ok(())
}
None => {
// Unknown allowance during reentrant gate must fail closed.
Err(IoError::PsdImportBudget { required: bytes, limit: 0 })
}
})
}
/// The enclosing attempt's remaining allowance, for tests that assert a nested import was
/// charged instead of resetting the parent attempt's budget.
#[cfg(test)]
pub(crate) fn active_attempt_remaining() -> Option<u64> {
ATTEMPT_ALLOWANCE.with(|a| a.get())
}
/// 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(crate) fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Result<AdmissionGuard, IoError> {
let current_thread = std::thread::current().id();
let (mutex, _cvar) = get_gate();
let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if state.active && state.owner == Some(current_thread) {
ctl.check().map_err(|_| IoError::Cancelled)?;
NESTED_DEPTH.with(|d| d.set(d.get().saturating_add(1)));
return Ok(AdmissionGuard { _marker: PhantomData });
}
#[cfg(target_arch = "wasm32")]
if state.active {
// Stateless wasm is single-threaded: contention cannot be resolved by waiting on Condvar.
return Err(IoError::Unsupported("concurrent PSD decoding is not supported on wasm".into()));
}
#[cfg(not(target_arch = "wasm32"))]
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);
NESTED_DEPTH.with(|d| d.set(1));
Ok(AdmissionGuard { _marker: PhantomData })
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn reentrant_admission_does_not_deadlock() {
let ctl = photocraft_raster::Interrupt::NONE;
let guard1 = acquire_decode_admission(&ctl).unwrap();
assert!(is_holding_admission());
// Nested admission on the same thread
let guard2 = acquire_decode_admission(&ctl).unwrap();
assert!(is_holding_admission());
drop(guard2);
assert!(is_holding_admission());
drop(guard1);
assert!(!is_holding_admission());
// Can acquire again after release
let _guard3 = acquire_decode_admission(&ctl).unwrap();
assert!(is_holding_admission());
}
#[test]
fn unknown_allowance_during_reentrant_gate_fails_closed() {
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = acquire_decode_admission(&ctl).unwrap();
// Allowance is None (unknown)
let res = consume_attempt_allowance(100);
assert!(matches!(res, Err(IoError::PsdImportBudget { limit: 0, .. })));
}
#[test]
fn nested_allowance_consumption_deducts_and_caps() {
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = acquire_decode_admission(&ctl).unwrap();
set_active_attempt_budget(5000);
assert!(consume_attempt_allowance(2000).is_ok());
assert_eq!(ATTEMPT_ALLOWANCE.with(|a| a.get()), Some(3000));
assert!(consume_attempt_allowance(3001).is_err());
assert!(consume_attempt_allowance(1000).is_ok());
assert_eq!(ATTEMPT_ALLOWANCE.with(|a| a.get()), Some(2000));
}
/// A saturated estimate is not a charge, even when the parent's allowance is the same
/// saturated value: it is refused and spends nothing.
#[test]
fn a_saturated_nested_charge_is_refused_and_spends_nothing() {
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = acquire_decode_admission(&ctl).unwrap();
set_active_attempt_budget(u64::MAX);
let err = consume_attempt_allowance(u64::MAX).expect_err("the overflow sentinel is never a charge");
assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == u64::MAX && limit == u64::MAX));
assert_eq!(active_attempt_remaining(), Some(u64::MAX), "a refused sentinel charge leaves the parent's allowance untouched");
// One byte below the sentinel is an ordinary, enormous charge.
assert!(consume_attempt_allowance(u64::MAX - 1).is_ok());
assert_eq!(active_attempt_remaining(), Some(1));
}
#[test]
fn gate_serializes_concurrent_threads() {
let ctl = photocraft_raster::Interrupt::NONE;
let guard = acquire_decode_admission(&ctl).unwrap();
let thread_started = Arc::new(AtomicBool::new(false));
let thread_acquired = Arc::new(AtomicBool::new(false));
let t_started = Arc::clone(&thread_started);
let t_acquired = Arc::clone(&thread_acquired);
let handle = std::thread::spawn(move || {
let ctl = photocraft_raster::Interrupt::NONE;
t_started.store(true, Ordering::SeqCst);
let g = acquire_decode_admission(&ctl).unwrap();
t_acquired.store(true, Ordering::SeqCst);
drop(g);
});
while !thread_started.load(Ordering::SeqCst) {
std::thread::yield_now();
}
// Give background thread time to reach condvar wait
std::thread::sleep(Duration::from_millis(60));
assert!(!thread_acquired.load(Ordering::SeqCst), "second thread must block while guard held");
drop(guard);
handle.join().unwrap();
assert!(thread_acquired.load(Ordering::SeqCst), "second thread must acquire after release");
}
#[test]
fn blocked_wait_aborts_on_cancellation() {
let ctl = photocraft_raster::Interrupt::NONE;
let guard = acquire_decode_admission(&ctl).unwrap();
let cancelled = Arc::new(AtomicBool::new(false));
let c_flag = Arc::clone(&cancelled);
let flag_for_thread = Arc::clone(&cancelled);
let handle = std::thread::spawn(move || {
let cancelled = || flag_for_thread.load(Ordering::SeqCst);
let progress = |_: f32| {};
let interrupt = photocraft_raster::Interrupt::new(&cancelled, &progress);
acquire_decode_admission(&interrupt).map(drop)
});
// Let thread block on condvar
std::thread::sleep(Duration::from_millis(60));
// Cancel waiting thread
c_flag.store(true, Ordering::SeqCst);
let res = handle.join().unwrap();
assert!(matches!(res, Err(IoError::Cancelled)), "waiting thread must abort with Cancelled");
// First thread releases guard
drop(guard);
// Subsequent acquire succeeds cleanly
let next_guard = acquire_decode_admission(&ctl);
assert!(next_guard.is_ok(), "gate must remain functional after cancelled wait");
}
}
+44 -5
View File
@@ -1228,6 +1228,30 @@ pub(crate) fn psd_to_document_decoded_integrity(
psd_to_document_global(file, ctl, decoded, global, false).map(|(doc, warnings, damaged, _)| (doc, warnings, damaged))
}
/// Admission for a legacy conversion.
///
/// A nested conversion spends the enclosing attempt's remaining allowance and never resets it.
/// A standalone conversion refuses an ineligible file before waiting for the decode gate and
/// rechecks the fresh measurement once admitted, so a refused file never waits behind an active
/// decode and a memory drop during the wait is seen before any pixel is decoded.
fn legacy_admission(est: &crate::psd_budget::PsdMemoryEstimate, ctl: &photocraft_raster::Interrupt) -> Result<crate::psd_gate::AdmissionGuard, crate::IoError> {
if crate::psd_gate::is_holding_admission() {
// Cancellation is checked before the charge and admission is reentrant here, so a
// cancelled or refused nested conversion never spends its parent's allowance.
ctl.check().map_err(|_| crate::IoError::Cancelled)?;
let guard = crate::psd_gate::acquire_decode_admission(ctl)?;
crate::psd_gate::consume_attempt_allowance(est.total_bytes)?;
return Ok(guard);
}
let snapshot = || crate::memory::MemorySnapshot::current();
// Legacy standalone is unconfirmed: it cannot silently auto allow an estimate above S.
crate::memory::evaluate_psd_admission(est.total_bytes, est.tile_bytes, 0, false, None, snapshot())?;
let guard = crate::psd_gate::acquire_decode_admission(ctl)?;
let outcome = crate::memory::evaluate_psd_admission(est.total_bytes, est.tile_bytes, 0, false, None, snapshot())?;
crate::psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes));
Ok(guard)
}
fn psd_to_document_global(
file: &PsdFile,
ctl: &photocraft_raster::Interrupt,
@@ -1238,11 +1262,26 @@ fn psd_to_document_global(
// Legacy conversion APIs return warnings rather than Result. Reject before metadata or
// pixels are decoded, and retain the fatal error for the ordinary import path. An import
// that checked the file against its own limit first (`preflighted`) does not estimate twice.
if !preflighted && let Err(error) = crate::psd_budget::check(file, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) {
let message = error.to_string();
let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);
return Some((doc, vec![message], true, Some(error)));
}
let _guard = if !preflighted || !crate::psd_gate::is_holding_admission() {
let est = match crate::psd_budget::estimate(file) {
Ok(e) => e,
Err(error) => {
let message = error.to_string();
let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);
return Some((doc, vec![message], true, Some(error)));
}
};
match legacy_admission(&est, ctl) {
Ok(guard) => Some(guard),
Err(error) => {
let message = error.to_string();
let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);
return Some((doc, vec![message], true, Some(error)));
}
}
} else {
None
};
let (mode, layered, multichannel, depth) = import_format(file);
let h = &file.header;
let mut warnings = Vec::new();
+27
View File
@@ -600,3 +600,30 @@ fn only_allocation_failures_are_fatal_to_a_layer_channel() {
other => panic!("{other:?}"),
}
}
/// A standalone legacy conversion that is over budget is refused *before* it waits for the
/// decode gate, so an ineligible file never blocks behind an active decode. The legacy API keeps
/// its warning (the ordinary import path still receives the fatal error).
#[test]
fn legacy_conversion_refuses_before_waiting_for_the_decode_gate() {
let mut file = testgen::small(Version::Psd, Compression::Zip);
// 30,000² tiles are several GiB: far past the hard budget of the 4 GiB machine below.
file.layers_mut()[0].rect = photocraft_psd::Rect::from_xywh(0, 0, 30_000, 30_000);
let snapshot = crate::memory::MemorySnapshot { available_ram: Some(4 << 30), swap_free: None, commit_headroom: None };
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = crate::psd_gate::acquire_decode_admission(&ctl).expect("active decode");
let (tx, rx) = std::sync::mpsc::channel();
let handle = std::thread::spawn(move || {
let (doc, warnings) = crate::memory::with_mock_memory(snapshot, || crate::psd_to_document(&file));
tx.send((doc.layers.len(), warnings)).ok();
});
// The refusal arrives while this thread still holds the gate: the legacy call never waited.
let (layers, warnings) = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a refused legacy conversion must not wait for the decode gate");
assert_eq!(layers, 0, "a refused conversion returns an empty document");
assert!(warnings.iter().any(|w| w.contains("pixel memory")), "{warnings:?}");
drop(_guard);
handle.join().expect("worker thread");
}
+498 -42
View File
@@ -48,19 +48,64 @@ fn set_resource(resources: &mut Vec<ImageResource>, id: u16, data: Option<Vec<u8
}
}
/// Opens a TIFF whose `img` carries Photoshop layer data in `layers` (its 37724 tag).
pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit: u64) -> Result<ImportResult, IoError> {
let mut warnings = Vec::new();
let (isd, w) = match ImageSourceData::from_bytes(layers) {
/// Everything a layered TIFF page's Photoshop tags say, read before any pixel is decoded.
///
/// It is built from a [`codecs::TiffBands`] page's dimensions, layout, sample type,
/// extra-sample count, metadata and decoder scratch bound, never from its pixels, so the whole
/// import is admitted through the adaptive budget before the composite is decoded.
pub(crate) struct LayeredPlan {
/// The PSD model the layer tag rebuilds, or `None` when the tag could not be read and the
/// page opens flattened.
model: Option<Box<LayeredModel>>,
/// Why the page opens flattened, when the layer tag did not parse.
flatten_warning: Option<String>,
/// Warnings the layer tag and the image resources produced.
warnings: Vec<String>,
/// Bytes this import needs beside what it already holds, for admission; see
/// [`layered_import_bytes`].
pub(crate) required: u64,
/// The part of `required` that is tile pixels, spillable to the scratch disk
/// ([`crate::psd_budget::PsdMemoryEstimate::tile_bytes`]); 0 for a flattened fallback, whose
/// admission charge is decode and conversion memory.
pub(crate) tiles: u64,
}
struct LayeredModel {
/// The PSD model with an empty merged image: the TIFF's pixels replace it after decoding.
file: photocraft_psd::PsdFile,
}
impl LayeredPlan {
/// Whether the page's layer tag parsed into a PSD model, as opposed to opening flattened.
///
/// A flattened fallback still reads the page's image resources for channel names and spot
/// flags, so the decoder's copies stay available; a layered page's tags are already in the
/// plan and the decoder's copies can be dropped.
pub(crate) fn is_layered(&self) -> bool {
self.model.is_some()
}
}
/// Reads a layered TIFF page's layer tag and image resources into a [`LayeredPlan`] without
/// decoding any pixels, and checks the group nesting depth and the PSD memory estimate.
pub(crate) fn preflight(bands: &codecs::TiffBands<'_>) -> Result<LayeredPlan, IoError> {
let (w, h) = bands.dimensions();
let (layout, sample) = (bands.layout(), bands.sample_type());
let extras = bands.extra_samples();
let scratch = bands.decode_scratch_bytes();
let layers = bands.meta.photoshop_layers.as_deref().unwrap_or_default();
let (isd, isd_warnings) = match ImageSourceData::from_bytes(layers) {
Ok(v) => v,
Err(e) => {
let mut r = image_to_document(name, img)?;
r.warnings.push(format!("the PSD layer data could not be read ({e}); opened flattened"));
return Ok(r);
// Malformed layer data opens flat, but the composite it opens still has to be
// bounded: its whole-image decode and the conversion are admitted too.
let warning = format!("the PSD layer data could not be read ({e}); opened flattened");
let required = crate::flat::flattened_import_bytes(w, h, layout, sample, extras, scratch);
return Ok(LayeredPlan { model: None, flatten_warning: Some(warning), warnings: Vec::new(), required, tiles: 0 });
}
};
warnings.extend(w.into_iter().map(|w| format!("layer data: {w}")));
let (mut resources, w) = match img.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()).map(resources_from_bytes) {
let mut warnings: Vec<String> = isd_warnings.into_iter().map(|w| format!("layer data: {w}")).collect();
let (mut resources, resource_warnings) = match bands.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()).map(resources_from_bytes) {
Some(Ok(v)) => v,
Some(Err(e)) => {
warnings.push(format!("the PSD image resources could not be read: {e}"));
@@ -68,44 +113,38 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit
}
None => (Vec::new(), Vec::new()),
};
warnings.extend(w.into_iter().map(|w| format!("image resources: {w}")));
// The profile, resolution, XMP and EXIF are the TIFF's own tags; they win over any copy
// in the resources.
set_resource(&mut resources, ids::ICC_PROFILE, img.icc.clone());
if let Some((x, y)) = img.meta.dpi.filter(|d| d.0 > 0.0) {
warnings.extend(resource_warnings.into_iter().map(|w| format!("image resources: {w}")));
// The profile, resolution, XMP and EXIF are the TIFF's own tags; they win over any copy in
// the resources. They are set here, from the page's metadata, because the model is complete
// before the composite exists.
set_resource(&mut resources, ids::ICC_PROFILE, bands.icc.clone());
if let Some((x, y)) = bands.meta.dpi.filter(|d| d.0 > 0.0) {
// Both axes, so the PSD import notes a vertical resolution the document can't keep.
let ri = ResolutionInfo { v_res_fixed: ResolutionInfo::from_dpi(f64::from(y)).v_res_fixed, ..ResolutionInfo::from_dpi(f64::from(x)) };
set_resource(&mut resources, ids::RESOLUTION_INFO, Some(ri.to_bytes()));
}
if let Some(xmp) = &img.meta.xmp {
if let Some(xmp) = &bands.meta.xmp {
set_resource(&mut resources, ids::XMP, Some(xmp.as_bytes().to_vec()));
}
if let Some(exif) = &img.meta.exif {
if let Some(exif) = &bands.meta.exif {
set_resource(&mut resources, ids::EXIF, Some(exif.clone()));
}
// The TIFF's pixels become the PSD's merged image: planar, big-endian, CMYK inverted.
let (mode, color_channels) = match img.layout() {
ChannelLayout::Gray | ChannelLayout::GrayA => (PsdMode::Grayscale, 1),
ChannelLayout::Rgb | ChannelLayout::Rgba => (PsdMode::Rgb, 3),
ChannelLayout::Cmyk | ChannelLayout::CmykA => (PsdMode::Cmyk, 4),
ChannelLayout::Lab | ChannelLayout::LabA => (PsdMode::Lab, 3),
let mode = match layout {
ChannelLayout::Gray | ChannelLayout::GrayA => PsdMode::Grayscale,
ChannelLayout::Rgb | ChannelLayout::Rgba => PsdMode::Rgb,
ChannelLayout::Cmyk | ChannelLayout::CmykA => PsdMode::Cmyk,
ChannelLayout::Lab | ChannelLayout::LabA => PsdMode::Lab,
};
let depth = match img.sample_type() {
let depth = match sample {
CSample::U8 => 8,
CSample::U16 => 16,
CSample::F16 | CSample::F32 => 32,
};
let (w, h) = img.dimensions();
// A half-float image is stored as 32-bit float; it is converted after the budget check, as
// the conversion allocates several times the decoded image.
let bps = if img.sample_type() == CSample::F16 { CSample::F32.bytes() } else { img.sample_type().bytes() };
let plane_len = (w as usize).saturating_mul(h as usize).saturating_mul(bps);
// The budget is checked on the model before the planar copy of the whole image is allocated,
// so an over-budget file is refused without it. The extra samples that fit the image count
// towards the channels the check sees.
let extras = img.meta.extra_samples.iter().take(codecs::MAX_EXTRA_SAMPLES).filter(|e| e.data.len() == plane_len).count();
let channels = u16::try_from(img.layout().channels().saturating_add(extras)).map_err(|_| IoError::Unsupported("too many channels".into()))?;
// The extra samples that fit the image count towards the channels the estimate sees; the
// codec already capped them at [`codecs::MAX_EXTRA_SAMPLES`].
let channels = u16::try_from(layout.channels().saturating_add(extras)).map_err(|_| IoError::Unsupported("too many channels".into()))?;
let header = Header::new(isd.version, w, h, channels, depth, mode);
let mut file = isd.into_psd(header, resources, ImageData::new(Compression::Raw, Vec::new()));
// Empty `Patt` and the default filter mask are written so Photoshop's block list matches
@@ -118,13 +157,73 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit
});
// The same nesting limit as opening a PSD (#2940).
crate::psd_import::check_group_depth(&file)?;
// The planar composite is copied whether or not the budget counts a merged image, so it is
// held against the allowance as well.
let composite = u64::try_from(plane_len.saturating_mul(usize::from(channels))).unwrap_or(u64::MAX);
if composite > pixel_limit {
return Err(photocraft_psd::PsdError::LimitExceeded("the TIFF composite exceeds the import allowance").into());
}
crate::psd_budget::check(&file, pixel_limit - composite)?;
// Layer/mask/merged pixel planes and their conversion workspace, from the tag alone.
let est = crate::psd_budget::estimate(&file)?;
// The decoder makes its own copy of the two Photoshop tags while decoding. The plan's
// copies are already made and are bounded by the file, not by the image size.
let tags = layers.len().saturating_add(bands.meta.photoshop_resources.as_ref().map_or(0, |r| r.len()));
let required = layered_import_bytes(est.total_bytes, w, h, layout.channels(), sample, extras, scratch, tags);
Ok(LayeredPlan { model: Some(Box::new(LayeredModel { file })), flatten_warning: None, warnings, required, tiles: est.tile_bytes })
}
/// Bytes a layered TIFF import needs beyond [`crate::psd_budget::estimate`]'s layer, mask,
/// merged and workspace charge:
///
/// - the decoded composite and its extra-sample planes: the decoder holds the interleaved extra
/// buffer and one split plane per sample at once;
/// - for a 16-bit float page, the normalized and 32-bit copies the conversion makes while the
/// 16-bit image and its planes are still alive;
/// - the planar big-endian merged-image copy, with one extra plane copied while it grows;
/// - the decoder's own scratch buffers (see [`codecs::TiffBands::decode_scratch_bytes`]);
/// - the decoder's copy of the Photoshop tags.
///
/// Every term saturates instead of wrapping: an estimate too large for `u64` is the `u64::MAX`
/// sentinel, which admission always refuses (see [`crate::memory::MemoryBudget::decide`]), so it
/// can never become an admitted, wrapped-around value.
#[allow(clippy::too_many_arguments)]
pub(crate) fn layered_import_bytes(est: u64, w: u32, h: u32, channels: usize, sample: CSample, extras: usize, scratch: u64, tags: usize) -> u64 {
let pixels = u64::from(w).saturating_mul(u64::from(h));
let ch = channels as u64;
let e = extras as u64;
let in_bps = sample.bytes() as u64;
let out_bps = if sample == CSample::F16 { CSample::F32.bytes() as u64 } else { in_bps };
let decoded = pixels.saturating_mul(ch.saturating_add(e.saturating_mul(2))).saturating_mul(in_bps);
// A normalized 32-bit buffer and the 32-bit result exist beside the 16-bit source.
let float_convert = if sample == CSample::F16 { pixels.saturating_mul(ch.saturating_add(e)).saturating_mul(8) } else { 0 };
let planar = pixels.saturating_mul(ch.saturating_add(e)).saturating_mul(out_bps);
let plane = if e > 0 { pixels.saturating_mul(out_bps) } else { 0 };
est.saturating_add(decoded).saturating_add(float_convert).saturating_add(planar).saturating_add(plane).saturating_add(scratch).saturating_add(tags as u64)
}
/// Opens a layered TIFF page from its decoded `img`, using the model and estimate [`preflight`]
/// read from the same page's tags.
///
/// The caller has admitted `plan.required` through the adaptive budget and holds decode
/// admission before any pixel is decoded, so nothing here resolves a second budget or charges
/// the enclosing attempt again: a top-level TIFF is charged once, and a nested independent one
/// spends only what its parent still has. `ctl` stops the PSD conversion between layers.
pub(crate) fn import_layered(name: &str, img: &Image, plan: LayeredPlan, ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
let LayeredPlan { model, flatten_warning, mut warnings, required: _, tiles: _ } = plan;
let Some(model) = model else {
let mut r = image_to_document(name, img)?;
if let Some(warning) = flatten_warning {
r.warnings.push(warning);
}
return Ok(r);
};
let LayeredModel { mut file } = *model;
let mode = match img.layout() {
ChannelLayout::Gray | ChannelLayout::GrayA => PsdMode::Grayscale,
ChannelLayout::Rgb | ChannelLayout::Rgba => PsdMode::Rgb,
ChannelLayout::Cmyk | ChannelLayout::CmykA => PsdMode::Cmyk,
ChannelLayout::Lab | ChannelLayout::LabA => PsdMode::Lab,
};
let color_channels = img.layout().color_channels();
// A half-float image is stored as 32-bit float; it is converted here, after admission, as
// the conversion allocates several times the decoded image (charged by the estimate).
let bps = if img.sample_type() == CSample::F16 { CSample::F32.bytes() } else { img.sample_type().bytes() };
let (w, h) = img.dimensions();
let plane_len = (w as usize).saturating_mul(h as usize).saturating_mul(bps);
let img = if img.sample_type() == CSample::F16 {
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
std::borrow::Cow::Owned(img.convert(img.layout(), CSample::F32))
@@ -149,11 +248,11 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit
// Spot planes are read in Photoshop's polarity (0 = solid ink), as from a PSD. The importer's
// rule for PSDs from earlier PhotoCraft versions never applies: those versions stored no
// extra samples in a TIFF, and a TIFF with them carries 1053.
let (mut doc, w, _, fatal_error) = psd_to_document_owned(file, &photocraft_raster::Interrupt::NONE, None).ok_or(IoError::Cancelled)?;
let (mut doc, psd_warnings, _, fatal_error) = psd_to_document_owned(file, ctl, None).ok_or(IoError::Cancelled)?;
if let Some(error) = fatal_error {
return Err(error);
}
warnings.extend(w);
warnings.extend(psd_warnings);
doc.name = name.to_string();
if doc.icc_profile.is_none() {
doc.icc_profile = img.icc.clone().map(Arc::new);
@@ -996,7 +1095,7 @@ mod tests {
use photocraft_doc::{Color, Document, Fill, FillCache, Layer, LayerContent};
use photocraft_raster::Surface;
use crate::{ExportOptions, export};
use crate::{ExportOptions, ImportOptions, IoError, export};
/// Hidden solid fills on a 2048² canvas: counted as canvas-sized planes (16 MiB each at 8
/// bits), 140 of them pass 2 GB, while their real pixels (the cached rendering, pruned to
@@ -1015,6 +1114,30 @@ mod tests {
doc
}
/// A small two-layer RGB document exported as a TIFF with Photoshop layer data: the real
/// file the admission tests below import. No fixture is decoded at a size near a threshold.
fn layered_tiff(w: u32, h: u32) -> Vec<u8> {
let mut doc = Document::new("charge.tif", photocraft_geom::Size::new(w, h), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
let fmt = doc.pixel_format();
let bytes = (w as usize * h as usize * fmt.bytes_per_pixel()).max(1);
for name in ["bottom", "top"] {
let mut s = Surface::new(fmt);
s.write_interleaved(photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &vec![96u8; bytes]);
doc.layers.push(Layer::new(name, LayerContent::Raster(s)));
}
export(&doc, "charge.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).expect("export layered TIFF").bytes
}
/// The bytes of the layered TIFF's decoded composite: the size of both the planar copy the
/// importer builds and the interleaved image it keeps beside it.
fn composite_bytes(bytes: &[u8]) -> u64 {
let img = photocraft_codecs::decode_with(bytes, &photocraft_codecs::DecodeOptions { keep_orientation: true, ..Default::default() })
.expect("decode the composite");
let (w, h) = img.dimensions();
let sample = u64::try_from(img.sample_type().bytes()).unwrap_or(1);
u64::from(w).saturating_mul(u64::from(h)).saturating_mul(sample).saturating_mul(img.layout().channels() as u64)
}
#[test]
fn layered_tiff_ignores_the_uncompressed_size_estimate() {
let doc = many_cheap_fills();
@@ -1039,4 +1162,337 @@ mod tests {
let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes);
assert!(layers.unwrap().starts_with(photocraft_psd::tiff::SIGNATURE_PSB));
}
/// The adaptive budget, not only the caller's pixel limit, decides a layered TIFF: a known
/// zero reading refuses the import before the planar composite is allocated, while a normal
/// machine opens the same file. Before this route the fixed 2 GiB default admitted it.
#[test]
fn layered_tiff_import_honours_a_known_zero_adaptive_budget() {
let bytes = layered_tiff(8, 6);
let zero = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(zero, || match crate::import_with_options("zero.tif", &bytes, &ImportOptions::default()) {
Err(IoError::PsdImportBudget { limit: 0, .. }) => {}
other => panic!("expected an import-budget refusal, got {other:?}"),
});
let plenty = crate::memory::MemorySnapshot { available_ram: Some(16 << 30), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(plenty, || {
let opened = crate::import_with_options("plenty.tif", &bytes, &ImportOptions::default()).expect("a normal machine opens it");
assert_eq!(opened.document.layers.len(), 2);
});
}
/// Approval and its estimate bound reach the TIFF route: the same options that a PSD takes
/// decide the layered TIFF's composite, layer and retained-image charge. The fixture is tiny;
/// the threshold charge is a thread-local test seam, so nothing near a gigabyte is allocated.
#[test]
fn layered_tiff_import_uses_the_adaptive_budget_approval_options() {
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let bytes = layered_tiff(8, 6);
// 12 GiB: S = 6 GiB, H = 9 GiB.
let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(snapshot, || {
let plain = crate::import_with_options("l.tif", &bytes, &ImportOptions::default()).expect("automatic").document.layers.len();
crate::psd_budget::with_test_estimate_charge(7 * gb, || {
let required = match crate::import_with_options("l.tif", &bytes, &ImportOptions::default()) {
Err(IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => {
assert_eq!((soft_limit, hard_limit), (6 * gb, 9 * gb));
assert_eq!(available_ram, Some(12 * gb));
required
}
other => panic!("expected an approval request, got {other:?}"),
};
assert!((7 * gb..=9 * gb).contains(&required), "the charge lands in the approval band: {required}");
// Approval opens the same file.
let approved = ImportOptions { psd_high_memory_approved: true, ..Default::default() };
assert_eq!(crate::import_with_options("l.tif", &bytes, &approved).expect("approved").document.layers.len(), plain);
// A matching one-shot estimate bound is enough; a smaller one needs fresh consent.
let bounded = ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required), ..Default::default() };
assert!(crate::import_with_options("l.tif", &bytes, &bounded).is_ok());
let stale = ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required - 1), ..Default::default() };
assert!(matches!(crate::import_with_options("l.tif", &bytes, &stale), Err(IoError::PsdApprovalRequired { .. })));
// Approval never bypasses a lower caller limit.
let lowered = ImportOptions { psd_high_memory_approved: true, psd_max_pixel_bytes: required - 1, ..Default::default() };
assert!(matches!(
crate::import_with_options("l.tif", &bytes, &lowered),
Err(IoError::PsdImportBudget { required: r, limit: l }) if r == required && l == required - 1
));
});
});
}
/// A real nested layered TIFF spends the enclosing attempt's remaining allowance: the charge
/// covers the planar composite and the decoded image kept beside it, and a refused nested
/// import neither waits for a fresh gate nor resets the parent's budget.
#[test]
fn real_nested_layered_tiff_import_is_charged_without_resetting_the_parent() {
let bytes = layered_tiff(8, 6);
let composite = composite_bytes(&bytes);
assert!(composite > 0);
let ctl = photocraft_raster::Interrupt::NONE;
let _guard = crate::psd_gate::acquire_decode_admission(&ctl).expect("parent admission");
let start = 1u64 << 40;
crate::psd_gate::set_active_attempt_budget(start);
crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl).expect("nested import");
let remaining = crate::psd_gate::active_attempt_remaining().expect("the parent attempt keeps an allowance");
let charged = start - remaining;
assert!(
charged >= composite.saturating_mul(2),
"both the planar composite ({composite}) and the decoded image kept beside it are charged; charged {charged}"
);
assert!(crate::psd_gate::is_holding_admission(), "the nested import must not release the parent's admission");
// One byte short: the real import is refused, the reason is the charge, and the parent's
// remaining allowance is untouched.
crate::psd_gate::set_active_attempt_budget(charged - 1);
match crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl) {
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (charged, charged - 1)),
other => panic!("expected an import-budget refusal, got {other:?}"),
}
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(charged - 1), "a failed nested import leaves the allowance as it was");
// Exactly enough succeeds and leaves nothing, so the charge is not reset per attempt.
crate::psd_gate::set_active_attempt_budget(charged);
crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl).expect("exact allowance");
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(0));
}
/// A cancelled job stops waiting for the PSD decode gate: the interrupt reaches the layered
/// TIFF's gate wait, so it does not block behind another decode until that one finishes.
#[test]
fn cancelled_layered_tiff_import_stops_waiting_for_the_gate() {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
let bytes = layered_tiff(8, 6);
let snapshot = crate::memory::MemorySnapshot { available_ram: Some(32 << 30), swap_free: None, commit_headroom: None };
let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE).expect("active decode");
let cancel = Arc::new(AtomicBool::new(false));
let prechecked = Arc::new(AtomicBool::new(false));
let (tx, rx) = std::sync::mpsc::channel();
let handle = {
let cancel = Arc::clone(&cancel);
let prechecked = Arc::clone(&prechecked);
std::thread::spawn(move || {
let provider = std::rc::Rc::new(move || {
prechecked.store(true, Ordering::SeqCst);
snapshot
});
let cancelled = move || cancel.load(Ordering::SeqCst);
let progress = |_: f32| {};
let ctl = photocraft_raster::Interrupt::new(&cancelled, &progress);
let result = crate::memory::with_mock_memory_provider(provider, || {
crate::import_with_options_and_interrupt("cancel.tif", &bytes, &ImportOptions::default(), &ctl)
});
tx.send(result.map(|r| r.document.layers.len())).ok();
})
};
// The provider's first call is the precheck, which happens before the gate wait.
let deadline = Instant::now() + Duration::from_secs(10);
while !prechecked.load(Ordering::SeqCst) {
assert!(Instant::now() < deadline, "the import never reached its admission precheck");
std::thread::yield_now();
}
cancel.store(true, Ordering::SeqCst);
// This thread still holds the gate, so the only way to answer is to abort the wait.
let result = rx.recv_timeout(Duration::from_secs(10)).expect("a cancelled import must stop waiting for the gate");
match result {
Err(IoError::Cancelled) => {}
other => panic!("expected the cancelled import to fail, got {other:?}"),
}
drop(_guard);
handle.join().expect("worker thread");
}
/// The estimate covers what the layered import holds besides the PSD layer model: the
/// decoded composite, the planar merged copy, the decoder's extra-sample planes and scratch,
/// the tags it copies, and a half-float conversion's extra buffers.
#[test]
fn layered_estimate_counts_decode_conversion_extras_and_scratch() {
use photocraft_codecs::SampleType as S;
// 100 × 50 px, RGB, 8-bit, no extras: the decoded image plus the planar copy.
let pixels = 100u64 * 50;
assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::U8, 0, 0, 0), 2 * pixels * 3);
// Two extra samples add their interleaved buffer, their split planes and one big-endian
// plane copied into the merged image.
assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::U8, 2, 0, 0), pixels * 13);
// A half-float page is converted: the 16-bit image and planes stay alive beside the
// normalized 32-bit buffer and the 32-bit result.
assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::F16, 0, 0, 0), pixels * (3 * 2 + 3 * 8 + 3 * 4));
let base = super::layered_import_bytes(0, 100, 50, 3, S::U8, 0, 0, 0);
assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::U8, 0, 1234, 99), base + 1234 + 99);
assert_eq!(super::layered_import_bytes(u64::MAX, 100, 50, 3, S::U8, 0, 0, 0), u64::MAX, "an estimate never wraps into an admitted one");
}
/// A TIFF whose layer tag cannot be read still opens flattened, and its whole-image decode
/// and conversion are admitted like a layered page: a refused file never reaches the decode,
/// and the flatten warning is unchanged.
#[test]
fn malformed_layer_tag_bounds_the_composite_before_it_is_decoded() {
use std::cell::Cell;
use std::rc::Rc;
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![40; 4 * 3 * 3]).unwrap();
img.meta.photoshop_layers = Some(b"not Photoshop image source data".to_vec());
let bytes = photocraft_codecs::encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
let decoded = Rc::new(Cell::new(0u32));
let hook = |decoded: &Rc<Cell<u32>>| -> Rc<dyn Fn()> {
let decoded = Rc::clone(decoded);
Rc::new(move || decoded.set(decoded.get() + 1))
};
let zero = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(zero, || {
crate::flat::with_before_composite_decode(hook(&decoded), || {
match crate::import_with_options("bogus.tif", &bytes, &ImportOptions::default()) {
Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0),
other => panic!("expected an import-budget refusal, got {other:?}"),
}
assert_eq!(decoded.get(), 0, "a refused file must not decode its composite");
});
});
let plenty = crate::memory::MemorySnapshot { available_ram: Some(16 << 30), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(plenty, || {
crate::flat::with_before_composite_decode(hook(&decoded), || {
let opened = crate::import_with_options("bogus.tif", &bytes, &ImportOptions::default()).expect("a normal machine opens the composite");
assert_eq!(opened.document.layers.len(), 1);
assert!(opened.warnings.iter().any(|w| w.contains("opened flattened")), "{:?}", opened.warnings);
assert_eq!(decoded.get(), 1, "the admitted import decodes the composite exactly once");
});
});
}
/// Admission happens before a layered TIFF's composite is decoded: a known-zero budget and
/// an approval-needed estimate both refuse the file without reaching the decode, and an
/// approved import does reach it. The fixture is the real tiny layered TIFF; the estimate
/// threshold is the scoped test seam, so nothing near a gigabyte is allocated.
#[test]
fn layered_tiff_is_refused_before_its_composite_is_decoded() {
use std::cell::Cell;
use std::rc::Rc;
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let bytes = layered_tiff(8, 6);
let decoded = Rc::new(Cell::new(0u32));
let hook = |decoded: &Rc<Cell<u32>>| -> Rc<dyn Fn()> {
let decoded = Rc::clone(decoded);
Rc::new(move || decoded.set(decoded.get() + 1))
};
let zero = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(zero, || {
crate::flat::with_before_composite_decode(hook(&decoded), || {
match crate::import_with_options("zero.tif", &bytes, &ImportOptions::default()) {
Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0),
other => panic!("expected an import-budget refusal, got {other:?}"),
}
assert_eq!(decoded.get(), 0, "a refused file must not decode its composite");
});
});
// 12 GiB: S = 6 GiB, H = 9 GiB. The seam puts the estimate in the approval band.
let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None };
crate::memory::with_mock_memory(snapshot, || {
crate::flat::with_before_composite_decode(hook(&decoded), || {
crate::psd_budget::with_test_estimate_charge(7 * gb, || {
match crate::import_with_options("approval.tif", &bytes, &ImportOptions::default()) {
Err(IoError::PsdApprovalRequired { required, soft_limit, hard_limit, .. }) => {
assert_eq!((soft_limit, hard_limit), (6 * gb, 9 * gb));
assert!(required > 6 * gb, "the charge reaches the approval band: {required}");
}
other => panic!("expected an approval request, got {other:?}"),
}
assert_eq!(decoded.get(), 0, "approval is needed before the composite is decoded, not after it");
let approved = ImportOptions { psd_high_memory_approved: true, ..Default::default() };
let opened = crate::import_with_options("approval.tif", &bytes, &approved).expect("approved");
assert_eq!(opened.document.layers.len(), 2);
assert_eq!(decoded.get(), 1, "the approved import decodes the composite exactly once");
});
});
});
}
/// Available memory can drop while a layered TIFF waits for the decode gate: the post-gate
/// recheck must refuse it before the composite is decoded. A per-attempt provider shared with
/// this test only changes the measurement; nothing near a gigabyte is allocated.
#[test]
fn layered_tiff_memory_drop_while_waiting_for_the_gate_refuses_before_decoding() {
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
return;
}
let gb = 1u64 << 30;
let bytes = layered_tiff(8, 6);
// Hold the gate so the import stops between its pre-gate check and the post-gate one.
let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE).expect("active decode");
let available = Arc::new(AtomicU64::new(32 * gb));
let prechecked = Arc::new(AtomicBool::new(false));
let decoded = Arc::new(AtomicBool::new(false));
let (tx, rx) = std::sync::mpsc::channel();
let handle = {
let available = Arc::clone(&available);
let prechecked = Arc::clone(&prechecked);
let decoded = Arc::clone(&decoded);
std::thread::spawn(move || {
let provider = Rc::new(move || {
// Read before signalling, so the pre-gate check that the main thread waits
// for has already measured the larger figure.
let ram = available.load(Ordering::SeqCst);
prechecked.store(true, Ordering::SeqCst);
crate::memory::MemorySnapshot { available_ram: Some(ram), swap_free: None, commit_headroom: None }
});
let hook: Rc<dyn Fn()> = Rc::new(move || decoded.store(true, Ordering::SeqCst));
let result = crate::memory::with_mock_memory_provider(provider, || {
crate::flat::with_before_composite_decode(hook, || crate::import_with_options("drop.tif", &bytes, &ImportOptions::default()))
});
tx.send(result.map(|r| r.document.layers.len())).ok();
})
};
// The provider's first call is the pre-gate admission check.
let deadline = Instant::now() + Duration::from_secs(10);
while !prechecked.load(Ordering::SeqCst) {
assert!(Instant::now() < deadline, "the import never reached its admission precheck");
std::thread::yield_now();
}
// The precheck admitted it; now the machine has nothing left. Release the gate afterwards.
available.store(0, Ordering::SeqCst);
drop(_guard);
let result = rx.recv_timeout(Duration::from_secs(10)).expect("the post-gate recheck must refuse instead of decoding");
match result {
Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0),
other => panic!("expected the post-gate recheck to refuse with a zero budget, got {other:?}"),
}
assert!(!decoded.load(Ordering::SeqCst), "the composite must not be decoded after the post-gate refusal");
handle.join().expect("worker thread");
}
}
+6 -1
View File
@@ -18,7 +18,12 @@ lz4_flex = { version = "0.11", default-features = false, features = ["std", "saf
# sysinfo reads the physical RAM size for the memory limit and the scratch volume's free space.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rayon = { workspace = true }
sysinfo = { version = "0.37", default-features = false, features = ["system", "disk"] }
sysinfo = { version = "=0.40.1", default-features = false, features = ["system", "disk"] }
# Available physical memory and commit headroom (memory/system.rs) through winsafe's safe
# `GlobalMemoryStatusEx` wrapper.
[target.'cfg(windows)'.dependencies]
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel"] }
[dev-dependencies]
proptest = { workspace = true }
+14 -3
View File
@@ -6,6 +6,8 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
pub mod system;
const MIB: u64 = 1 << 20;
#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
@@ -76,14 +78,23 @@ pub fn configuration_generation() -> u64 {
#[cfg(not(target_arch = "wasm32"))]
pub fn measure() -> Snapshot {
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
static SYSTEM: OnceLock<Mutex<System>> = OnceLock::new();
let mut s = SYSTEM.get_or_init(|| Mutex::new(System::new())).lock().unwrap_or_else(PoisonError::into_inner);
static SYSTEM: OnceLock<Mutex<Option<System>>> = OnceLock::new();
let mut guard = SYSTEM.get_or_init(|| Mutex::new(System::new().ok())).lock().unwrap_or_else(PoisonError::into_inner);
// No provider: an unknown total keeps the configured ceiling (see [`budgets`]).
let Some(s) = guard.as_mut() else { return Snapshot::default() };
s.refresh_memory();
let pid = Pid::from_u32(std::process::id());
s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), true, ProcessRefreshKind::nothing().with_memory());
// The shared detector bounds host memory by the process's cgroup and, on macOS, counts only
// reclaimable pages. A constraint it could not read keeps the host figure here: the tile
// budget only decides what to spill, and a fail-closed zero would stall every operation.
let available = match system::current() {
system::SystemMemory { available_ram: Some(ram), constraint_unreadable: false, .. } => ram,
_ => s.available_memory(),
};
Snapshot {
total_bytes: s.total_memory(),
available_bytes: s.available_memory(),
available_bytes: available,
process_resident_bytes: s.process(pid).map_or(0, |p| p.memory()),
process_virtual_bytes: s.process(pid).map_or(0, |p| p.virtual_memory()),
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -247,7 +247,7 @@ fn reap_abandoned(dir: &Path, own: &File) {
use std::os::unix::fs::MetadataExt;
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
let Ok(metadata) = own.metadata() else { return };
let mut system = System::new();
let Ok(mut system) = System::new() else { return };
system.refresh_processes_specifics(ProcessesToUpdate::All, true, ProcessRefreshKind::nothing());
// Fail closed when process enumeration isn't available. Live files are never removed.
if system.process(Pid::from_u32(std::process::id())).is_none() {
+25 -7
View File
@@ -508,13 +508,8 @@ fn no_room(dir: &Path, cap: Option<u64>) -> String {
#[cfg(not(target_arch = "wasm32"))]
fn free_space(dir: &Path) -> Option<(u64, u64)> {
let dir = std::fs::canonicalize(dir).ok()?;
let disks = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage());
disks
.list()
.iter()
.filter(|d| dir.starts_with(d.mount_point()))
.max_by_key(|d| d.mount_point().as_os_str().len())
.map(|d| (d.available_space(), d.total_space()))
let disks = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage()).ok()?;
disks.iter().filter(|d| dir.starts_with(d.mount_point())).max_by_key(|d| d.mount_point().as_os_str().len()).map(|d| (d.available_space(), d.total_space()))
}
#[cfg(target_arch = "wasm32")]
@@ -695,6 +690,29 @@ pub fn last_error() -> Option<String> {
M.config().last_error.clone()
}
/// Uncompressed tile bytes the scratch disk can still take before it reaches its size limit
/// ([`set_size_cap`]) or the volume's free-space reserve, so an import can admit tile pixels
/// beyond physical RAM. `None` while spilling is off or paused, and when neither the free space
/// nor a size limit is known (nothing to promise). Tiles are written compressed; this counts
/// them uncompressed, less 1/64 for the allocator's block rounding, so it never over-promises.
pub fn scratch_capacity() -> Option<u64> {
if !enabled() || paused() {
return None;
}
let (dir, used, cap) = {
let c = M.config();
(c.dir.clone()?, c.file.as_ref().map_or(0, |f| f.used()), c.size_cap)
};
let room = free_space(&dir).map(|(available, total)| available.saturating_sub(RESERVE_MIN.max(total / 20)));
let room = match (room, cap) {
(Some(room), Some(cap)) => room.min(cap.saturating_sub(used)),
(Some(room), None) => room,
(None, Some(cap)) => cap.saturating_sub(used),
(None, None) => return None,
};
Some(room - room / 64)
}
/// Whether spilling is on (tiles beyond the budget go to disk).
pub fn enabled() -> bool {
M.budget.load(Ordering::Relaxed) > 0
+40
View File
@@ -0,0 +1,40 @@
//! [`spill::scratch_capacity`]: the room imports may count on for tile pixels beyond RAM.
//!
//! One test function: the spill manager is process-wide, so its steps must not interleave.
use photocraft_raster::spill;
#[test]
fn scratch_capacity_follows_spilling_the_size_limit_and_pauses() {
let root = std::env::temp_dir().join(format!("photocraft-scratch-capacity-{}", std::process::id()));
let dir = root.join("scratch");
// Spilling off: nothing to promise.
spill::configure(None, 0).unwrap();
assert_eq!(spill::scratch_capacity(), None);
spill::configure(Some(&dir), 1 << 20).unwrap();
assert!(spill::enabled() && !spill::paused());
// The free-space reserve applies; an unknown volume without a size limit promises nothing.
if let Some(room) = spill::scratch_capacity() {
assert!(room < u64::MAX / 2, "the reserve and margin are applied: {room}");
}
// The Scratch Size Limit bounds it, less the 1/64 margin, whatever the volume has free.
let cap = 64u64 << 20;
spill::set_size_cap(Some(cap));
let room = spill::scratch_capacity().expect("a size limit is known room");
assert!(room <= cap - cap / 64, "{room}");
// Paused (an unusable directory): no credit while tiles cannot leave memory.
let blocked = root.join("not-a-dir");
std::fs::write(&blocked, b"x").unwrap();
assert!(spill::configure(Some(&blocked), 1 << 20).is_err());
assert!(spill::paused());
assert_eq!(spill::scratch_capacity(), None);
spill::set_size_cap(None);
spill::configure(None, 0).unwrap();
assert_eq!(spill::scratch_capacity(), None);
let _ = std::fs::remove_dir_all(&root);
}
+1
View File
@@ -57,6 +57,7 @@ sys-locale = "=0.3.2"
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] }
[dev-dependencies]
photocraft-io = { workspace = true, features = ["testgen"] }
# egui's own default fonts in tests: the oracle for egui_fonts.rs, and contexts made with
# `Context::default()` (no install_fonts) can lay out text.
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
+2
View File
@@ -194,6 +194,8 @@ impl PhotocraftApp {
jpeg_options: None,
dds_options: None,
held_opens: Default::default(),
held_memory_prompts: Default::default(),
prompt_order: Default::default(),
held_preset_import: None,
allow_close: false,
stylus: Default::default(),
+41 -8
View File
@@ -58,6 +58,19 @@ impl PhotocraftApp {
/// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes
/// to Open Recent), when known.
pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result<Vec<String>, String> {
self.open_bytes_placed(name, bytes, path, None, None)
}
/// [`Self::open_bytes_from`] for a file dropped on a tab slot (`slot`) or opened as one of a
/// set (`order`): both survive the inline decode, a memory prompt and the final placement.
pub(crate) fn open_bytes_placed(
&mut self,
name: &str,
bytes: &[u8],
path: Option<&str>,
slot: Option<usize>,
order: Option<crate::jobs_ui::OpenOrder>,
) -> Result<Vec<String>, String> {
if let Some(r) = preset_files_ui::open(self, name, bytes) {
return r.map(|()| Vec::new());
}
@@ -65,15 +78,28 @@ impl PhotocraftApp {
// Decoded on a worker: a tab with progress appears now, the document when it's ready
// (warnings are shown then).
if self.background_jobs {
jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?;
jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes), slot, order)?;
return Ok(Vec::new());
}
let import = self.services.import.as_ref().ok_or("no importer configured")?;
let opts = photocraft_engine::jobs::import_options(self.session.prefs());
let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) {
// A PSD and a magic-detected TIFF both go through the typed IO path: only it carries
// `PsdApprovalRequired` (and, for a PSD, the structured damaged flag), so a layered
// TIFF's high-memory decision can raise its prompt instead of becoming a terminal
// string. Every other format keeps the shell's import service.
let typed_open = photocraft_io::is_psd(bytes) || photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff);
let (mut doc, warnings, damaged) = if typed_open {
// Read PSD damage as structured information in the same decode, not by
// retrying an error or matching the text of a compatibility warning.
let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?;
// retrying an error or matching the text of a compatibility warning. A TIFF never
// sets it: its layered import has no damaged-content confirmation.
let (r, damaged) = match photocraft_io::import_for_open(name, bytes, &opts) {
Ok(result) => result,
Err(photocraft_io::IoError::PsdApprovalRequired { .. }) => {
jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes), slot, order)?;
return Ok(Vec::new());
}
Err(error) => return Err(error.to_string()),
};
(r.document, r.warnings, damaged)
} else {
let (doc, warnings) = import(name, bytes, &opts)?;
@@ -99,7 +125,8 @@ impl PhotocraftApp {
path: path.map(str::to_string),
warnings: warnings.clone(),
bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())),
slot: None,
slot,
order,
question,
policy_applied: false,
},
@@ -112,13 +139,18 @@ impl PhotocraftApp {
/// Returns the import warnings (also shown to the user). Brush and gradient
/// files go to the preset libraries, as for interactive opens.
pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
self.open_automation_bytes_with_approval(name, bytes, false)
}
/// [`Self::open_automation_bytes`] with the caller's high-memory approval for the imported bytes.
pub fn open_automation_bytes_with_approval(&mut self, name: &str, bytes: &[u8], approved: bool) -> Result<Vec<String>, String> {
let events_enabled = self.session.prefs().script_events.enabled;
if events_enabled {
self.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
}
let result = match preset_files_ui::open(self, name, bytes) {
Some(r) => r.map(|()| Vec::new()),
None => self.import_automation_document(name, bytes),
None => self.import_automation_document(name, bytes, approved),
};
if events_enabled {
self.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
@@ -128,9 +160,10 @@ impl PhotocraftApp {
/// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script
/// events and no Color Settings policy (which may read user-configured profile paths).
fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
fn import_automation_document(&mut self, name: &str, bytes: &[u8], approved: bool) -> Result<Vec<String>, String> {
let import = self.services.import.as_ref().ok_or("no importer configured")?;
let opts = photocraft_engine::jobs::import_options(self.session.prefs());
let mut opts = photocraft_engine::jobs::import_options(self.session.prefs());
opts.psd_high_memory_approved = approved;
let (mut doc, warnings) = import(name, bytes, &opts)?;
photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc);
// The caller records the path it read from.
+9 -3
View File
@@ -1369,7 +1369,11 @@ fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReques
let p = &req.params;
Some(match req.method.as_str() {
"app.open" => match str_param(p, "path") {
Some(path) => app_open(app, path),
Some(path) => match p.get("approveHighMemory") {
None | Some(Value::Null) => app_open(app, path, false),
Some(Value::Bool(approved)) => app_open(app, path, *approved),
Some(_) => err("expected boolean for `approveHighMemory`"),
},
None => err("missing `path`"),
},
"app.save" => match crate::FormatChoices::from_params(p, "app.save") {
@@ -1388,7 +1392,9 @@ fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReques
})
}
fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome {
/// The `app.open` control method: opens a path through the configured automation read
/// capability, with optional high-memory approval.
fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Outcome {
if let Some(outcome) = open_pcraft_directory(app, path) {
return outcome;
}
@@ -1398,7 +1404,7 @@ fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome {
};
wrap(opened.and_then(|(name, bytes)| {
let name = app.open_name(&name);
let warnings = app.open_automation_bytes(&name, &bytes)?;
let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?;
// Brushes/gradients go to the preset libraries: no document, no Open Recent entry.
if !crate::preset_files_ui::is_preset_file(&name) {
app.opened_from(path);
+7 -1
View File
@@ -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<bool> {
let mut outcome: Option<bool> = 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<Value, String> {
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<Value, String> {
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)?;
+237 -20
View File
@@ -33,6 +33,10 @@ pub struct Held {
pub bytes: Option<Arc<Vec<u8>>>,
/// The tab position a reopened file keeps.
pub slot: Option<usize>,
/// The file's place in a set opened together, when it is one of several
/// ([`crate::jobs_ui::OpenOrder`]): kept while this file waits, so its tab still lands in the
/// set's order.
pub order: Option<crate::jobs_ui::OpenOrder>,
/// The profile question ([`photocraft_engine::color_cmds::ColorState::open_question`]), or
/// `None` to open without asking.
pub question: Option<Value>,
@@ -41,35 +45,95 @@ pub struct Held {
pub policy_applied: bool,
}
/// Dialog field for the high-memory confirmation prompt.
pub const MEMORY_FIELD: &str = "__psdMemoryOpen";
/// Item kind in the arrival-ordered open prompt queue.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PromptKind {
Memory,
Open,
}
/// An un-decoded PSD file whose preflight estimate requires user approval.
#[derive(Clone)]
pub struct MemoryPrompt {
pub id: u64,
pub name: String,
pub path: Option<String>,
pub slot: Option<usize>,
pub order: Option<crate::jobs_ui::OpenOrder>,
pub estimated: u64,
/// The capacity measured when the estimate was made; `None` when it could not be measured.
pub available: Option<u64>,
/// The engine could not measure available memory for this estimate. No number is shown.
pub capacity_unknown: bool,
/// The estimate is above the unknown-capacity warning threshold (8 GiB), so the prompt also
/// says the process or tab may run out of memory. Approval stays possible.
pub uncertain_capacity_warning: bool,
}
/// 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.
pub fn arrive(app: &mut PhotocraftApp, held: Held) {
app.held_opens.push_back(held);
app.prompt_order.push_back(PromptKind::Open);
advance(app);
}
/// Whether any open prompt (damage, profile or high-memory) is currently on screen.
pub fn has_open_dialog(app: &PhotocraftApp) -> bool {
app.ui.dialogs.iter().any(|d| owns(&d.fields) || owns_damage(&d.fields) || owns_memory(&d.fields))
}
/// Opens queued files in order until one needs its prompt, which is shown if it isn't yet.
fn advance(app: &mut PhotocraftApp) {
while let Some(front) = app.held_opens.front() {
if front.damage_pending {
if !app.ui.dialogs.iter().any(|d| owns_damage(&d.fields)) {
show_damage(app);
pub fn advance(app: &mut PhotocraftApp) {
// Reconcile legacy callers that populated held queues directly.
if app.prompt_order.is_empty() {
app.prompt_order.extend(std::iter::repeat_n(PromptKind::Open, app.held_opens.len()));
app.prompt_order.extend(std::iter::repeat_n(PromptKind::Memory, app.held_memory_prompts.len()));
}
if has_open_dialog(app) {
return;
}
loop {
match app.prompt_order.front() {
None => return,
Some(PromptKind::Memory) => {
if let Some(front) = app.held_memory_prompts.front().cloned() {
show_memory(app, &front);
return;
} else {
app.prompt_order.pop_front();
}
}
return;
}
if front.question.is_some() {
if !app.ui.dialogs.iter().any(|d| d.fields.contains_key(FIELD)) {
show(app);
Some(PromptKind::Open) => {
let Some(front) = app.held_opens.front() else {
app.prompt_order.pop_front();
continue;
};
if front.damage_pending {
show_damage(app);
return;
}
if front.question.is_some() {
show(app);
return;
}
let Some(held) = app.held_opens.pop_front() else {
app.prompt_order.pop_front();
continue;
};
app.prompt_order.pop_front();
let _ = open(app, held, None);
if has_open_dialog(app) {
return;
}
}
return;
}
if let Some(held) = app.held_opens.pop_front() {
// A failure is shown to the user (`open_failed`); the next file still opens.
let _ = open(app, held, None);
}
}
}
@@ -129,19 +193,31 @@ pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result<Value, St
return Err("answer the damaged PSD confirmation first".into());
}
let Some(action) = action else {
let dropped = app.held_opens.len();
let name = app.held_opens.front().map(|h| h.name.clone()).unwrap_or_default();
let dropped = app.held_opens.len() + app.held_memory_prompts.len();
let name = app.held_opens.front().map(|h| h.name.clone()).or_else(|| app.held_memory_prompts.front().map(|m| m.name.clone())).unwrap_or_default();
for m in app.held_memory_prompts.drain(..) {
app.session.cancel_pending_preflight(m.id);
}
app.session.clear_pending_preflights();
app.held_opens.clear();
app.prompt_order.clear();
for job in app.jobs.opens.iter().map(|o| o.job).collect::<Vec<_>>() {
app.session.cancel_job(job);
}
app.jobs.opens.clear();
app.jobs.batches.clear();
app.ui.dialogs.retain(|d| !owns(&d.fields) && !owns_damage(&d.fields) && !owns_memory(&d.fields));
app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]);
app.ui.status_error = false;
return Ok(json!({"cancelled": dropped}));
};
let Some(held) = app.held_opens.pop_front() else { return Err("no file is waiting to open".into()) };
if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Open) {
app.prompt_order.remove(pos);
}
let r = open(app, held, Some(action));
advance(app);
crate::jobs_ui::end_batch(app);
r
}
@@ -164,14 +240,19 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result<Value
!h.damage_pending && policy_key(h.doc.mode) == Some(key) && h.question.as_ref().is_some_and(|q| q.get("missing").and_then(Value::as_bool) != Some(true))
};
let Some(held) = app.held_opens.pop_front() else { return Err("no file is waiting to open".into()) };
if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Open) {
app.prompt_order.remove(pos);
}
let r = open(app, held, Some(action));
while app.held_opens.front().is_some_and(same) {
while app.prompt_order.front() == Some(&PromptKind::Open) && app.held_opens.front().is_some_and(same) {
if let Some(held) = app.held_opens.pop_front() {
app.prompt_order.pop_front();
// A failure is shown to the user (`open_failed`); the next file still opens.
let _ = open(app, held, Some(action));
}
}
advance(app);
crate::jobs_ui::end_batch(app);
r
}
@@ -225,10 +306,14 @@ pub(crate) fn answer_damage(app: &mut PhotocraftApp, accept: bool) -> Result<Val
front.damage_pending = false;
} else {
app.held_opens.pop_front();
if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Open) {
app.prompt_order.remove(pos);
}
app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]);
app.ui.status_error = false;
}
advance(app);
crate::jobs_ui::end_batch(app);
Ok(json!({"name": name, "continued": accept}))
}
@@ -238,7 +323,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
if held.damage_pending {
return Err("damaged PSD cannot be opened before confirmation".into());
}
let Held { mut doc, read_only, damage_pending: _, name, path, warnings, bytes, slot, question, policy_applied } = held;
let Held { mut doc, read_only, damage_pending: _, name, path, warnings, bytes, slot, order, question, policy_applied } = held;
let index = if question.is_some() || policy_applied {
if let Some(action) = action
&& let Err(e) = app.session.color.resolve_open(&mut doc, action)
@@ -255,6 +340,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
if let Some(st) = app.session.active_mut() {
st.source_read_only = read_only;
}
let slot = crate::jobs_ui::tab_slot(app, slot, order);
let index = match slot {
Some(slot) => app
.run("document.move", json!({"document": index, "to": slot}))
@@ -267,3 +353,134 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice))?;
Ok(json!({"document": index, "action": action}))
}
/// Queues a high-memory prompt in arrival order and shows it when it reaches the front.
#[allow(clippy::too_many_arguments)]
pub fn arrive_memory(
app: &mut PhotocraftApp,
id: u64,
name: String,
path: Option<String>,
slot: Option<usize>,
order: Option<crate::jobs_ui::OpenOrder>,
estimated: u64,
available: Option<u64>,
capacity_unknown: bool,
uncertain_capacity_warning: bool,
) {
app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning });
app.prompt_order.push_back(PromptKind::Memory);
advance_memory(app);
}
/// Whether a dialog's fields mark it as the high-memory confirmation.
pub fn owns_memory(fields: &serde_json::Map<String, Value>) -> bool {
fields.contains_key(MEMORY_FIELD)
}
/// Draws the high-memory prompt's message body from its dialog fields.
pub(crate) fn memory_body(ui: &mut egui::Ui, fields: &serde_json::Map<String, Value>) {
ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default());
}
/// Advances the shared open-prompt queue; memory prompts take their turn with damage and profile
/// prompts in arrival order.
pub fn advance_memory(app: &mut PhotocraftApp) {
advance(app);
}
/// Builds and opens the confirmation dialog for a queued high-memory preflight.
fn show_memory(app: &mut PhotocraftApp, prompt: &MemoryPrompt) {
let est_gb = prompt.estimated as f64 / (1u64 << 30) as f64;
// An unmeasured capacity is never printed as a number, even if a stale measurement is
// attached: the engine's `capacityUnknown` wins.
let available = prompt.available.filter(|_| !prompt.capacity_unknown);
let mut message = match available {
Some(a) => crate::i18n::fmt(
tl!("Opening “{name}” requires an estimated {est} GiB of memory ({avail} GiB available)."),
&[("name", &prompt.name), ("est", &format!("{est_gb:.1}")), ("avail", &format!("{:.1}", a as f64 / (1u64 << 30) as f64))],
),
None => crate::i18n::fmt(
tl!("Opening “{name}” requires an estimated {est} GiB of memory. The available memory could not be measured."),
&[("name", &prompt.name), ("est", &format!("{est_gb:.1}"))],
),
};
message.push_str("\n\n");
message.push_str(tl!("Opening this document uses more memory and may slow down your computer or other running applications."));
if prompt.uncertain_capacity_warning {
message.push_str("\n\n");
message.push_str(tl!(
"The estimate is above 8 GiB and the available memory is unknown, so this process or browser tab may run out of memory. You can still try to open it."
));
}
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!(available)),
("capacityUnknown".into(), json!(prompt.capacity_unknown)),
("uncertainCapacityWarning".into(), json!(prompt.uncertain_capacity_warning)),
]
.into_iter()
.collect();
app.ui.open_dialog(crate::state::DialogKind::Command, fields);
}
/// Answers the front high-memory prompt: accepts and starts the approved open, or declines and
/// advances the queue. The engine command revalidates the source identity and the hard limit.
pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result<Value, String> {
let Some(front) = app.held_memory_prompts.pop_front() else {
advance(app);
return Err("no high-memory PSD is waiting for confirmation".into());
};
if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Memory) {
app.prompt_order.remove(pos);
}
let id = front.id;
let name = front.name.clone();
let path = front.path.clone();
let slot = front.slot;
let order = front.order;
let res = app.run("file.approveMemory", json!({"id": id, "approve": accept, "background": app.background_jobs})).map_err(|e| format!("{}: {e}", name));
match res {
Ok(r) => {
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, slot, 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 if let Some(result) = r.get("result") {
let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(0), name: name.clone(), path: path.clone(), slot, order };
if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) {
app.ui.status = e;
app.ui.status_error = true;
}
}
} else {
app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]);
app.ui.status_error = false;
crate::jobs_ui::end_batch(app);
}
advance(app);
crate::jobs_ui::end_batch(app);
Ok(r)
}
Err(err) => {
app.ui.status = err.clone();
app.ui.status_error = true;
crate::jobs_ui::end_batch(app);
advance(app);
crate::jobs_ui::end_batch(app);
Err(err)
}
}
}
+58 -26
View File
@@ -93,16 +93,27 @@ impl PhotocraftApp {
/// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import
/// warnings (also shown to the user).
pub fn open_file(&mut self, path: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
self.open_file_placed(path, bytes, None, None)
}
/// [`Self::open_file`] for a file dropped on a tab slot or opened as one of a set.
pub(crate) fn open_file_placed(
&mut self,
path: &str,
bytes: &[u8],
slot: Option<usize>,
order: Option<crate::jobs_ui::OpenOrder>,
) -> Result<Vec<String>, String> {
// Brushes/gradients go to the preset libraries (no document, no Open Recent entry).
if let Some(r) = crate::preset_files_ui::open(self, path, bytes) {
return r.map(|()| Vec::new());
}
if self.background_jobs {
// The path and Open Recent are recorded when the background open finishes.
crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), crate::jobs_ui::bytes(bytes))?;
crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), crate::jobs_ui::bytes(bytes), slot, order)?;
return Ok(Vec::new());
}
self.open_bytes_from(&display_name(path), bytes, Some(path))
self.open_bytes_placed(&display_name(path), bytes, Some(path), slot, order)
}
/// Record that the active document was just opened from `path`: File › Save writes back to it
@@ -131,6 +142,13 @@ impl PhotocraftApp {
/// Read and open the file at `path` (see [`open_file`](Self::open_file)).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path(&mut self, path: &str) -> Result<Vec<String>, String> {
self.open_path_placed(path, None, None)
}
/// [`Self::open_path`] for a file dropped on a tab slot or opened as one of a set: the slot
/// and order survive an inline memory/profile prompt and the document's final placement.
#[cfg(not(target_arch = "wasm32"))]
fn open_path_placed(&mut self, path: &str, slot: Option<usize>, order: Option<crate::jobs_ui::OpenOrder>) -> Result<Vec<String>, String> {
if self.show_if_open(path) {
return Ok(Vec::new());
}
@@ -138,11 +156,18 @@ impl PhotocraftApp {
// would block the window). Preset files (brushes, gradients) go the usual way.
let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
if self.background_jobs && !crate::preset_files_ui::PRESET_EXTS.contains(&ext.as_str()) {
crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), photocraft_engine::jobs::OpenSource::Path(path.to_string()))?;
crate::jobs_ui::start_open(
self,
&display_name(path),
Some(path.to_string()),
photocraft_engine::jobs::OpenSource::Path(path.to_string()),
slot,
order,
)?;
return Ok(Vec::new());
}
let bytes = photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| format!("{path}: {e}"))?;
self.open_file(path, &bytes)
self.open_file_placed(path, &bytes, slot, order)
}
#[cfg(target_arch = "wasm32")]
@@ -150,6 +175,12 @@ impl PhotocraftApp {
Err(format!("cannot open paths on the web: {path}"))
}
/// The web has no filesystem paths: a drop read by the shell arrives as bytes.
#[cfg(target_arch = "wasm32")]
fn open_path_placed(&mut self, path: &str, _slot: Option<usize>, _order: Option<crate::jobs_ui::OpenOrder>) -> Result<Vec<String>, String> {
Err(format!("cannot open paths on the web: {path}"))
}
/// Open several files, reporting each failure to the user instead of stopping. Relative paths
/// are resolved against the working directory so the remembered path stays valid. The files
/// open in name order ([`natural_cmp`]: `File_2` before `File_10`), and their tabs keep that
@@ -168,21 +199,14 @@ impl PhotocraftApp {
continue;
}
let order = crate::jobs_ui::OpenOrder { batch, seq };
let pending = self.jobs.opens.len();
match self.open_path(abs) {
Ok(_) => {
opened += 1;
// A background open's tab takes its place when it finishes; a document opened
// at once is in place now.
match self.jobs.opens.get_mut(pending) {
Some(tab) => tab.order = Some(order),
None => crate::jobs_ui::opened_in_order(&mut self.jobs, order),
}
}
// The order travels with the open: a background tab, an inline document, or a memory
// prompt that is answered later all place the file at its place in the set.
match self.open_path_placed(abs, None, Some(order)) {
Ok(_) => opened += 1,
Err(e) => self.open_failed(&display_name(abs), &e),
}
}
crate::jobs_ui::end_batch(&mut self.jobs);
crate::jobs_ui::end_batch(self);
opened
}
@@ -198,6 +222,13 @@ impl PhotocraftApp {
} else if let Some(o) = self.jobs.opens.iter().find(|o| o.path.as_deref().is_some_and(|p| !is_template(p) && same(p))) {
// A template still loading opens as another Untitled, as it does once loaded.
self.jobs.focus = Some(o.job);
} else if self.held_memory_prompts.iter().any(|m| m.path.as_deref().is_some_and(|p| !is_template(p) && same(p))) {
// The file's high-memory prompt is already waiting: show it, don't queue a second
// prompt and a second open for the same file. A template still opens again as
// another Untitled, like one that is still loading.
crate::open_prompt::advance_memory(self);
self.ui.chrome.home = None;
return true;
} else {
return false;
}
@@ -282,22 +313,23 @@ impl PhotocraftApp {
DropTarget::Elsewhere
}
/// Open one dropped file; with `slot`, its tab goes there (when it finishes opening, for
/// background opens). True when it took the slot.
/// Open one dropped file; with `slot`, its tab goes there (at once, or when a held prompt is
/// answered). True when it took the slot.
fn open_dropped_file(&mut self, f: &egui::DroppedFileHandle, name: &str, slot: Option<usize>) -> Result<bool, String> {
// Opens append: a background open's tab, or a document.
let (docs, opens) = (self.session.documents().len(), self.jobs.opens.len());
let held = self.held_opens.len() + self.held_memory_prompts.len();
// The slot travels with the open through the inline document, a background tab and a
// memory/profile prompt, so no separate move here can land on another document.
if f.path().is_absolute() {
self.open_path(&path_text(f.path(), false)?)?;
self.open_path_placed(&path_text(f.path(), false)?, slot, None)?;
} else {
self.open_bytes(name, &crate::read_dropped(&**f)?)?;
self.open_bytes_placed(name, &crate::read_dropped(&**f)?, None, slot, None)?;
}
let Some(slot) = slot else { return Ok(false) };
if let Some(tab) = self.jobs.opens.get_mut(opens) {
tab.slot = Some(slot);
return Ok(true);
if slot.is_none() {
return Ok(false);
}
Ok(self.run("document.move", serde_json::json!({"document": docs, "to": slot})).is_ok())
let took = self.jobs.opens.len() > opens || self.session.documents().len() > docs || self.held_opens.len() + self.held_memory_prompts.len() > held;
Ok(took)
}
/// Place the next file dropped on the canvas and start Free Transform on it, once no other
+1 -1
View File
@@ -885,7 +885,7 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() {
let index = app.session.add_document(Document::new("f1.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None);
assert_eq!(index, 1);
jobs_ui::opened_in_order(&mut app.jobs, OpenOrder { batch, seq: 1 });
jobs_ui::end_batch(&mut app.jobs);
jobs_ui::end_batch(&mut app);
assert_eq!(app.jobs.batches.len(), 1, "kept while members are opening");
// The rest finish out of order: last, first, third.
for seq in [3usize, 0, 2] {
+63 -18
View File
@@ -197,14 +197,24 @@ pub fn run(app: &mut PhotocraftApp, id: &str, params: Value) -> Result<Value, St
}
/// Open a file in the background: a tab appears at once and shows the progress; the document
/// replaces it when decoded. `path` is remembered for File › Save and Open Recent.
pub fn start_open(app: &mut PhotocraftApp, name: &str, path: Option<String>, source: OpenSource) -> Result<(), String> {
/// replaces it when decoded. `path` is remembered for File › Save and Open Recent. `slot` (a file
/// dropped on the tabs) and `order` (its place in a set opened together) survive an inline
/// completion, a memory prompt and the open itself, so the tab lands where it belongs either way.
pub fn start_open(
app: &mut PhotocraftApp,
name: &str,
path: Option<String>,
source: OpenSource,
slot: Option<usize>,
order: Option<OpenOrder>,
) -> Result<(), String> {
let name = &app.open_name(name);
match app.session.start_open_for_user(name, source).map_err(|e| e.to_string())? {
// Inline (wasm): finish now, like a background open that ended at once.
Started::Done(v) => finish_open(app, name, path.as_deref(), &v, None),
match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? {
// Inline (wasm, or background jobs off): finish now, like a background open that ended at
// once. A preflight keeps the slot and set order in its memory prompt.
Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order),
Started::Job(job) => {
app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot: None, order: None });
app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot, order });
app.jobs.focus = Some(job);
app.ui.chrome.home = None;
app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", name)]);
@@ -226,16 +236,20 @@ pub(crate) fn begin_batch(app: &mut PhotocraftApp) -> u64 {
/// A member of a set opened at once (not in the background): its document is in place at the
/// end, so later members go after it.
#[cfg(test)]
pub(crate) fn opened_in_order(jobs: &mut JobsUi, order: OpenOrder) {
if let Some(batch) = jobs.batches.iter_mut().find(|b| b.id == order.batch) {
batch.opened.push(order.seq);
}
}
/// Every member of the set has been started: forget it unless some are still opening.
pub(crate) fn end_batch(jobs: &mut JobsUi) {
let opens = &jobs.opens;
jobs.batches.retain(|b| opens.iter().any(|o| o.order.is_some_and(|x| x.batch == b.id)));
/// Every member of the set has been started: forget it unless some are still opening, waiting on
/// their prompt (memory, profile or damage), or waiting for a prompt to clear.
pub(crate) fn end_batch(app: &mut PhotocraftApp) {
let waiting: Vec<u64> =
app.held_memory_prompts.iter().filter_map(|m| m.order.map(|o| o.batch)).chain(app.held_opens.iter().filter_map(|h| h.order.map(|o| o.batch))).collect();
let JobsUi { opens, batches, .. } = &mut app.jobs;
batches.retain(|b| opens.iter().any(|o| o.order.is_some_and(|x| x.batch == b.id)) || waiting.contains(&b.id));
}
/// The tab position for a member of a set that just opened: after the members before it that
@@ -247,12 +261,19 @@ fn batch_slot(jobs: &mut JobsUi, order: OpenOrder) -> Option<usize> {
Some(slot)
}
/// Where a finished open puts its tab: an explicit slot (a file dropped on the tabs) wins;
/// otherwise its place in a set opened together, if that set is still tracked.
pub(crate) fn tab_slot(app: &mut PhotocraftApp, slot: Option<usize>, order: Option<OpenOrder>) -> Option<usize> {
let in_set = order.and_then(|o| batch_slot(&mut app.jobs, o));
slot.or(in_set)
}
/// 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.
/// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. A memory
/// preflight keeps both in its prompt.
pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> {
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);
let r = finish_open(app, &tab.name, tab.path.as_deref(), v, tab.slot, tab.order);
end_batch(app);
r
}
@@ -447,6 +468,8 @@ pub fn cancel(app: &mut PhotocraftApp, id: JobId) -> bool {
cancelled
}
/// Handles one finished job: optional completion beep, waiting control replies, and the
/// command-specific open, save, transform and recovery paths.
fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {
// Preferences ▸ General ▸ Beep When Done (off by default): a finished operation beeps, like
// Photoshop's cue. Cancelling is the user's own action and stays silent.
@@ -507,7 +530,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {
app.ui.status_error = false;
}
}
end_batch(&mut app.jobs);
end_batch(app);
return;
}
match e.outcome {
@@ -546,8 +569,29 @@ 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<usize>) -> Result<(), String> {
/// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position
/// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final
/// document, so an inline completion lands where a background tab would.
fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option<usize>, order: Option<OpenOrder>) -> 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);
let capacity_unknown = v.get("capacityUnknown").and_then(Value::as_bool).unwrap_or(available.is_none());
let uncertain_capacity_warning = v.get("uncertainCapacityWarning").and_then(Value::as_bool).unwrap_or(false);
crate::open_prompt::arrive_memory(
app,
preflight_id,
name.to_string(),
path.map(str::to_string),
slot,
order,
estimated,
available,
capacity_unknown,
uncertain_capacity_warning,
);
return Ok(());
}
let warnings: Vec<String> =
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 {
@@ -559,6 +603,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
warnings: warnings.clone(),
bytes: None,
slot,
order,
question,
policy_applied,
};
@@ -581,7 +626,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
crate::open_prompt::arrive(app, held(doc, read_only, None, true));
return Ok(());
}
if let Some(slot) = slot {
if let Some(slot) = tab_slot(app, slot, order) {
let _ = app.run("document.move", json!({"document": index, "to": slot}));
}
after_open(app, document, name, path, &warnings, None)
+8 -8
View File
@@ -940,7 +940,7 @@ fn background_open_warns_about_missing_fonts() {
// What the open job leaves behind: the decoded document in the session, then its result.
let (index, _) = app.session.open_document(doc, None);
let id = app.session.documents()[index].doc.id;
super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None).unwrap();
super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap();
let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()];
assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices);
}
@@ -1022,7 +1022,7 @@ fn open_identity_survives_tab_reordering() {
let old_index = result["document"].as_u64().unwrap() as usize;
app.session.move_document(old_index, 0).unwrap();
assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id);
super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None).unwrap();
super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None, None).unwrap();
control.assert_untouched(&app);
assert_eq!(app.session.active().unwrap().doc.id, imported);
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png"));
@@ -1037,7 +1037,7 @@ fn open_identity_survives_an_earlier_tab_closing() {
let (result, imported) = identified_result(&app, result);
app.session.close(1).unwrap();
app.session.set_active(0);
super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0)).unwrap();
super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0), None).unwrap();
control.assert_untouched(&app);
assert_eq!(app.session.active().unwrap().doc.id, imported);
assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document");
@@ -1059,13 +1059,13 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() {
}
Some(value) => result["docId"] = value,
}
assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0)).is_err(), "invalid identity was accepted: {result}");
assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0), None).is_err(), "invalid identity was accepted: {result}");
control.assert_untouched(&app);
assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
assert_eq!(app.session.documents().len(), 1);
result["docId"] = json!(imported.0);
assert!(
super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None).is_err(),
super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None, None).is_err(),
"a closed identity must not fall back to the old tab index"
);
control.assert_untouched(&app);
@@ -1086,9 +1086,9 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() {
let (second, second_id) = identified_result(&app, second);
// All engine applies have finished. Handling the first ordinary result removes its tab,
// shifting the second result before its UI callback runs.
super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None).unwrap();
super::finish_open(&mut app, "first.png", Some("first.png"), &first, None).unwrap();
super::finish_open(&mut app, "second.png", Some("second.png"), &second, None).unwrap();
super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None, None).unwrap();
super::finish_open(&mut app, "first.png", Some("first.png"), &first, None, None).unwrap();
super::finish_open(&mut app, "second.png", Some("second.png"), &second, None, None).unwrap();
assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::<Vec<_>>(), ["profile.png", "first.png", "second.png"]);
assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::<Vec<_>>(), [first_id, second_id]);
assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt");
+3
View File
@@ -691,6 +691,9 @@ 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<open_prompt::Held>,
/// PSD files whose memory preflight requires user approval before pixel decoding (see `open_prompt`).
pub(crate) held_memory_prompts: std::collections::VecDeque<open_prompt::MemoryPrompt>,
pub(crate) prompt_order: std::collections::VecDeque<open_prompt::PromptKind>,
/// A brush or gradient file waiting on the group-name prompt (see `preset_group_prompt`).
pub(crate) held_preset_import: Option<preset_group_prompt::Held>,
/// Set once the user has agreed to quit, so the resulting close request goes through.
+756
View File
@@ -197,3 +197,759 @@ 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;
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,
})
.unwrap();
crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false);
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;
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");
assert!(app.held_memory_prompts.is_empty());
assert!(app.prompt_order.is_empty());
}
/// #10897: the inline path (the browser shell and any desktop open with background jobs off)
/// routes the memory prompt's answer through `file.approveMemory`, and the retry only opens the
/// file when it carries the one-shot approval. A tiny fixture under a scoped estimate charge
/// reaches the real approval window, so dropping the approval flag or the bound estimate in the
/// retry leaves the prompt (and no document) instead of passing silently.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn memory_confirmation_resume_inline_success() {
if cfg!(target_pointer_width = "32") {
return; // the 3 GiB charge would exceed a 32-bit process cap
}
let gb = 1u64 << 30;
let mut app = app();
app.background_jobs = false;
let psd = recovery_psd::make_psd(false);
// Known 5 GiB: S = 2.5 GiB, H = 3.75 GiB. The 3 GiB charge lands in (S, H] on this thread.
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None };
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
photocraft_io::memory::with_mock_memory(snap, || {
// The real inline import raises the preflight: no fabricated prompt or preflight.
app.open_bytes_from("inline_resume.psd", &psd, Some("/test/inline_resume.psd")).unwrap();
assert!(app.session.documents().is_empty(), "the file waits for approval");
assert_eq!(app.held_memory_prompts.len(), 1);
assert_eq!(app.ui.dialogs.len(), 1);
let fields = &app.ui.dialogs[0].fields;
assert!(crate::open_prompt::owns_memory(fields));
assert!(fields["estimated"].as_u64().unwrap() > 3 * gb, "the charged estimate is shown: {fields:?}");
assert_eq!(fields["available"], json!(5 * gb));
assert_eq!(fields["capacityUnknown"], json!(false));
assert_eq!(fields["uncertainCapacityWarning"], json!(false));
let dlg_id = app.ui.dialogs[0].id;
let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id}));
assert_eq!(res["ok"], true, "{res}");
assert!(app.ui.dialogs.is_empty(), "dialog dismissed after inline resume");
assert_eq!(app.session.documents().len(), 1, "document opened via inline resume");
assert_eq!(app.session.documents()[0].doc.name, "inline_resume.psd");
assert_eq!(app.session.documents()[0].path.as_deref(), Some("/test/inline_resume.psd"));
assert!(app.held_memory_prompts.is_empty());
assert!(app.held_opens.is_empty());
assert!(app.prompt_order.is_empty());
assert!(app.jobs.opens.is_empty());
assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0, "the approval consumed and released the preflight");
});
});
}
/// #10897: a background open carries the same scoped estimate into its worker through the
/// explicitly captured test scope (never a global mock), so the real job raises the approval
/// prompt; the retry then opens the file only with the one-shot approval.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn memory_confirmation_resume_background_success() {
if cfg!(target_pointer_width = "32") {
return; // the 3 GiB charge would exceed a 32-bit process cap
}
let gb = 1u64 << 30;
let mut app = app();
app.background_jobs = true;
let psd = recovery_psd::make_psd(false);
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None };
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
photocraft_io::memory::with_mock_memory(snap, || {
app.open_bytes_from("bg_resume.psd", &psd, Some("/test/bg_resume.psd")).unwrap();
assert_eq!(app.jobs.opens.len(), 1, "a background open tab appears at once");
let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect();
for id in jobs {
app.session.wait_job(id).unwrap();
}
crate::jobs_ui::tick(&mut app, &egui::Context::default());
assert!(app.session.documents().is_empty(), "the file waits for approval");
assert_eq!(app.held_memory_prompts.len(), 1);
assert_eq!(app.ui.dialogs.len(), 1);
let fields = &app.ui.dialogs[0].fields;
assert!(crate::open_prompt::owns_memory(fields));
assert!(fields["estimated"].as_u64().unwrap() > 3 * gb, "the worker made the charged estimate: {fields:?}");
assert_eq!(fields["available"], json!(5 * gb));
assert_eq!(fields["capacityUnknown"], json!(false));
let dlg_id = app.ui.dialogs[0].id;
let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id}));
assert_eq!(res["ok"], true, "{res}");
assert_eq!(app.jobs.opens.len(), 1, "background retry job registered in jobs.opens");
let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect();
for id in jobs {
app.session.wait_job(id).unwrap();
}
crate::jobs_ui::tick(&mut app, &egui::Context::default());
assert_eq!(app.session.documents().len(), 1, "document opened via background resume");
assert_eq!(app.session.documents()[0].doc.name, "bg_resume.psd");
assert_eq!(app.session.documents()[0].path.as_deref(), Some("/test/bg_resume.psd"));
assert!(app.ui.dialogs.is_empty());
assert!(app.held_memory_prompts.is_empty());
assert!(app.held_opens.is_empty());
assert!(app.prompt_order.is_empty());
assert!(app.jobs.opens.is_empty());
assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0);
});
});
}
#[test]
fn memory_confirmation_refuses_when_source_changed_inline() {
let mut app = app();
app.background_jobs = false;
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("changed.psd");
std::fs::write(&path, b"initial file contents").unwrap();
let src = photocraft_engine::jobs::OpenSource::Path(path.to_string_lossy().to_string());
let fp = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap();
let preflight_id = app
.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: "changed.psd".into(),
source: src,
fingerprint: fp,
required: 1000,
soft_limit: 500,
hard_limit: 50_000,
available_ram: Some(100_000),
confirm_damage: true,
})
.unwrap();
crate::open_prompt::arrive_memory(
&mut app,
preflight_id,
"changed.psd".into(),
Some(path.to_string_lossy().to_string()),
None,
None,
1000,
Some(100_000),
false,
false,
);
assert_eq!(app.ui.dialogs.len(), 1);
let dlg_id = app.ui.dialogs[0].id;
// Mutate file before confirming:
std::fs::write(&path, b"modified file contents longer").unwrap();
let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id}));
assert_eq!(res["ok"], false, "confirming changed file inline must fail");
let error = res["error"].as_str().unwrap_or_default();
assert!(error.contains("changed since it was checked"), "the refusal names the changed identity, not a parser failure: {res}");
assert!(app.session.documents().is_empty());
assert!(app.held_memory_prompts.is_empty());
}
#[test]
fn memory_confirmation_refuses_when_source_changed_async() {
let mut app = app();
app.background_jobs = true;
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("changed_async.psd");
std::fs::write(&path, b"initial file contents").unwrap();
let src = photocraft_engine::jobs::OpenSource::Path(path.to_string_lossy().to_string());
let fp = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap();
let preflight_id = app
.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: "changed_async.psd".into(),
source: src,
fingerprint: fp,
required: 1000,
soft_limit: 500,
hard_limit: 50_000,
available_ram: Some(100_000),
confirm_damage: true,
})
.unwrap();
crate::open_prompt::arrive_memory(
&mut app,
preflight_id,
"changed_async.psd".into(),
Some(path.to_string_lossy().to_string()),
None,
None,
1000,
Some(100_000),
false,
false,
);
assert_eq!(app.ui.dialogs.len(), 1);
let dlg_id = app.ui.dialogs[0].id;
// Mutate file before confirming:
std::fs::write(&path, b"modified file contents longer").unwrap();
let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id}));
assert_eq!(res["ok"], true, "confirmation kicks off background job");
assert_eq!(app.jobs.opens.len(), 1);
// Run the job to completion and observe async failure:
let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect();
for id in jobs {
let _ = app.session.wait_job(id);
}
crate::jobs_ui::tick(&mut app, &egui::Context::default());
assert!(app.session.documents().is_empty(), "no document opened on changed file failure");
assert!(app.jobs.opens.is_empty(), "opens cleared on job failure");
assert!(app.ui.status_error, "error recorded in UI status");
assert!(app.ui.status.contains("changed since it was checked"), "the background refusal names the changed identity: {}", app.ui.status);
}
#[test]
fn memory_decline_advances_queue_and_cleans_batch() {
let mut app = app();
let batch_id = crate::jobs_ui::begin_batch(&mut app);
let order = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 0 };
let preflight_id = app
.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: "declined.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: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.unwrap();
crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000), false, false);
assert_eq!(app.ui.dialogs.len(), 1);
let dlg_id = app.ui.dialogs[0].id;
let res = call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}));
assert_eq!(res["ok"], true);
assert!(app.ui.dialogs.is_empty());
assert!(app.session.take_pending_preflight(preflight_id).is_none());
assert!(app.jobs.batches.is_empty(), "batch cleaned up on decline");
assert!(app.prompt_order.is_empty());
}
#[test]
fn batch_single_file_cancel_preserves_other_held_memory_orders() {
let mut app = app();
let batch_id = crate::jobs_ui::begin_batch(&mut app);
let order0 = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 0 };
let order1 = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 1 };
let p0 = app
.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: "first.psd".into(),
source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])),
fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]))).unwrap(),
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.unwrap();
let p1 = app
.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: "second.psd".into(),
source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])),
fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]))).unwrap(),
required: 1000,
soft_limit: 500,
hard_limit: 2000,
available_ram: Some(4000),
confirm_damage: true,
})
.unwrap();
crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000), false, false);
crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000), false, false);
// Cancel first file:
let dlg0 = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg0}))["ok"], true);
// Batch must be preserved because second file is still waiting:
assert_eq!(app.jobs.batches.len(), 1, "batch preserved while second file is waiting");
assert_eq!(app.held_memory_prompts.len(), 1);
// Now cancel second file:
let dlg1 = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg1}))["ok"], true);
assert!(app.jobs.batches.is_empty(), "batch cleaned after all members cancelled");
assert!(app.prompt_order.is_empty());
}
#[test]
fn profile_cancel_cancels_whole_queue_including_memory_prompts() {
let mut app = app();
let gb = 1u64 << 30;
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,
})
.unwrap();
crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false);
crate::open_prompt::arrive(
&mut app,
crate::open_prompt::Held {
doc: photocraft_doc::Document::new("test", photocraft_geom::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8),
read_only: false,
damage_pending: false,
name: "profile.psd".into(),
path: None,
warnings: vec![],
bytes: None,
slot: None,
order: None,
question: Some(json!({"missing": false, "working": "sRGB", "embedded": "Adobe RGB"})),
policy_applied: false,
},
);
let r = crate::open_prompt::answer(&mut app, None).unwrap();
assert_eq!(r["cancelled"], 2, "both held open and memory prompt dropped");
assert!(app.held_opens.is_empty());
assert!(app.held_memory_prompts.is_empty());
assert!(app.prompt_order.is_empty());
assert!(app.session.take_pending_preflight(preflight_id).is_none(), "pending preflight cancelled");
}
#[test]
fn mixed_prompts_follow_arrival_order_fifo() {
let mut app = app();
let gb = 1u64 << 30;
// 1. Arrive damage prompt first
crate::open_prompt::arrive(
&mut app,
crate::open_prompt::Held {
doc: photocraft_doc::Document::new("test", photocraft_geom::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8),
read_only: false,
damage_pending: true,
name: "first_damage.psd".into(),
path: None,
warnings: vec!["damaged data".into()],
bytes: None,
slot: None,
order: None,
question: None,
policy_applied: false,
},
);
// 2. Arrive memory prompt second
let preflight_id = app
.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: "second_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,
})
.unwrap();
crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false);
// First prompt shown must be damage (since it arrived first)!
assert_eq!(app.ui.dialogs.len(), 1);
assert!(crate::open_prompt::owns_damage(&app.ui.dialogs[0].fields));
// Cancel damage prompt:
let dlg_id = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true);
// Now memory prompt must be shown!
assert_eq!(app.ui.dialogs.len(), 1);
assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields));
let dlg_mem = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_mem}))["ok"], true);
assert!(app.ui.dialogs.is_empty());
}
/// A stored preflight for the prompt tests, with a tiny in-memory source so nothing large is
/// ever held.
fn store_preflight(app: &mut PhotocraftApp, name: &str, required: u64, available: Option<u64>) -> u64 {
let bytes = std::sync::Arc::new(vec![0u8; 16]);
let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::clone(&bytes));
let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap();
app.session
.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight {
id: 0,
name: name.into(),
source,
fingerprint,
required,
soft_limit: required / 2,
hard_limit: required.saturating_mul(2),
available_ram: available,
confirm_damage: true,
})
.unwrap()
}
/// #10897: the browser and desktop share one consent route. The web shell runs every open inline
/// (`background_jobs == false`), answers the same `MemoryPrompt`, and dispatches the same
/// `file.approveMemory` command: it is not menu-only, journaled or gated off wasm. The web's own
/// allowance and 2 GiB product cap stay in `photocraft-io`'s policy, so approval never raises
/// them. This checks the routing half on the host; the web policy half is covered by
/// `photocraft_io::memory`'s web-policy tests.
#[test]
fn memory_approval_routes_through_the_file_approve_memory_command() {
let app = app();
assert!(!app.background_jobs, "the browser shell is always inline");
assert!(app.session.is_enabled("file.approveMemory"), "the one-shot approval command is available on every target");
let spec = photocraft_engine::commands::find("file.approveMemory").expect("registered");
assert!(spec.menu.is_empty(), "it is not a menu item");
assert!(!spec.journal, "a one-shot permission is never journaled or replayed");
}
/// #10897: on the web the same prompt offers consent, and `file.approveMemory` may authorize an
/// estimate above the 1 GiB automatic allowance only within the 2 GiB product cap: a 1.5 GiB
/// estimate is approved and opens, a 3 GiB estimate is refused before decoding. The fixed mock
/// snapshot is ignored on wasm (the web policy does not read one), so the charge alone sets the
/// window. This target is compile-checked, not executed, by the current CI (`cargo xtask wasm`
/// checks the crates without test targets); the same web policy is exercised on native by
/// `photocraft_io::memory`'s web-policy tests.
#[cfg(target_arch = "wasm32")]
#[test]
fn web_memory_prompt_offers_consent_within_the_two_gib_product_cap() {
let gb = 1u64 << 30;
let psd = recovery_psd::make_psd(false);
let mut approved = app();
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb / 2, || {
approved.open_bytes_from("web.psd", &psd, Some("web.psd")).unwrap();
assert_eq!(approved.held_memory_prompts.len(), 1, "1.5 GiB is above the web's 1 GiB automatic allowance");
let fields = &approved.ui.dialogs[0].fields;
assert_eq!(fields["available"], json!(null));
assert_eq!(fields["capacityUnknown"], json!(true), "the browser cannot measure the tab's capacity");
let dlg = approved.ui.dialogs[0].id;
assert_eq!(call(&mut approved, "ui.dialog.confirm", json!({"dialog": dlg}))["ok"], true);
assert_eq!(approved.session.documents().len(), 1, "consent opens an estimate within the product cap");
});
let mut refused = app();
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
assert!(refused.open_bytes_from("too-big.psd", &psd, Some("too-big.psd")).is_err(), "consent cannot raise the 2 GiB product cap");
assert!(refused.ui.dialogs.is_empty());
assert!(refused.session.documents().is_empty());
});
}
/// #10897: the prompt shows an unmeasured capacity honestly (no invented number) and adds the
/// above-8-GiB warning, both from the engine's typed flags, so the browser and desktop consent
/// text matches what was actually measured.
#[test]
fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() {
let gb = 1u64 << 30;
let mut app = app();
let id = store_preflight(&mut app, "unknown.psd", 9 * gb, None);
let tab = crate::jobs_ui::OpenTab {
job: photocraft_engine::jobs::JobId(1),
name: "unknown.psd".into(),
path: Some("/pics/unknown.psd".into()),
slot: None,
order: None,
};
crate::jobs_ui::finish_open_tab(
&mut app,
&tab,
&json!({"pendingPreflight": id, "estimated": 9 * gb, "availableRam": null, "capacityUnknown": true, "uncertainCapacityWarning": true}),
)
.unwrap();
assert_eq!(app.ui.dialogs.len(), 1);
let fields = &app.ui.dialogs[0].fields;
assert!(crate::open_prompt::owns_memory(fields));
assert_eq!(fields["available"], json!(null), "no number is invented for an unmeasured capacity");
assert_eq!(fields["capacityUnknown"], json!(true));
assert_eq!(fields["uncertainCapacityWarning"], json!(true));
let message = fields["message"].as_str().unwrap();
assert!(message.contains("could not be measured"), "{message}");
assert!(message.contains("8 GiB") && message.contains("may run out of memory"), "{message}");
assert!(!message.contains("available)"), "the unknown-capacity message claims no available figure: {message}");
let dialog = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true);
// A measured capacity shows the number and drops the uncertainty warning.
let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb));
let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, slot: None, order: None };
crate::jobs_ui::finish_open_tab(
&mut app,
&tab,
&json!({"pendingPreflight": id, "estimated": 3 * gb, "availableRam": 5 * gb, "capacityUnknown": false, "uncertainCapacityWarning": false}),
)
.unwrap();
let fields = &app.ui.dialogs[0].fields;
assert_eq!(fields["available"], json!(5 * gb));
assert_eq!(fields["capacityUnknown"], json!(false));
let message = fields["message"].as_str().unwrap();
assert!(message.contains("5.0 GiB available"), "{message}");
assert!(!message.contains("could not be measured") && !message.contains("may run out of memory"), "{message}");
let dialog = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true);
assert!(app.ui.dialogs.is_empty());
}
/// #10897: reopening an ordinary file whose high-memory prompt is already waiting shows that
/// prompt instead of queueing a second one and a second open; a template still opens again as
/// another Untitled, like one that is still loading.
#[test]
fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() {
let gb = 1u64 << 30;
let mut app = app();
let id = store_preflight(&mut app, "slow.psd", 3 * gb, Some(5 * gb));
crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, 3 * gb, Some(5 * gb), false, false);
assert_eq!(app.held_memory_prompts.len(), 1);
assert_eq!(app.ui.dialogs.len(), 1);
assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown");
assert_eq!(app.held_memory_prompts.len(), 1, "no second prompt for the same file");
assert_eq!(app.ui.dialogs.len(), 1);
// The template exception: a repeat open still creates another Untitled.
let id = store_preflight(&mut app, "card.psdt", 3 * gb, Some(5 * gb));
crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, 3 * gb, Some(5 * gb), false, false);
assert_eq!(app.held_memory_prompts.len(), 2);
assert!(!app.show_if_open("/pics/card.psdt"), "a template reopens instead of reusing the waiting prompt");
assert_eq!(app.held_memory_prompts.len(), 2);
}
/// A tiny PNG so a set can hold one PSD that needs approval and one flat file that opens at once.
#[cfg(not(target_arch = "wasm32"))]
fn png_file() -> Vec<u8> {
let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![10; 2 * 2 * 3]).unwrap();
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()
}
/// #10897: a set opened inline keeps the charged PSD's place in the set through its memory
/// prompt: the prompt carries the batch order and the answered file lands before the later member.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn inline_set_keeps_the_memory_prompted_file_in_batch_order() {
if cfg!(target_pointer_width = "32") {
return; // the 3 GiB charge would exceed a 32-bit process cap
}
let gb = 1u64 << 30;
let dir = tempfile::tempdir().unwrap();
let psd = dir.path().join("a_high.psd");
let png = dir.path().join("b_flat.png");
std::fs::write(&psd, recovery_psd::make_psd(false)).unwrap();
std::fs::write(&png, png_file()).unwrap();
let paths = vec![psd.to_string_lossy().into_owned(), png.to_string_lossy().into_owned()];
let mut app = app();
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None };
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
photocraft_io::memory::with_mock_memory(snap, || {
assert_eq!(app.open_paths(&paths), 2);
assert_eq!(app.held_memory_prompts.len(), 1, "the charged PSD waits for approval");
assert_eq!(app.held_memory_prompts.front().unwrap().order.map(|o| o.seq), Some(0), "the set order travels with the prompt");
// The flat file waits behind the prompt, keeping its own place in the set.
assert_eq!(app.held_opens.len(), 1);
assert_eq!(app.held_opens.front().unwrap().order.map(|o| o.seq), Some(1));
let dlg = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg}))["ok"], true);
let names: Vec<_> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
assert_eq!(names, ["a_high.psd", "b_flat.png"]);
assert!(app.held_memory_prompts.is_empty() && app.held_opens.is_empty());
assert!(app.jobs.batches.is_empty(), "the set is forgotten once every member opened");
assert!(app.prompt_order.is_empty());
});
});
}
/// A real tiny layered TIFF: a small two-layer RGB document exported with Photoshop layer data.
/// The fixture is the actual file the UI opens, not a fabricated preflight.
#[cfg(not(target_arch = "wasm32"))]
fn exported_layered_tiff(w: u32, h: u32) -> Vec<u8> {
use photocraft_doc::{Document, Layer, LayerContent};
use photocraft_raster::Surface;
let mut doc = Document::new("layers.tif", photocraft_geom::Size::new(w, h), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
let fmt = doc.pixel_format();
let bytes = (w as usize * h as usize * fmt.bytes_per_pixel()).max(1);
for name in ["bottom", "top"] {
let mut s = Surface::new(fmt);
s.write_interleaved(photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &vec![96u8; bytes]);
doc.layers.push(Layer::new(name, LayerContent::Raster(s)));
}
photocraft_io::export(&doc, "layers.tif", &photocraft_io::ExportOptions { tiff_layers: true, ..Default::default() }).expect("export a layered TIFF").bytes
}
/// #10897: a layered TIFF opened inline reaches the same high-memory prompt a PSD does. Only the
/// typed IO path carries `PsdApprovalRequired`; the shell's plain import service turns it into a
/// terminal string, so without that routing this open fails instead of prompting. The real
/// two-layer fixture plus the scoped estimate charge land in the confirmation band under a fixed
/// 5 GiB, and the prompt arrives before any composite pixel is decoded.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn inline_layered_tiff_prompts_before_decoding_and_opens_or_declines() {
if cfg!(target_pointer_width = "32") {
return; // the 3 GiB charge would exceed a 32-bit process cap
}
let gb = 1u64 << 30;
let bytes = exported_layered_tiff(8, 6);
let path = "/pics/layered.tif";
let mut app = app();
assert!(!app.background_jobs, "the inline path the web shell uses");
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None };
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
photocraft_io::memory::with_mock_memory(snap, || {
let order = crate::jobs_ui::OpenOrder { batch: crate::jobs_ui::begin_batch(&mut app), seq: 0 };
app.open_bytes_placed("layered.tif", &bytes, Some(path), None, Some(order)).unwrap();
// The prompt comes first: nothing is decoded, no tab is opened, and the engine holds
// the source for the approval. The set order travels with the prompt.
assert!(app.session.documents().is_empty(), "the layered TIFF waits for approval instead of opening");
assert!(app.jobs.opens.is_empty(), "inline: no background tab");
assert_eq!(app.held_memory_prompts.len(), 1);
assert_eq!(app.held_memory_prompts.front().unwrap().order, Some(order));
assert_eq!(app.ui.dialogs.len(), 1);
let fields = &app.ui.dialogs[0].fields;
assert!(crate::open_prompt::owns_memory(fields));
assert!(fields["estimated"].as_u64().unwrap() > 3 * gb, "the charged estimate is shown: {fields:?}");
assert_eq!(fields["available"], json!(5 * gb));
assert!(app.session.pending_preflight_bytes().unwrap() > 0, "the engine preflight holds the source");
// Accepting runs the typed TIFF import with the one-shot approval: both layers, in
// their order, keep the document's path, and the preflight is released.
let dlg = app.ui.dialogs[0].id;
let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg}));
assert_eq!(res["ok"], true, "{res}");
assert_eq!(app.session.documents().len(), 1, "the approved TIFF opens");
let st = app.session.active().unwrap();
assert_eq!(st.doc.name, "layered.tif");
assert_eq!(st.path.as_deref(), Some(path), "the approved open keeps its path");
let names: Vec<_> = st.doc.layers.iter().map(|l| l.name.clone()).collect();
assert_eq!(names, ["bottom", "top"], "both layers open in their order");
assert!(app.ui.dialogs.is_empty(), "a TIFF has no damage prompt");
assert!(app.held_memory_prompts.is_empty());
assert!(app.jobs.batches.is_empty(), "the set is forgotten once its prompted file opened");
assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0, "accepting clears the engine preflight");
// Declining opens nothing and releases the engine preflight too.
app.open_bytes_from("declined.tif", &bytes, Some("/pics/declined.tif")).unwrap();
assert_eq!(app.held_memory_prompts.len(), 1);
assert!(app.session.pending_preflight_bytes().unwrap() > 0);
let dlg = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg}))["ok"], true);
assert!(app.held_memory_prompts.is_empty() && app.ui.dialogs.is_empty());
assert_eq!(app.session.documents().len(), 1, "declining opens nothing");
assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0, "declining clears the engine preflight");
});
});
}
/// A TIFF whose Photoshop layer tag cannot be read still opens flattened through the typed path,
/// with its warning: routing TIFF magic to typed IO must not turn a malformed tag into a refusal.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn inline_tiff_with_a_malformed_layer_tag_opens_flattened() {
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![40; 4 * 3 * 3]).unwrap();
img.meta.photoshop_layers = Some(b"not Photoshop image source data".to_vec());
let bytes = photocraft_codecs::encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
let mut app = app();
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(16 << 30), swap_free: None, commit_headroom: None };
photocraft_io::memory::with_mock_memory(snap, || {
let warnings = app.open_bytes("bogus.tif", &bytes).unwrap();
assert_eq!(app.session.documents().len(), 1, "the composite still opens");
assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "a malformed tag opens one flat layer");
assert!(warnings.iter().any(|w| w.contains("opened flattened")), "{warnings:?}");
assert!(app.ui.dialogs.is_empty());
});
}
/// #10897: a file dropped on a tab slot keeps that slot through an inline memory prompt, even
/// though the open completes later (before, it appended to the end of the tab strip).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn inline_drop_slot_survives_the_memory_prompt() {
if cfg!(target_pointer_width = "32") {
return; // the 3 GiB charge would exceed a 32-bit process cap
}
let gb = 1u64 << 30;
let mut app = app();
for name in ["first.psd", "second.psd"] {
app.open_bytes(name, &recovery_psd::make_psd(false)).unwrap();
}
assert_eq!(app.session.documents().len(), 2);
let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None };
photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || {
photocraft_io::memory::with_mock_memory(snap, || {
app.open_bytes_placed("dropped.psd", &recovery_psd::make_psd(false), None, Some(0), None).unwrap();
assert_eq!(app.held_memory_prompts.len(), 1);
assert_eq!(app.held_memory_prompts.front().unwrap().slot, Some(0), "the drop slot travels with the prompt");
let dlg = app.ui.dialogs[0].id;
assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg}))["ok"], true);
let names: Vec<_> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
assert_eq!(names, ["dropped.psd", "first.psd", "second.psd"], "the approved drop keeps its tab slot");
});
});
}
+2 -2
View File
@@ -443,8 +443,8 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl
| `jobs.list` / `jobs.cancel` | `{}` / `{job?}`: background jobs; cancel one or all. Every request (and MCP tool call) first applies the jobs that finished, so `doc.save`, `doc.inspect`, `doc.render` and `session.list` include a finished job's result without polling `jobs.list` first |
| `engine.commands` | `{filter?}`: registry with params docs and enablement (`enabled`, `disabledReason`, `needsDocument`); `result` is a bare array of command objects ([Command list replies](#command-list-replies)) |
| `session.list` | open documents and the active index |
| `doc.open` / `doc.new` | `{path}` / `file.new` params |
| `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path |
| `doc.open` / `doc.new` | `{path, approveHighMemory? (false)}` / `file.new` params (`approveHighMemory` is the same one-shot PSD/PSB consent as the `file.openAs` command; see [development.md](development.md) for the structured refusal fields) |
| `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), approveHighMemory? (false), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path. `approveHighMemory` is refused unless it is a boolean |
| `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) |
| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips |
| `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command |
+121 -5
View File
@@ -678,12 +678,122 @@ 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, where measurable, system commit headroom:
- **Hard budget (H)** for known RAM: $\min(75\% \text{ RAM}, \text{RAM} - 1 \text{ GiB}, \text{commit headroom} - 512 \text{ MiB}, \text{aggregate address-space cap})$.
- **Soft budget (S)**: $\min(50\% \text{ RAM}, 8 \text{ 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. Headless callers default to no interactive dialog and require explicit per-invocation opt-in:
- Engine commands: `file.openAs` and `file.placeEmbedded` take `approveHighMemory: bool` (default `false`); `file.approveMemory` takes `{"id": u64, "approve": bool = true}`.
- Headless RPC / control protocol: `doc.open` and `doc.place` take `approveHighMemory: bool`.
- MCP: `doc_open` and `doc_place` take `approve_high_memory: bool` (default `false`; a wrong type is refused, not coerced).
- CLI: `convert`, `info`, `run`, and `batch` take `--approve-high-memory`.
- Explicit approval authorizes imports within $(S, H]$ but never bypasses the hard memory budget $H$.
- Files requiring $> H$ are refused and cannot be overridden.
- When available RAM is unknown (an unsupported platform or a failed provider), native
automatic admission is 2 GiB, not 8 GiB:
$S = \min(2 \text{ GiB}, H)$, where $H$ is the aggregate address-space cap
(`native_platform_cap`), reduced by known commit headroom. Estimates above $S$ need the same
explicit, per-invocation approval as known-memory estimates above $S$, and approval is possible
up to $H$. Estimates above 8 GiB remain approvable; `MemoryBudget::warning_threshold` and
`MemoryBudget::requires_uncertainty_warning` let callers show the uncertain-capacity warning.
8 GiB is a warning threshold, not a hard ceiling, because the process may still run out of
memory.
- These budgets apply to an import's **aggregate peak estimate**, not to one allocation: a peak
may sum many layer, mask, merged and workspace buffers. Each individual buffer must still fit
the target's layout limit (`isize::MAX`) and the decoder's own per-buffer allowance
(`photocraft-psd`'s `MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`), which is
enforced by fallible allocation or an explicit cap where that buffer is created. A 64-bit
native process has no measurable aggregate address-space cap, so admission relies on explicit
approval plus those per-buffer checks; 32-bit native uses a 2 GiB project cap
(`NATIVE_32BIT_PEAK_CAP`), a product choice below its 4 GiB address space.
- WebAssembly (wasm32): automatic admission is 1 GiB; estimates above it use the same explicit
approval. The architectural linear-memory limit is 4 GiB (65,536 × 64 KiB pages), shared with
the runtime, stack, allocator, resident document and history, and one Rust allocation cannot
exceed `isize::MAX` (2 GiB − 1). Admission uses a **project cap of 2 GiB**
(`WASM_MAX_PEAK_BUDGET`) for the aggregate peak, chosen below the address space to leave room
for the rest; it is not an architectural maximum, browsers often allow less, and allocation can
still fail.
- macOS reads a conservative reclaimable-memory measurement through `sysinfo`'s safe API:
$\min(\text{total} - \text{used}, \text{available})$, never below `free`. `total` is
`HW_MEMSIZE`; `used` is `internal_page_count - purgeable_count + wire_count +
compressor_page_count`; `available` is sysinfo's `available_memory` (`active + inactive +
free_count`, where XNU counts speculative pages inside `free_count`); `free` is its
`free_memory` (`free_count - speculative`). XNU documents *available memory* (active +
inactive + free + speculative) as everything not wired, compressed or stolen, which counts
anonymous working sets, while $\text{total} - \text{used}$ is the pool that can be handed out
without evicting one: free + file-backed + purgeable pages, close to the fully-reclaimable
pool jetsam monitors. Taking the smaller of the two keeps a counter disagreement
conservative, and `free` is a measured floor because those pages are allocatable by
definition. Swap is excluded. A genuine zero reading stays zero; unknown memory is reported
only when the provider query demonstrably failed (zero installed size or zero used memory,
which a live host cannot report). Linux reads `MemAvailable` from `/proc/meminfo` and
constrains it by the memory cgroup: v2 from the unified hierarchy's
`memory.max`/`memory.current`/`memory.swap.max`, using `cgroup.controllers` and
`cgroup.subtree_control` to distinguish a genuinely disabled controller (and the interface-file
exemption of the hierarchy root) from a view that is missing files it should expose; v1 from the
`memory` controller mount found in `/proc/self/mountinfo` (including dedicated mounts, bind
mounts and non-root process paths), applying every visible ancestor limit. When several mounts
match, the widest view (the shortest cgroup mount root) is used so a deep bind mount cannot hide
a constrained ancestor. Inactive page cache counts as reclaimable (`inactive_file` on v2,
`total_inactive_file` on v1). A v1 `memsw` limit also caps RAM; per ancestor its swap allowance
is `memsw limit - memory limit - swap already used`, and those allowances are combined
separately from RAM headroom. A memory cgroup whose mount, path, membership, limit or usage
cannot be read, or whose membership file is malformed or empty, fails closed (available memory
is treated as zero) rather than falling back to unrestricted host RAM.
- 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.
- A pending high-memory approval is bound to one source and one estimate. The engine keeps at
most 32 pending preflights and, separately, at most 1 GiB of source bytes
(`Session::MAX_PENDING_PREFLIGHT_BYTES`): only an in-memory source holds data (a path streams
from its file once opened), and an `Arc` shared by several preflights is counted once. The
retention cap is not a pixel budget or an admission limit; it keeps an unanswered prompt from
pinning unbounded memory, and is deliberately below the 2 GiB web hard cap. The charge is
computed from the queue, so answering, cancelling, refusing or clearing releases it.
- The approval verifies the file it decodes, not the path it was told about: the importer opens
the path once, reads `photocraft_io::FileIdentity` from that handle (Unix: device, inode,
length, mtime and ctime with nanoseconds), refuses with `SourceChanged` when it is not the
approved file, and re-reads the identity from the same handle when the memory preflight pauses
for approval. Windows has no stable file-index API in `std`, so its identity is the length and
modification time (a different file with both preserved is not distinguished there). The
`file.approveMemory` permission is one-shot and is not journaled or recorded in an action. A
refusal above the hard ceiling is the typed `PsdHardBudget` error (name, required, limit), not
a string, and it releases the queued source.
- A layered TIFF (Photoshop layer data in tags 37724/34377) is admitted by the same policy
before its composite is decoded. The page's tags are read into the PSD model first, without
pixels; then that model's layer/workspace estimate, the decoded composite and its
extra-sample planes, the planar big-endian merged copy, a 16-bit-float conversion's extra
copies, the decoder's scratch buffers (one strip or tile per worker, see
`codecs::TiffBands::decode_scratch_bytes`) and the decoder's copy of the tags are charged
together, with the caller limit and approval flags from `ImportOptions`. A zero caller limit
means the adaptive budget, as for a PSD. A TIFF whose layer tag cannot be read still opens
flattened with the same warning as before, and that whole-image decode and conversion are
bounded the same way. A layered TIFF opened inside another import spends the enclosing
attempt's remaining allowance instead of resolving a fresh budget, and its admission guard is
held across the composite decode and the PSD conversion, so a top-level import is charged
once and a same-file continuation is never charged again.
- Before waiting for the decode gate, an import checks admission; it checks again with a fresh
measurement once admitted, and only then decodes. This holds for the ordinary PSD and layered
TIFF paths and for the standalone legacy `psd_to_document` conversion, so an ineligible file
never waits behind an active decode. A nested import checks cancellation before consuming its
parent's remaining allowance and takes the reentrant admission guard first, so a cancelled or
refused nested import never spends the parent's budget. Hiding a large estimate behind a
destroyed composite or a malformed layer tag does not bypass the obvious bound: the
codecs' per-buffer limit (`Limits::max_alloc`) and the flat band check still apply to a page
opened without Photoshop layers.
Headless RPC and MCP report approval-required memory errors with byte counts (`required`,
`softLimit`, `hardLimit`, and `availableRam` when known). A hard-budget refusal reports only
`required` and `hardLimit`: no approval can raise that ceiling, so there is no soft limit or
capacity to act on. This holds for `doc.open` and `doc.place` and for the MCP `doc_open` and
`doc_place` tools, including a refusal from `file.openAs`/`file.placeEmbedded` reached through a
command. GUI automation imports currently cross a service boundary that returns string errors.
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.
@@ -705,6 +815,12 @@ contents, generated vector caches, and text preparation are outside it and retai
existing limits. Joining these paths to a shared budget and streaming ZIP inflation are follow-up work. An accepted
estimate does not guarantee allocation success on a memory-constrained host.
The legacy `memory::available()` helper used by flat TIFF conversion keeps its established
meaning: on Linux it reports `MemAvailable + SwapFree`, now bounded by cgroup v2 swap limits or
v1 `memsw`, and it is `None` on Windows and macOS. The adaptive budget is the only consumer of
the macOS physical-memory provider. Banded flat TIFF pages keep that helper; a layered TIFF's
whole-image work is admitted by the adaptive policy above.
## Test corpora
Real files are our best oracles, but they are large binaries, so they never go into this
+9
View File
@@ -59,3 +59,12 @@ read from outside the edited document (for example a clipboard copy) is not dete
Scratch storage alone does not make every format, filter or renderer streamable. See
[EXR streaming](streaming-io.md) for the block-by-block EXR import. Viewport rendering is a
separate change built on these guards and memory reservations.
Available RAM is measured in one place, `photocraft_raster::memory::system` (cgroup v1/v2
limits on Linux, reclaimable pages on macOS, the commit limit on Windows; swap never counts as
RAM, and an unreadable container limit fails closed). The residency budget and the PSD/PSB and
layered-TIFF import admission (`photocraft_io::memory`) both read it. While spilling is on and
not paused, import admission counts the tile pixels of a file against RAM plus the scratch room
(`spill::scratch_capacity`: the free space above the reserve, within the Scratch Size Limit);
decode buffers, conversion copies and merged planes still need RAM. With spilling off or
paused, and on the web, the RAM-only limits apply unchanged.