From a2e24096087f62c54ebca27af2c0470f04161033 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:44:46 -0800 Subject: [PATCH 01/13] Import: read PhotoCraft composites and saved layer pixels --- Cargo.lock | 67 ++++- Cargo.toml | 3 +- README.md | 3 +- apps/effectcraft-web/src/files.rs | 7 +- crates/engine/Cargo.toml | 4 + crates/engine/src/cmd/file.rs | 54 +++- crates/engine/src/footage/media_browser.rs | 2 +- crates/engine/src/footage/sequence.rs | 2 +- crates/engine/src/interchange.rs | 1 + .../engine/src/interchange/pcraft_import.rs | 160 ++++++++++++ crates/engine/src/services.rs | 23 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/import_photocraft.rs | 237 ++++++++++++++++++ crates/media/Cargo.toml | 1 + crates/media/src/convert.rs | 15 ++ crates/media/src/layered.rs | 8 +- crates/media/src/lib.rs | 26 +- crates/media/src/pcraft.rs | 170 +++++++++++++ crates/ui-egui/src/menus/frontend.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 5 +- crates/ui-egui/src/panels/forms.rs | 29 +++ crates/ui-egui/src/prefs_live.rs | 2 +- docs/photocraft-import.md | 25 ++ 23 files changed, 829 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/interchange/pcraft_import.rs create mode 100644 crates/engine/src/tests/import_photocraft.rs create mode 100644 crates/media/src/pcraft.rs create mode 100644 docs/photocraft-import.md diff --git a/Cargo.lock b/Cargo.lock index c43ba9d9c..7742a2c0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -489,6 +489,19 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -959,6 +972,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.9.4" @@ -1089,6 +1108,22 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-doc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" +dependencies = [ + "blake3", + "craft-ecproj-format", + "craft-pcraft-format", + "craft-vectorcraft-format", + "flate2", + "ruzstd", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1097,7 +1132,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13af [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ca1b5e2edb8568335c6c14f390307bd5beae8238#ca1b5e2edb8568335c6c14f390307bd5beae8238" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" dependencies = [ "serde", "serde_json", @@ -1132,6 +1167,16 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -1199,6 +1244,17 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-vectorcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1506,6 +1562,7 @@ name = "effectcraft-engine" version = "0.21.0" dependencies = [ "chrono", + "craft-doc", "craft-docpath", "effectcraft-color", "effectcraft-effects", @@ -1513,6 +1570,7 @@ dependencies = [ "effectcraft-interchange", "effectcraft-keyframe", "effectcraft-lottie", + "effectcraft-media", "effectcraft-model", "effectcraft-path", "effectcraft-pdf", @@ -1701,6 +1759,7 @@ dependencies = [ name = "effectcraft-media" version = "0.21.0" dependencies = [ + "craft-doc", "craft-docpath", "effectcraft-color", "effectcraft-model", @@ -5333,6 +5392,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" + [[package]] name = "ryu-js" version = "1.0.3" diff --git a/Cargo.toml b/Cargo.toml index f5f84775f..6c4a562c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,10 +11,11 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] +craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6ae033e6c18bde9cd6f18e505c0556667ba2226a" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", default-features = false, features = ["read"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ca1b5e2edb8568335c6c14f390307bd5beae8238" } +craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6ae033e6c18bde9cd6f18e505c0556667ba2226a" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal diff --git a/README.md b/README.md index 81b5a0ba5..585f29268 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,8 @@ cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md) ``` -New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and +New to it? [docs/photocraft-import.md](docs/photocraft-import.md) describes PhotoCraft composites and saved layer pixels. +[docs/footage.md](docs/footage.md) covers importing footage and image sequences and Interpret Footage. To work on it: `cargo test --workspace`, and `cargo xtask ci` before every commit (format, lints, diff --git a/apps/effectcraft-web/src/files.rs b/apps/effectcraft-web/src/files.rs index f6aac5aa4..b1647c15d 100644 --- a/apps/effectcraft-web/src/files.rs +++ b/apps/effectcraft-web/src/files.rs @@ -114,8 +114,13 @@ pub struct WebServices; impl Services for WebServices { fn read_file(&self, path: &str) -> std::io::Result> { get(path) - .map(|d| d.to_vec()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)"))) + .and_then(|data| { + if (data.starts_with(b"PK\x03\x04") || path.to_ascii_lowercase().ends_with(".pcraft")) && data.len() as u64 > 512 << 20 { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + } + Ok(data.to_vec()) + }) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { put(path, data.into()); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 826346987..10e4140c4 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-doc = { workspace = true } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-geom = { workspace = true } @@ -40,6 +41,9 @@ image = { workspace = true } web-time = { workspace = true } exr = { workspace = true } +[dev-dependencies] +effectcraft-media = { workspace = true } + # Native file identity and SAM 2 inference; browsers keep the built-in engines. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] same-file = { workspace = true } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e1f58a1cc..61ee1d8ae 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -321,6 +321,18 @@ impl Prober { let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?; let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?; let mut warning = None; + if f.codec == "PhotoCraft" { + let bytes = self.services.read_file(path).map_err(|e| fail(e.to_string()))?; + let outline = craft_doc::outline(&bytes, &craft_doc::Limits::default()).map_err(|e| fail(e.to_string()))?; + if let Some(canvas) = outline.canvas + && (canvas.width, canvas.height) != (f.width, f.height) + { + warning = Some(format!( + "{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", + f.width, f.height, canvas.width, canvas.height + )); + } + } // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence && !f.alphabetical @@ -416,7 +428,22 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { if let Some(retain) = retain { let mut rest = vec![]; for path in paths { + if path.to_ascii_lowercase().ends_with(".pcraft") && s.services.stamp(&path).is_some_and(|(bytes, _)| bytes > 512 << 20) { + errors.push(format!("{path}: PhotoCraft bundle exceeds the 512 MiB input limit")); + continue; + } let bytes = match s.services.read_file(&path) { + Ok(b) if path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { + match import_pcraft_comp(s, &path, &b, retain) { + Ok((comp, made, warnings)) => { + comps.push(comp); + items.extend(made); + errors.extend(warnings); + } + Err(e) => errors.push(format!("{path}: {e}")), + } + continue; + } Ok(b) if effectcraft_psd::is_psd(&b) => b, Ok(b) if effectcraft_pdf::sniff(&b).is_some() && !path.to_ascii_lowercase().ends_with(".svg") => { // PDF / Illustrator / EPS: one layer per file layer. @@ -429,6 +456,10 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { } continue; } + Err(e) if e.kind() == std::io::ErrorKind::InvalidData || path.to_ascii_lowercase().ends_with(".pcraft") => { + errors.push(format!("{path}: {e}")); + continue; + } _ => { rest.push(path); continue; @@ -545,7 +576,26 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec bool { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") || codec.eq_ignore_ascii_case("PSD") + matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "pcraft" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") + || codec.eq_ignore_ascii_case("PSD") + || codec == "PhotoCraft" +} + +fn import_pcraft_comp(s: &mut Session, path: &str, bytes: &[u8], retain: bool) -> Result<(u64, Vec, Vec)> { + use crate::interchange::pcraft_import; + let doc = pcraft_import::read(bytes).map_err(EngineError::Other)?; + let name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into()); + let rate = effectcraft_time::FrameRate::FPS_29_97; + let secs = if s.prefs.import.still_footage == "seconds" { s.prefs.import.still_seconds } else { 10.0 }; + let duration = rate.snap_nearest(effectcraft_time::Tick::from_seconds_f64(secs)); + let r = s.edit("Import", None, |project, state| { + let r = pcraft_import::import(project, &doc, path, &name, retain, rate, duration); + state.project_selection = vec![r.comp]; + Ok(r) + })?; + let mut items = vec![r.folder.0]; + items.extend(r.items.iter().map(|id| id.0)); + Ok((r.comp.0, items, r.warnings)) } /// A Photoshop layer by index or name (pixel layers only). @@ -785,7 +835,7 @@ pub fn specs() -> Vec { "File...", ["File", "Import"], Some("Cmd+I"), - "{paths: [string] (files or folders), sequence?: bool (the Sequence checkbox: true imports numbered stills of one run as one image sequence, one picked file bringing its whole run and several picked files that range; default false: picked or dropped files import as stills, as in After Effects; folders' runs import as sequences; false imports stills and a folder's files individually), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As; files import as stills unless sequence), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), newComp?: bool (make one new composition of the footage and solids imported, as file.newCompFromSelection with single; a layered file imported as a composition is that composition and gets no other; takes precedence over addToComp), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}", + "{paths: [string] (files or folders), sequence?: bool (the Sequence checkbox: true imports numbered stills of one run as one image sequence, one picked file bringing its whole run and several picked files that range; default false: picked or dropped files import as stills, as in After Effects; folders' runs import as sequences; false imports stills and a folder's files individually), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PhotoCraft, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As; files import as stills unless sequence), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), newComp?: bool (make one new composition of the footage and solids imported, as file.newCompFromSelection with single; a layered file imported as a composition is that composition and gets no other; takes precedence over addToComp), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}", always, import_cmd ), diff --git a/crates/engine/src/footage/media_browser.rs b/crates/engine/src/footage/media_browser.rs index 2c40fcf20..d21efd439 100644 --- a/crates/engine/src/footage/media_browser.rs +++ b/crates/engine/src/footage/media_browser.rs @@ -197,7 +197,7 @@ fn sort_entries(entries: &mut [Entry]) { entries.sort_by_cached_key(|e| (!e.is_dir, e.name.to_lowercase())); } -const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "svg", "tga", "dpx", "cin", "hdr"]; +const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "pcraft", "svg", "tga", "dpx", "cin", "hdr"]; const AUDIO: &[&str] = &["wav", "aif", "aiff", "mp3", "m4a", "aac", "flac", "ogg", "opus"]; const DATA: &[&str] = &["json", "csv", "tsv", "mgjson"]; const MODEL: &[&str] = &["gltf", "glb", "obj", "stl", "fbx"]; diff --git a/crates/engine/src/footage/sequence.rs b/crates/engine/src/footage/sequence.rs index fc2dab2b0..ec2547b2a 100644 --- a/crates/engine/src/footage/sequence.rs +++ b/crates/engine/src/footage/sequence.rs @@ -97,7 +97,7 @@ fn extension(path: &str) -> String { /// Stills that can form a sequence (not layered or vector documents, which import as comps). fn sequenceable(path: &str) -> bool { - crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb") + crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb" | "pcraft") } /// The run a still belongs to: (folder, name prefix, extension); alphabetical runs ignore the diff --git a/crates/engine/src/interchange.rs b/crates/engine/src/interchange.rs index 3b166b83e..a83090159 100644 --- a/crates/engine/src/interchange.rs +++ b/crates/engine/src/interchange.rs @@ -1,5 +1,6 @@ pub(crate) mod keyframe_text; pub(crate) mod keyframe_text_effects; +pub(crate) mod pcraft_import; pub mod psd_import; pub mod vector; pub mod xml_project; diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs new file mode 100644 index 000000000..a7b24ff62 --- /dev/null +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -0,0 +1,160 @@ +//! PhotoCraft's layer outline as a composition of lazily decoded, canvas-sized pixel layers. + +use std::sync::Arc; + +use craft_doc::{Layer as InputLayer, Outline}; +use effectcraft_color::{BlendMode, Label}; +use effectcraft_keyframe::Value; +use effectcraft_project::{AlphaMode, Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, SourceLayer, build}; +use effectcraft_time::{FrameRate, Tick}; + +pub(crate) struct Document { + outline: Outline, + width: u32, + height: u32, +} + +/// Metadata only: source pixels remain media and are decoded when a frame needs them, as PSD +/// footage is. Bound the number of project items before creating their property groups. +pub(crate) fn read(bytes: &[u8]) -> Result { + if bytes.len() as u64 > 512 << 20 { + return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); + } + fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { + if depth > 100 { + return Err("PhotoCraft groups exceed 100 levels".into()); + } + for layer in layers { + *nodes += 1; + if *nodes > 4096 { + return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); + } + if matches!(layer.kind.as_str(), "raster" | "text" | "shape" | "smart") { + *pixels += 1; + } + if !layer.children.is_empty() { + if layer.kind != "group" { + return Err(format!("PhotoCraft {} layer has unsupported nested content", layer.kind)); + } + count(&layer.children, depth + 1, nodes, pixels)?; + } + } + Ok(()) + } + let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| e.to_string())?; + let canvas = outline.canvas.as_ref().ok_or("not a PhotoCraft canvas")?; + let (width, height) = (canvas.width, canvas.height); + if width == 0 || height == 0 || width > effectcraft_project::limits::MAX_SIZE || height > effectcraft_project::limits::MAX_SIZE { + return Err(format!("PhotoCraft canvas {width} × {height} is outside the composition size limits")); + } + if u64::from(width) * u64::from(height) > 16 << 20 { + return Err("PhotoCraft layer decoding exceeds 16777216 canvas pixels; import as Footage for the saved composite".into()); + } + if matches!(canvas.mode.as_str(), "Cmyk" | "Lab") { + return Err(format!("PhotoCraft {} layer pixels are not supported; import as Footage for the saved composite", canvas.mode)); + } + let (mut nodes, mut pixels) = (0, 0); + count(&outline.layers, 0, &mut nodes, &mut pixels)?; + if nodes != 0 && pixels == 0 { + return Err("PhotoCraft document has no supported saved pixel layers; import as Footage for the saved composite".into()); + } + Ok(Document { outline, width, height }) +} + +pub(crate) struct Imported { + pub comp: ItemId, + pub folder: ItemId, + pub items: Vec, + pub warnings: Vec, +} + +struct Context<'a> { + doc: &'a Document, + path: &'a str, + folder: ItemId, + rate: FrameRate, + duration: Tick, + next: u32, + items: Vec, + warnings: Vec, +} + +pub(crate) fn import(project: &mut Project, doc: &Document, path: &str, name: &str, retain: bool, rate: FrameRate, duration: Tick) -> Imported { + let folder = project.add_item(&format!("{name} Layers"), Label::Yellow, None, ItemKind::Folder); + let mut ctx = Context { + doc, + path, + folder, + rate, + duration, + next: 0, + items: Vec::new(), + warnings: vec![ + "Layered PhotoCraft import uses saved pixels. Some masks, effects and profiles are unsupported; use Footage for the saved appearance.".into(), + ], + }; + if retain { + ctx.warnings.push("PhotoCraft layer footage uses the document canvas; Retain Layer Sizes keeps those canvas bounds.".into()); + } + let comp = build_comp(project, &mut ctx, name, &doc.outline.layers, None, 0); + Imported { comp, folder, items: ctx.items, warnings: ctx.warnings } +} + +fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[InputLayer], parent: Option, depth: usize) -> ItemId { + let mut comp = Comp::new(ctx.doc.width, ctx.doc.height, ctx.rate, ctx.duration); + let id = project.add_item(name, Label::Sandstone, parent, ItemKind::Comp(Arc::new(comp.clone()))); + ctx.items.push(id); + if depth <= 100 { + for input in layers { + let index = ctx.next; + ctx.next = ctx.next.saturating_add(1); + let name = if input.name.is_empty() { format!("Layer {}", index + 1) } else { input.name.clone() }; + let source = if input.kind == "group" { + let folder = ctx.folder; + let sub = build_comp(project, ctx, &name, &input.children, Some(folder), depth + 1); + LayerSource::Comp { item: sub } + } else if matches!(input.kind.as_str(), "raster" | "text" | "shape" | "smart") { + let file = std::path::Path::new(ctx.path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let footage = Footage { + path: ctx.path.into(), + kind: FootageKind::Still, + width: ctx.doc.width, + height: ctx.doc.height, + has_video: true, + alpha: AlphaMode::Straight, + codec: "PhotoCraft".into(), + layer: Some(SourceLayer { index, name: name.clone(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let item = project.add_item(&format!("{name}/{file}"), Label::Lavender, Some(ctx.folder), ItemKind::Footage(footage)); + ctx.items.push(item); + LayerSource::Footage { item } + } else { + ctx.warnings.push(format!("{name}: PhotoCraft {} content has no supported saved pixels and was skipped", input.kind)); + continue; + }; + let mut layer = build::layer(project, &comp, &name, source, (ctx.doc.width, ctx.doc.height), None); + layer.switches.video = input.visible; + if let Some(opacity) = layer.props.prop_mut("transform/opacity") { + opacity.value = Value::Scalar(f64::from(input.opacity.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0); + } + if let Some(blend) = input.blend.as_deref() { + if input.kind == "group" && (blend.eq_ignore_ascii_case("PassThrough") || blend.eq_ignore_ascii_case("Pass Through")) { + layer.switches.collapse = true; + } else if let Some(mode) = BlendMode::from_name(blend) { + layer.blend_mode = mode; + } else { + ctx.warnings.push(format!("{name}: PhotoCraft blend mode {blend} is not supported; using Normal")); + } + } + comp.layers.push(layer); + } + } + // PhotoCraft stores bottom first; EffectCraft stores the top layer first. Reverse + // after visiting the source so preorder pixel indexes still address the original tree. + comp.layers.reverse(); + if let Some(item) = project.item_mut(id) { + item.kind = ItemKind::Comp(Arc::new(comp)); + } + id +} diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 2d425a4e6..5f1a86c99 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -53,16 +53,35 @@ impl Services for FsServices { /// Refuses what isn't a regular file: a project can name `/dev/zero` or a FIFO, and reading /// those never ends (#2134). fn read_file(&self, path: &str) -> std::io::Result> { - use std::io::Read; + use std::io::{Read, Seek}; let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); } + // A renamed PhotoCraft bundle must be bounded before allocating its whole input. + // Bound ZIP containers by their signature even when manifest.json is a later entry. + let mut head = [0u8; 4]; + if meta.len() >= 4 { + file.read_exact(&mut head)?; + file.rewind()?; + } + let limited = head == *b"PK\x03\x04" || path.to_ascii_lowercase().ends_with(".pcraft"); + const MAX_BUNDLE: u64 = 512 << 20; + if limited && meta.len() > MAX_BUNDLE { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.read_to_end(&mut bytes)?; + if limited { + file.take(MAX_BUNDLE + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_BUNDLE { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle grew beyond the 512 MiB input limit")); + } + } else { + file.read_to_end(&mut bytes)?; + } Ok(bytes) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 013d2f24c..bb06ba978 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -17,6 +17,7 @@ mod fidelity; mod frame_export; mod fuzz_open; mod history; +mod import_photocraft; mod import_project; mod instance3d; mod key_metadata_order; diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs new file mode 100644 index 000000000..1298c346f --- /dev/null +++ b/crates/engine/src/tests/import_photocraft.rs @@ -0,0 +1,237 @@ +//! PhotoCraft bundles written from synthetic manifest data. + +use effectcraft_color::BlendMode; +use effectcraft_project::{ItemId, ItemKind, LayerSource}; +use serde_json::{Value, json}; + +use crate::Session; + +struct Import; + +impl crate::Importer for Import { + fn probe(&self, path: &str) -> Result { + effectcraft_media::probe(path).map_err(|e| e.to_string()) + } +} + +fn surface(color: &str) -> Value { + json!({"format":{"mode":"Rgb","sample":"U8","alpha":true},"default":color,"tiles":[]}) +} + +fn layer(name: &str, visible: bool, opacity: f32, blend: &str, content: Value) -> Value { + json!({"name":name,"visible":visible,"opacity":opacity,"blend":blend,"content":content}) +} + +fn bundle(layers: Value) -> Vec { + bundle_sized(layers, (8, 6)) +} + +fn bundle_sized(layers: Value, size: (u32, u32)) -> Vec { + let manifest = json!({"format_version":1,"generator":"synthetic PhotoCraft fixture", + "document":{"size":{"width":size.0,"height":size.1},"resolution_dpi":72.0,"mode":"Rgb","depth":"U8","layers":layers}, + "thumbnail":null,"composite":"composite/preview.png"}); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 3, image::Rgba([20, 30, 40, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + effectcraft_lottie::zip::store(&[("manifest.json".into(), serde_json::to_vec(&manifest).unwrap()), ("composite/preview.png".into(), png.into_inner())]) +} + +fn fixture(name: &str, layers: Value) -> String { + fixture_bytes(name, bundle(layers)) +} + +fn fixture_bytes(name: &str, bytes: Vec) -> String { + let dir = std::env::temp_dir().join(format!("effectcraft-pcraft-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +#[test] +fn photocraft_composite_imports_as_footage() { + let path = fixture("composite.pcraft", json!([])); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[path]})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let id = ItemId(r["items"][0].as_u64().unwrap()); + let ItemKind::Footage(f) = &s.project.item(id).unwrap().kind else { panic!("not footage") }; + assert_eq!((f.path.as_str(), f.width, f.height, f.codec.as_str()), (path.as_str(), 4, 3, "PhotoCraft")); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("4 × 3") && w.contains("8 × 6"))), "{r}"); + let image = effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((image.width, image.height), (4, 3)); + assert!((image.data[0][0] - 20.0 / 255.0).abs() < 1e-6); + assert_eq!(crate::media_browser::kind_of("shot_001.pcraft"), Some("image")); + assert!(crate::sequence::sequences(s.services.as_ref(), &["/shot_001.pcraft".into(), "/shot_002.pcraft".into()], false).is_empty()); + assert!(effectcraft_media::is_importable(std::path::Path::new("shot.PCRAFT"))); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { + let layers = json!([ + layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")})), + layer("Hidden", false, 0.25, "Multiply", json!({"kind":"text","cache":surface("00ff0080")})), + layer( + "Group", + true, + 1.0, + "Normal", + json!({"kind":"group","children":[ + layer("Nested", true, 0.5, "Screen", json!({"kind":"shape","cache":surface("0000ffff")})) + ]}) + ) + ]); + let path = fixture("layered.pcraft", layers); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(r["comps"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), "{r}"); + let cid = ItemId(r["comps"][0].as_u64().unwrap()); + let c = s.project.comp(cid).unwrap(); + assert_eq!((c.width, c.height), (8, 6)); + let bottom = c.layers.iter().find(|l| l.name == "Bottom").unwrap(); + assert!(matches!(bottom.source, LayerSource::Footage { .. })); + let hidden = c.layers.iter().find(|l| l.name == "Hidden").unwrap(); + assert!(!hidden.switches.video); + assert_eq!(hidden.blend_mode, BlendMode::Multiply); + assert_eq!(hidden.props.prop("transform/opacity").unwrap().value.as_f64(), 25.0); + let group = c.layers.iter().find(|l| l.name == "Group").unwrap(); + let LayerSource::Comp { item } = group.source else { panic!("group is not a precomposition") }; + let nested = &s.project.comp(item).unwrap().layers[0]; + assert_eq!(nested.name, "Nested"); + assert_eq!(nested.blend_mode, BlendMode::Screen); + assert_eq!(nested.props.prop("transform/opacity").unwrap().value.as_f64(), 50.0); + let LayerSource::Footage { item } = nested.source else { panic!("nested layer is not footage") }; + let ItemKind::Footage(f) = &s.project.item(item).unwrap().kind else { panic!("not footage") }; + assert_eq!(f.layer.as_ref().unwrap().index, 3); + let image = effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((image.width, image.height), (8, 6)); + assert_eq!(image.data[0], [0.0, 0.0, 1.0, 1.0]); + let saved = s.project.to_json(); + let limits = craft_doc::Limits::default(); + assert_eq!(craft_doc::info(saved.as_bytes(), &limits).unwrap().kind, craft_doc::Kind::EffectCraft); + let written = craft_doc::outline(saved.as_bytes(), &limits).unwrap(); + assert!(written.pages.iter().any(|p| p.layers.iter().any(|l| l.name == "Hidden"))); + assert!(craft_doc::renditions(saved.as_bytes(), &limits).unwrap().is_empty()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.project.items.len(), before); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_masks_and_sample_depths_decode_through_the_media_pool() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + for (sample, color, expected) in [ + ("U8", "ff0000ff", 1.0), + ("U16", "ffff00000000ffff", 1.0), + ("F32", "0000803e00000000000000000000803f", 0.5370987), + ("F32", "0000c07f00000000000000000000803f", 0.0), + ] { + let content = json!({"kind":"raster","surface":{"format":{"mode":"Rgb","sample":sample,"alpha":true},"default":color,"tiles":[]}}); + let mut raster = layer("Masked", true, 1.0, "Normal", content); + raster["mask"] = json!({"enabled":true,"density":0.5,"feather":if sample == "U16" { 0.75 } else { 0.0 }, + "surface":{"format":{"mode":"Grayscale","sample":"U8","alpha":false},"default":"80","tiles":[]}}); + let path = fixture(&format!("masked-{sample}.pcraft"), json!([raster])); + let mut f = Footage { + path: path.clone(), + width: 8, + height: 6, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Masked".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let pool = effectcraft_media::MediaPool::new(); + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + let coverage = 1.0 - 0.5 * (1.0 - 128.0 / 255.0); + assert!((image.data[0][0] - expected * coverage).abs() < 1e-5, "{sample}: {:?}", image.data[0]); + assert!((image.data[0][3] - coverage).abs() < 1e-6); + f.alpha = AlphaMode::Premultiplied; + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert!((image.data[0][0] - expected * coverage).abs() < 1e-5, "masked premultiplied {sample}: {:?}", image.data[0]); + assert!((image.data[0][3] - coverage).abs() < 1e-6); + f.alpha = AlphaMode::Ignore; + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert!((image.data[0][0] - expected).abs() < 1e-5); + assert_eq!(image.data[0][3], 1.0, "Ignore Alpha includes the source mask"); + std::fs::remove_file(path).unwrap(); + } +} + +#[test] +fn photocraft_overlapping_layers_render_in_source_stack_order() { + let path = fixture( + "stack-order.pcraft", + json!([ + layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")})), + layer( + "Group", + true, + 1.0, + "Normal", + json!({"kind":"group","children":[ + layer("Group bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("00ff00ff")})), + layer("Group top", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")})) + ]}) + ) + ]), + ); + let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + let image = s.render(comp, effectcraft_time::Tick::ZERO, Default::default()); + assert_eq!(image.data[0], [0.0, 0.0, 1.0, 1.0], "the source's top layer must cover both lower layers"); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_bad_metadata_and_missing_layer_pixels_report_errors() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + for (name, bytes) in [ + ("empty-side.pcraft", bundle_sized(json!([]), (0, 6))), + ("large-canvas.pcraft", bundle_sized(json!([]), (30_000, 30_000))), + ("unsupported-fill.pcraft", bundle(json!([layer("Fill", true, 1.0, "Normal", json!({"kind":"fill"}))]))), + ("truncated.pcraft", b"PK\x03\x04broken".to_vec()), + ] { + let path = fixture_bytes(name, bytes); + let mut s = Session::default(); + let before = s.project.items.len(); + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert!(result["comps"].as_array().unwrap().is_empty(), "{name}: {result}"); + assert!(!result["errors"].as_array().unwrap().is_empty(), "{name}: {result}"); + assert_eq!(s.project.items.len(), before); + std::fs::remove_file(path).unwrap(); + } + let path = fixture("missing-cache.pcraft", json!([layer("Text", true, 1.0, "Normal", json!({"kind":"text"}))])); + let mut f = Footage { + path: path.clone(), + width: 8, + height: 6, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Text".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let pool = effectcraft_media::MediaPool::new(); + assert!(pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string().contains("no saved pixels")); + f.layer.as_mut().unwrap().index = 99; + assert!(pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string().contains("no PhotoCraft layer")); + std::fs::remove_file(path).unwrap(); +} + +#[test] +#[cfg(unix)] // Sparse length checks exercise the guard without writing half a GiB. +fn photocraft_large_files_are_rejected_before_reading() { + for name in ["large-sparse.pcraft", "renamed-sparse.zip"] { + let path = fixture_bytes(name, b"PK\x03\x04".to_vec()); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(s.project.items.len(), before); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index a4070297b..5cca921c8 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-doc = { workspace = true, features = ["pcraft-pixels"] } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index 9e88ab4dd..cbecb2729 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -37,6 +37,21 @@ impl AlphaOp { pub(crate) fn float_curve(self) -> FloatCurve { self.float } + /// A source sample, with float RGB encoded the same way as a floating-point image. + pub(crate) fn rgba(self, rgb: [f32; 3], alpha: f32, floating: bool, coverage: f32) -> Px { + let rgb = if floating && self.mode == AlphaMode::Premultiplied { + let inv = if alpha > 0.0 { 1.0 / alpha } else { 0.0 }; + rgb.map(|v| self.float(v * inv) * alpha) + } else if floating { + rgb.map(|v| self.float(v)) + } else { + rgb + }; + let pixel = self.apply(rgb, alpha); + // Interpret the source against its original alpha and matte before applying the + // mask. Ignore Alpha deliberately ignores both source and mask coverage. + if self.mode == AlphaMode::Ignore { pixel } else { pixel.map(|v| v * coverage) } + } /// A linear float value as the compositor takes it. #[inline(always)] fn float(self, v: f32) -> f32 { diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index b259c8b7f..76e6ff0e8 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -43,11 +43,14 @@ fn is_pdf_like(path: &str, bytes: &[u8]) -> bool { /// Whether `bytes` (the first 64 KiB suffice) are a Photoshop or vector file [`probe`] handles. #[cfg_attr(not(any(unix, windows)), allow(dead_code))] pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { - effectcraft_psd::is_psd(bytes) || is_svg(path, bytes) || is_pdf_like(path, bytes) + effectcraft_psd::is_psd(bytes) || crate::pcraft::sniff(path, bytes) || is_svg(path, bytes) || is_pdf_like(path, bytes) } /// Footage for a Photoshop or vector file (`None` for other formats). pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { + if crate::pcraft::sniff(path, bytes) { + return crate::pcraft::probe(path, bytes).map(Some); + } if effectcraft_psd::is_psd(bytes) { let psd = effectcraft_psd::Psd::parse(bytes.to_vec()).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; let mut f = crate::probe::still_footage(path, psd.width, psd.height, image::ImageFormat::Png, true); @@ -76,6 +79,9 @@ pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { /// Decode a Photoshop or SVG still (`None` for other formats). pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result> { + if crate::pcraft::sniff(path, bytes) { + return crate::pcraft::decode(path, bytes, footage, op).map(Some); + } if effectcraft_psd::is_psd(bytes) { let psd = effectcraft_psd::Psd::parse(bytes.to_vec()).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; // A smart object's embedded file: an embedded document's merged image, or an image. diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index e985985b7..ad6b1442a 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -11,7 +11,8 @@ //! AV1, ProRes, DNxHD, MPEG-2, MJPEG; AAC, Opus, PCM, MP3/FLAC/Vorbis) come from FilmCraft's pure-Rust crates (git dependency, //! pinned; `plan/adr/0001`). FilmCraft types never leave this crate. Stills use the `image` crate //! (PNG, JPEG, GIF, WebP, TIFF, BMP, OpenEXR, Targa, Radiance HDR); Photoshop documents (merged image or one layer) come -//! from `effectcraft-psd` and SVG from `effectcraft-svg` (rasterised at any scale). +//! from `effectcraft-psd`, PhotoCraft composites and saved layer pixels from `craft-doc`, and SVG +//! from `effectcraft-svg` (rasterised at any scale). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -22,6 +23,7 @@ mod dpx; pub mod exr_channels; mod gif_anim; mod layered; +mod pcraft; pub use layered::vector_doc; mod pool; mod probe; @@ -62,7 +64,7 @@ impl From for MediaError { /// File extensions recognised as stills. pub const STILL_EXTENSIONS: &[&str] = - &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps"]; + &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "pcraft", "svg", "pdf", "ai", "eps"]; /// File extensions recognised as audio-only files. pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS; pub use effectcraft_project::VIDEO_EXTENSIONS; @@ -83,16 +85,32 @@ pub fn is_importable(path: &std::path::Path) -> bool { /// A whole file's bytes, refusing anything that isn't a regular file: a project can name /// `/dev/zero` or a FIFO as footage, and reading those never ends (#2134). pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> { - use std::io::Read; + use std::io::{Read, Seek}; let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } + let mut head = [0u8; 4]; + if meta.len() >= 4 { + file.read_exact(&mut head)?; + file.rewind()?; + } + let pcraft = ext_of(path) == "pcraft" || head == *b"PK\x03\x04"; + if pcraft && meta.len() > pcraft::MAX_INPUT_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.read_to_end(&mut bytes)?; + if pcraft { + file.take(pcraft::MAX_INPUT_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > pcraft::MAX_INPUT_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); + } + } else { + file.read_to_end(&mut bytes)?; + } Ok(bytes) } diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs new file mode 100644 index 000000000..fb7587c31 --- /dev/null +++ b/crates/media/src/pcraft.rs @@ -0,0 +1,170 @@ +//! PhotoCraft's saved composite and canvas-sized raster or cached layer pixels. + +use craft_doc::{Layer, RenditionKind, Samples}; +use effectcraft_project::{AlphaMode, Footage}; +use effectcraft_raster::Image; + +use crate::convert::{AlphaOp, dynamic_to_image}; +use crate::{MediaError, Result}; + +/// Keep the decoded float frame and its conversion buffers within the still-image budget. +const MAX_PIXELS: u64 = 16 << 20; +pub(crate) const MAX_INPUT_BYTES: u64 = 512 << 20; + +pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { + path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(bytes) == Some(craft_doc::Kind::PhotoCraft) +} + +fn error(path: &str, e: impl std::fmt::Display) -> MediaError { + MediaError::Decode(format!("{path}: {e}")) +} + +fn check_size(path: &str, width: u32, height: u32) -> Result<()> { + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_PIXELS { + return Err(error(path, format!("PhotoCraft image {width} × {height} exceeds the {MAX_PIXELS}-pixel decoding limit or has an empty side"))); + } + Ok(()) +} + +fn composite(path: &str, bytes: &[u8]) -> Result> { + check_input(path, bytes)?; + craft_doc::renditions(bytes, &craft_doc::Limits::default()) + .map_err(|e| error(path, e))? + .into_iter() + .find(|r| r.kind == RenditionKind::Composite) + .map(|r| r.bytes) + .ok_or_else(|| error(path, "PhotoCraft document has no saved composite")) +} + +fn check_input(path: &str, bytes: &[u8]) -> Result<()> { + if bytes.len() as u64 > MAX_INPUT_BYTES { + return Err(error(path, "PhotoCraft bundle exceeds the 512 MiB input limit")); + } + Ok(()) +} + +fn png_size(path: &str, bytes: &[u8]) -> Result<(u32, u32)> { + let size = image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().map_err(|e| error(path, e))?; + check_size(path, size.0, size.1)?; + Ok(size) +} + +pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result { + let png = composite(path, bytes)?; + let (w, h) = png_size(path, &png)?; + let mut f = crate::probe::still_footage(path, w, h, image::ImageFormat::Png, true); + f.codec = "PhotoCraft".into(); + f.alpha = AlphaMode::Straight; + Ok(f) +} + +/// Preorder indexes include groups and unsupported layers, so a reload addresses the same +/// outline entry used by the composition importer. +fn layer_path(layers: &[Layer], wanted: u32) -> Option> { + fn find(layers: &[Layer], wanted: u32, next: &mut u32, path: &mut Vec, depth: usize) -> Option> { + if depth > 100 { + return None; + } + for (index, layer) in layers.iter().enumerate() { + path.push(index); + let current = *next; + *next = next.checked_add(1)?; + if current == wanted { + return Some(path.clone()); + } + if let Some(found) = find(&layer.children, wanted, next, path, depth + 1) { + return Some(found); + } + path.pop(); + } + None + } + find(layers, wanted, &mut 0, &mut Vec::new(), 0) +} + +fn mask_image(path: &str, width: u32, height: u32, samples: Samples) -> Result { + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|e| error(path, e))?; + if samples.len() != count { + return Err(error(path, "PhotoCraft mask size does not match the canvas")); + } + let mut data = Vec::new(); + data.try_reserve_exact(count).map_err(|e| error(path, e))?; + let pixel = |v: f32| [if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; 4]; + match samples { + Samples::U8(v) => data.extend(v.into_iter().map(|v| pixel(f32::from(v) / 255.0))), + Samples::U16(v) => data.extend(v.into_iter().map(|v| pixel(f32::from(v) / 65535.0))), + Samples::F32(v) => data.extend(v.into_iter().map(pixel)), + _ => return Err(error(path, "unsupported PhotoCraft mask sample type")), + } + Ok(Image { width, height, data }) +} + +pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result { + check_input(path, bytes)?; + let Some(layer) = &footage.layer else { + let png = composite(path, bytes)?; + png_size(path, &png)?; + let image = crate::probe::load_oriented(&png, Some(image::ImageFormat::Png)).map_err(|e| error(path, e))?; + return Ok(dynamic_to_image(&image, op)); + }; + if layer.layer_size || layer.embedded.is_some() || layer.placed { + return Err(error(path, "PhotoCraft layer footage supports canvas-sized saved pixels, not cropped or embedded-file sources")); + } + let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| error(path, e))?; + let canvas = outline.canvas.ok_or_else(|| error(path, "PhotoCraft document has no canvas"))?; + check_size(path, canvas.width, canvas.height)?; + let indexes = layer_path(&outline.layers, layer.index).ok_or_else(|| error(path, format!("no PhotoCraft layer {}", layer.index)))?; + let pixels = craft_doc::pcraft_layer_rgba(bytes, &indexes, &craft_doc::Limits::default()) + .map_err(|e| error(path, e))? + .ok_or_else(|| error(path, format!("PhotoCraft layer {} has no saved pixels", layer.name)))?; + let (w, h) = (pixels.width, pixels.height); + let count = usize::try_from(u64::from(w) * u64::from(h)).map_err(|e| error(path, e))?; + if count.checked_mul(4) != Some(pixels.rgba.len()) { + return Err(error(path, "PhotoCraft layer sample count does not match the canvas")); + } + let mask = if let Some(mask) = pixels.mask.filter(|m| m.enabled) { + let mut alpha = mask_image(path, w, h, mask.alpha)?; + let sigma = if mask.feather.is_finite() { f64::from(mask.feather.clamp(0.0, 1000.0)) } else { 0.0 }; + if sigma > 0.0 { + alpha = if effectcraft_raster::gaussian_is_exact(sigma, sigma) { + effectcraft_raster::gaussian_blur_exact(&alpha, sigma, sigma, true) + } else { + effectcraft_raster::gaussian_blur(&alpha, sigma, sigma, true) + }; + } + let density = if mask.density.is_finite() { mask.density.clamp(0.0, 1.0) } else { 1.0 }; + Some((alpha, density)) + } else { + None + }; + let mut data = Vec::new(); + data.try_reserve_exact(count).map_err(|e| error(path, e))?; + let mut push = |index: usize, rgba: [f32; 4], floating: bool| -> Result<()> { + let rgba = rgba.map(|v| if v.is_finite() { v } else { 0.0 }); + let coverage = match &mask { + Some((alpha, density)) => 1.0 - density * (1.0 - alpha.data.get(index).ok_or_else(|| error(path, "PhotoCraft mask pixel is missing"))?[3]), + None => 1.0, + }; + data.push(op.rgba([rgba[0], rgba[1], rgba[2]], rgba[3].clamp(0.0, 1.0), floating, coverage)); + Ok(()) + }; + match pixels.rgba { + Samples::U8(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [f32::from(*r), f32::from(*g), f32::from(*b), f32::from(*a)].map(|v| v / 255.0), false)?; + } + } + Samples::U16(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [f32::from(*r), f32::from(*g), f32::from(*b), f32::from(*a)].map(|v| v / 65535.0), false)?; + } + } + Samples::F32(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [*r, *g, *b, *a], true)?; + } + } + _ => return Err(error(path, "unsupported PhotoCraft layer sample type")), + } + Ok(Image { width: w, height: h, data }) +} diff --git a/crates/ui-egui/src/menus/frontend.rs b/crates/ui-egui/src/menus/frontend.rs index 71bf8214b..88c5bb7c7 100644 --- a/crates/ui-egui/src/menus/frontend.rs +++ b/crates/ui-egui/src/menus/frontend.rs @@ -607,7 +607,7 @@ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> // Importable files besides movies. const MEDIA: &[&str] = &[ "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3", "flac", "ogg", "opus", "svg", "pdf", "ai", - "eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv", + "eps", "psd", "psb", "pcraft", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv", ]; let footage = |more: &[&'static str]| effectcraft_project::VIDEO_EXTENSIONS.iter().chain(more).copied().collect::>(); // A host whose blocking dialogs are unsafe inside this frame shows the dialog without diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 0ed3fe7ad..fe16b7486 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -449,7 +449,7 @@ fn file_dialogs_block_floating_windows_only_while_up() { } #[test] -fn tga_is_available_in_import_replace_and_proxy_dialogs() { +fn tga_is_available_in_import_replace_and_proxy_and_pcraft_in_import_replace() { use std::sync::{Arc, Mutex}; let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); let ctx = egui::Context::default(); @@ -460,6 +460,9 @@ fn tga_is_available_in_import_replace_and_proxy_dialogs() { assert_eq!(invoke(&mut app, &ctx, command, json!({})).unwrap(), json!({"dialog": command})); let crate::FileDialog::Open { exts, .. } = pending.lock().unwrap().pop().unwrap() else { panic!("not an open dialog") }; assert!(exts.iter().any(|ext| ext == "tga"), "{command}: {exts:?}"); + if command != "file.setProxy" { + assert!(exts.iter().any(|ext| ext == "pcraft"), "{command}: {exts:?}"); + } } } diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index 65d825b45..269db8a47 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -513,6 +513,20 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { let lt = layer.map(|l| l.layer_time(t)).unwrap_or(t); let mut base = p.clone(); let (title, fields): (String, Vec) = match id { + "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { + let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); + let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); + ( + "Import PhotoCraft File".into(), + vec![ + Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), + Field::note( + "pcraftNote", + "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", + ), + ], + ) + } // Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes). Dropped // files start at Settings ▸ Import ▸ Default Drag Import As. "file.import" if !has(p, &["importAs"]) && is_layered(p) => { @@ -1050,6 +1064,21 @@ pub fn show_view_options(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Toke mod tests { use super::*; + #[test] + fn photocraft_import_offers_footage_or_canvas_sized_layers() { + for (pref, expected) in [("footage", "footage"), ("comp", "composition"), ("compLayerSizes", "composition")] { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.session.prefs.import.drag_import_as = pref.into(); + let reply = crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths":["/picked.pcraft"],"drag":true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import PhotoCraft File"); + assert_eq!(app.dialog_state.form.params()["importAs"], expected); + assert!(app.dialog_state.form.params().get("pcraftNote").is_none()); + let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; + assert_eq!(options.len(), 2, "Retain Layer Sizes is not offered for canvas-sized PhotoCraft pixels"); + } + } + #[test] fn form_params_build_arrays_and_choices() { let f = Form { diff --git a/crates/ui-egui/src/prefs_live.rs b/crates/ui-egui/src/prefs_live.rs index b456dc7ce..f351864eb 100644 --- a/crates/ui-egui/src/prefs_live.rs +++ b/crates/ui-egui/src/prefs_live.rs @@ -112,7 +112,7 @@ pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) { let alt = ctx.input(|i| i.modifiers.alt); // A dropped Photoshop file asks how to import it (the Import Photoshop File dialog, its // Import Kind starting at Default Drag Import As), as File ▸ Import ▸ File… does (#678). - let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb"))); + let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb" | "pcraft"))); let mut params = json!({ "paths": rest, "drag": true, diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md new file mode 100644 index 000000000..8c4d709e3 --- /dev/null +++ b/docs/photocraft-import.md @@ -0,0 +1,25 @@ +# Import PhotoCraft documents + +Choose **File ▸ Import ▸ File…** and select a `.pcraft` document. Numbered PhotoCraft documents import individually, rather than as an image sequence. + +**Footage** reads the document's saved composite as one still image. Its dimensions are the saved image's actual dimensions. The currently pinned shared reader exposes PhotoCraft's saved preview, which can be smaller than the canvas. Import reports both sizes when they differ. Full-resolution composite selection requires a later shared-reader update. + +**Composition** creates a composition with canvas-sized layer footage. It preserves layer names, visibility, opacity, recognized blend modes and group nesting. Groups become precompositions; pass-through groups use Collapse Transformations. Raster layers and saved pixel caches for text, shapes and smart objects remain linked to the source file. Text, shapes and smart objects are imported as pixels, without their native editing controls. + +Layer pixels decode when a frame needs them. Missing caches or unsupported pixel data produce media decoding errors when used. Layered import supports RGB and grayscale pixels with 8-bit, 16-bit or floating-point samples. Enabled raster masks apply their density and feather. Native effects, vector and group masks, and embedded color profiles are unsupported, so a layered composition can differ from the saved appearance. Choose Footage when that appearance matters. + +The dialog offers Footage and Composition. The command API also accepts `compositionLayerSizes`, but reports that PhotoCraft layers retain the full canvas bounds. A drag preference for retaining layer sizes selects Composition in this dialog. + +## Command API + +```json +{"command":"file.import","params":{"paths":["/path/artwork.pcraft"],"importAs":"footage"}} +``` + +Use `"importAs":"composition"` for layers. Import uses the existing still-footage duration preference and creates one undoable import operation for each layered document. Compatibility messages accompany the command's import results. + +## Limits + +PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites and layer canvases are limited to 16,777,216 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. + +Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. From 76bd5dc1018966cce0f709dbfc61e294ea942437 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:51:02 -0800 Subject: [PATCH 02/13] Import: budget PhotoCraft layer buffers before decoding pixels --- .../engine/src/interchange/pcraft_import.rs | 6 +++-- crates/engine/src/tests/import_photocraft.rs | 22 +++++++++++++++++++ crates/media/src/pcraft.rs | 7 ++++++ docs/photocraft-import.md | 4 +++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs index a7b24ff62..681409f1f 100644 --- a/crates/engine/src/interchange/pcraft_import.rs +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -47,8 +47,10 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if width == 0 || height == 0 || width > effectcraft_project::limits::MAX_SIZE || height > effectcraft_project::limits::MAX_SIZE { return Err(format!("PhotoCraft canvas {width} × {height} is outside the composition size limits")); } - if u64::from(width) * u64::from(height) > 16 << 20 { - return Err("PhotoCraft layer decoding exceeds 16777216 canvas pixels; import as Footage for the saved composite".into()); + if u64::from(width) * u64::from(height) > 12 << 20 { + return Err( + "PhotoCraft layer decoding exceeds the 1 GiB working-buffer budget (12582912 canvas pixels); import as Footage for the saved composite".into() + ); } if matches!(canvas.mode.as_str(), "Cmyk" | "Lab") { return Err(format!("PhotoCraft {} layer pixels are not supported; import as Footage for the saved composite", canvas.mode)); diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 1298c346f..e9b7af55c 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -235,3 +235,25 @@ fn photocraft_large_files_are_rejected_before_reading() { std::fs::remove_file(path).unwrap(); } } + +#[test] +fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + // An invalid source sample proves the budget is checked before the pixel reader. + let mut raster = layer("Large masked layer", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("invalid-pixel-sample")})); + raster["mask"] = json!({"enabled":true,"density":1.0,"feather":4.0, + "surface":{"format":{"mode":"Grayscale","sample":"U8","alpha":false},"default":"ff","tiles":[]}}); + let path = fixture_bytes("mask-budget.pcraft", bundle_sized(json!([raster]), (4097, 3072))); + let f = Footage { + path: path.clone(), + width: 4097, + height: 3072, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Large masked layer".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let error = effectcraft_media::MediaPool::new().frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string(); + assert!(error.contains("1 GiB working-buffer budget") && error.contains("Footage"), "{error}"); + std::fs::remove_file(path).unwrap(); +} diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs index fb7587c31..220fcd381 100644 --- a/crates/media/src/pcraft.rs +++ b/crates/media/src/pcraft.rs @@ -9,6 +9,10 @@ use crate::{MediaError, Result}; /// Keep the decoded float frame and its conversion buffers within the still-image budget. const MAX_PIXELS: u64 = 16 << 20; +// Conservatively count source RGBA (16 B), raw mask samples (4 B), mask image +// (16 B), two blur images (32 B) and output (16 B), even where lifetimes do not +// overlap. Twelve Mi pixels fit within a 1 GiB working-buffer budget (84 B/pixel). +const MAX_LAYER_PIXELS: u64 = 12 << 20; pub(crate) const MAX_INPUT_BYTES: u64 = 512 << 20; pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { @@ -113,6 +117,9 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| error(path, e))?; let canvas = outline.canvas.ok_or_else(|| error(path, "PhotoCraft document has no canvas"))?; check_size(path, canvas.width, canvas.height)?; + if u64::from(canvas.width) * u64::from(canvas.height) > MAX_LAYER_PIXELS { + return Err(error(path, "PhotoCraft layer exceeds the 1 GiB working-buffer budget; import as Footage for the saved composite")); + } let indexes = layer_path(&outline.layers, layer.index).ok_or_else(|| error(path, format!("no PhotoCraft layer {}", layer.index)))?; let pixels = craft_doc::pcraft_layer_rgba(bytes, &indexes, &craft_doc::Limits::default()) .map_err(|e| error(path, e))? diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md index 8c4d709e3..47cdf5a8c 100644 --- a/docs/photocraft-import.md +++ b/docs/photocraft-import.md @@ -20,6 +20,8 @@ Use `"importAs":"composition"` for layers. Import uses the existing still-footag ## Limits -PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites and layer canvases are limited to 16,777,216 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. +PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. + +Layer decoding has a separate limit of 12,582,912 canvas pixels, checked before reading source samples. A conservative budget counts the source, raw mask, mask image, both feathering intermediates and output together, within 1 GiB of working buffers. Larger canvases report an error recommending Footage before decoding layer pixels. This includes masked and unmasked layers; saved composites retain the 16,777,216-pixel limit. From b7cd1ae80dcfa9a8cdb3db1b5feec12045c51907 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:55:01 -0800 Subject: [PATCH 03/13] Import: match PhotoCraft group depth to the renderer limit --- .../engine/src/interchange/pcraft_import.rs | 12 ++++++--- crates/engine/src/tests/import_photocraft.rs | 25 +++++++++++++++++++ docs/photocraft-import.md | 2 +- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs index 681409f1f..ae3b4e4e0 100644 --- a/crates/engine/src/interchange/pcraft_import.rs +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -8,6 +8,9 @@ use effectcraft_keyframe::Value; use effectcraft_project::{AlphaMode, Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, SourceLayer, build}; use effectcraft_time::{FrameRate, Tick}; +// Each source group becomes a precomposition; match the renderer's nesting limit. +const MAX_GROUP_DEPTH: usize = 16; + pub(crate) struct Document { outline: Outline, width: u32, @@ -21,10 +24,13 @@ pub(crate) fn read(bytes: &[u8]) -> Result { return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); } fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { - if depth > 100 { - return Err("PhotoCraft groups exceed 100 levels".into()); + if depth > MAX_GROUP_DEPTH { + return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); } for layer in layers { + if depth == MAX_GROUP_DEPTH && layer.kind == "group" { + return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); + } *nodes += 1; if *nodes > 4096 { return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); @@ -106,7 +112,7 @@ fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[In let mut comp = Comp::new(ctx.doc.width, ctx.doc.height, ctx.rate, ctx.duration); let id = project.add_item(name, Label::Sandstone, parent, ItemKind::Comp(Arc::new(comp.clone()))); ctx.items.push(id); - if depth <= 100 { + if depth <= MAX_GROUP_DEPTH { for input in layers { let index = ctx.next; ctx.next = ctx.next.saturating_add(1); diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index e9b7af55c..203fc9ecf 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -257,3 +257,28 @@ fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { assert!(error.contains("1 GiB working-buffer budget") && error.contains("Footage"), "{error}"); std::fs::remove_file(path).unwrap(); } + +#[test] +fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { + for (depth, blend) in [(16, "Normal"), (16, "PassThrough"), (17, "Normal"), (17, "PassThrough")] { + let mut layers = json!([layer("Deep pixels", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")}))]); + for index in 0..depth { + layers = json!([layer(&format!("Group {index}"), true, 1.0, blend, json!({"kind":"group","children":layers}))]); + } + let path = fixture(&format!("nesting-{depth}-{blend}.pcraft"), layers); + let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; + let before = s.project.items.len(); + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + if depth == 16 { + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0]); + } else { + assert_eq!(s.project.items.len(), before, "unsupported nesting must not create a composition with disappearing artwork"); + assert!( + result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("16 levels") && e.contains("Footage"))), + "{result}" + ); + } + std::fs::remove_file(path).unwrap(); + } +} diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md index 47cdf5a8c..0599fcfbf 100644 --- a/docs/photocraft-import.md +++ b/docs/photocraft-import.md @@ -20,7 +20,7 @@ Use `"importAs":"composition"` for layers. Import uses the existing still-footag ## Limits -PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. +PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. From 6d5615cb4336c40b77a4ab4196f3d3008d923c68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 03:54:06 -0800 Subject: [PATCH 04/13] Import: keep optional PhotoCraft canvas warnings non-fatal --- crates/engine/src/cmd/file.rs | 21 ++++++------- crates/engine/src/tests/import_photocraft.rs | 32 ++++++++++++++++++++ 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 61ee1d8ae..e91de3e6f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -321,17 +321,16 @@ impl Prober { let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?; let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?; let mut warning = None; - if f.codec == "PhotoCraft" { - let bytes = self.services.read_file(path).map_err(|e| fail(e.to_string()))?; - let outline = craft_doc::outline(&bytes, &craft_doc::Limits::default()).map_err(|e| fail(e.to_string()))?; - if let Some(canvas) = outline.canvas - && (canvas.width, canvas.height) != (f.width, f.height) - { - warning = Some(format!( - "{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", - f.width, f.height, canvas.width, canvas.height - )); - } + // The composite has already probed successfully. Optional canvas metadata must + // not prevent Footage import when its read or outline exceeds another limit. + if f.codec == "PhotoCraft" + && let Ok(bytes) = self.services.read_file(path) + && let Ok(outline) = craft_doc::outline(&bytes, &craft_doc::Limits::default()) + && let Some(canvas) = outline.canvas + && (canvas.width, canvas.height) != (f.width, f.height) + { + warning = + Some(format!("{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", f.width, f.height, canvas.width, canvas.height)); } // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 203fc9ecf..58115fd71 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -119,6 +119,38 @@ fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { std::fs::remove_file(path).unwrap(); } +#[test] +fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { + struct Metadata(bool); + impl crate::Services for Metadata { + fn read_file(&self, _: &str) -> std::io::Result> { + if self.0 { + Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "metadata unavailable")) + } else { + Ok(b"invalid optional metadata".to_vec()) + } + } + fn write_file(&self, _: &str, _: &[u8]) -> std::io::Result<()> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "read only")) + } + } + for unreadable in [true, false] { + let path = fixture(&format!("optional-metadata-{unreadable}.pcraft"), json!([])); + let mut s = Session { services: std::sync::Arc::new(Metadata(unreadable)), importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let result = s.execute("file.import", json!({"paths":[path]})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert_eq!(result["items"].as_array().unwrap().len(), 1, "a successful media probe must survive an optional warning failure"); + let id = ItemId(result["items"][0].as_u64().unwrap()); + let ItemKind::Footage(f) = &s.project.item(id).unwrap().kind else { panic!("not footage") }; + assert_eq!((f.width, f.height), (4, 3)); + assert_eq!( + effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap().data[0], + [20.0 / 255.0, 30.0 / 255.0, 40.0 / 255.0, 1.0] + ); + std::fs::remove_file(path).unwrap(); + } +} + #[test] fn photocraft_masks_and_sample_depths_decode_through_the_media_pool() { use effectcraft_project::{AlphaMode, Footage, SourceLayer}; From bc527043b04680c01ed01c6d3f1888a055c49b26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 20:32:10 -0800 Subject: [PATCH 05/13] Import: limit only PhotoCraft reads to 512 MiB Services::read_file and the media reader no longer refuse ZIP-based files over 512 MiB, so large templates and dotLottie files read as before. A new Services::read_pcraft applies the limit before reading, and the PhotoCraft canvas check and composition import use it for .pcraft files; the browser checks the stored size before copying. The media reader limits .pcraft files before reading. A PhotoCraft bundle with another extension is still refused after its read, before it is parsed. --- apps/effectcraft-web/src/files.rs | 16 ++-- crates/engine/src/cmd/file.rs | 16 ++-- crates/engine/src/lib.rs | 2 +- crates/engine/src/services.rs | 94 +++++++++++++------- crates/engine/src/tests/import_photocraft.rs | 20 ++--- crates/media/src/lib.rs | 27 ++++-- docs/photocraft-import.md | 2 +- 7 files changed, 112 insertions(+), 65 deletions(-) diff --git a/apps/effectcraft-web/src/files.rs b/apps/effectcraft-web/src/files.rs index b1647c15d..d33db6542 100644 --- a/apps/effectcraft-web/src/files.rs +++ b/apps/effectcraft-web/src/files.rs @@ -114,13 +114,17 @@ pub struct WebServices; impl Services for WebServices { fn read_file(&self, path: &str) -> std::io::Result> { get(path) + .map(|d| d.to_vec()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)"))) - .and_then(|data| { - if (data.starts_with(b"PK\x03\x04") || path.to_ascii_lowercase().ends_with(".pcraft")) && data.len() as u64 > 512 << 20 { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); - } - Ok(data.to_vec()) - }) + } + /// Checks the size before copying the stored bytes. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + let data = + get(path).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)")))?; + if data.len() as u64 > effectcraft_engine::PCRAFT_MAX_INPUT { + return Err(effectcraft_engine::pcraft_too_large()); + } + Ok(data.to_vec()) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { put(path, data.into()); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e91de3e6f..23e835cbf 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -324,7 +324,7 @@ impl Prober { // The composite has already probed successfully. Optional canvas metadata must // not prevent Footage import when its read or outline exceeds another limit. if f.codec == "PhotoCraft" - && let Ok(bytes) = self.services.read_file(path) + && let Ok(bytes) = self.services.read_pcraft(path) && let Ok(outline) = craft_doc::outline(&bytes, &craft_doc::Limits::default()) && let Some(canvas) = outline.canvas && (canvas.width, canvas.height) != (f.width, f.height) @@ -427,12 +427,12 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { if let Some(retain) = retain { let mut rest = vec![]; for path in paths { - if path.to_ascii_lowercase().ends_with(".pcraft") && s.services.stamp(&path).is_some_and(|(bytes, _)| bytes > 512 << 20) { - errors.push(format!("{path}: PhotoCraft bundle exceeds the 512 MiB input limit")); - continue; - } - let bytes = match s.services.read_file(&path) { - Ok(b) if path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { + // Only PhotoCraft reads have the input limit; a renamed bundle is checked after its + // read, before it is parsed. + let pcraft = path.to_ascii_lowercase().ends_with(".pcraft"); + let read = if pcraft { s.services.read_pcraft(&path) } else { s.services.read_file(&path) }; + let bytes = match read { + Ok(b) if pcraft || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { match import_pcraft_comp(s, &path, &b, retain) { Ok((comp, made, warnings)) => { comps.push(comp); @@ -455,7 +455,7 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { } continue; } - Err(e) if e.kind() == std::io::ErrorKind::InvalidData || path.to_ascii_lowercase().ends_with(".pcraft") => { + Err(e) if pcraft => { errors.push(format!("{path}: {e}")); continue; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0cc9a7189..6493a0481 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -95,7 +95,7 @@ pub use doc_state::{CompSelection, EditorState, KeyClip, KeyMove, KeyRef, LinkCl pub use error::{EngineError, Result}; pub use event::Event; pub use fonts::{FontRow, font_features, font_menu, font_preview, font_styles, text_families}; -pub use services::{FsServices, Importer, Services}; +pub use services::{FsServices, Importer, PCRAFT_MAX_INPUT, Services, pcraft_too_large}; pub use session::upgrade_effects; pub struct Session { diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 5f1a86c99..cce219f33 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -1,8 +1,28 @@ use super::config; +/// The largest PhotoCraft bundle [`Services::read_pcraft`] reads. +pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; + +/// The error for a PhotoCraft bundle over [`PCRAFT_MAX_INPUT`]. +pub fn pcraft_too_large() -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit") +} + /// Host services (file access) injected by the frontend. pub trait Services: Send + Sync { fn read_file(&self, path: &str) -> std::io::Result>; + /// A PhotoCraft bundle's bytes: like [`Services::read_file`], but a file over + /// [`PCRAFT_MAX_INPUT`] is an error. Other files read with `read_file` have no such limit. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + if self.stamp(path).is_some_and(|(len, _)| len > PCRAFT_MAX_INPUT) { + return Err(pcraft_too_large()); + } + let bytes = self.read_file(path)?; + if bytes.len() as u64 > PCRAFT_MAX_INPUT { + return Err(pcraft_too_large()); + } + Ok(bytes) + } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()>; /// Whether a file exists (the background footage check after open). fn exists(&self, path: &str) -> bool { @@ -53,42 +73,39 @@ impl Services for FsServices { /// Refuses what isn't a regular file: a project can name `/dev/zero` or a FIFO, and reading /// those never ends (#2134). fn read_file(&self, path: &str) -> std::io::Result> { - use std::io::{Read, Seek}; - let mut file = std::fs::File::open(path)?; - let meta = file.metadata()?; - if !meta.is_file() { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); - } - // A renamed PhotoCraft bundle must be bounded before allocating its whole input. - // Bound ZIP containers by their signature even when manifest.json is a later entry. - let mut head = [0u8; 4]; - if meta.len() >= 4 { - file.read_exact(&mut head)?; - file.rewind()?; - } - let limited = head == *b"PK\x03\x04" || path.to_ascii_lowercase().ends_with(".pcraft"); - const MAX_BUNDLE: u64 = 512 << 20; - if limited && meta.len() > MAX_BUNDLE { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); - } - let mut bytes = Vec::new(); - // A sparse file can claim far more than memory: an error, not an abort. - bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - if limited { - file.take(MAX_BUNDLE + 1).read_to_end(&mut bytes)?; - if bytes.len() as u64 > MAX_BUNDLE { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle grew beyond the 512 MiB input limit")); - } - } else { - file.read_to_end(&mut bytes)?; - } - Ok(bytes) + read_regular_file(path, None) + } + /// Checks the size before reserving the buffer, and stops reading a file that grows past + /// the limit while it is read. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + read_regular_file(path, Some(PCRAFT_MAX_INPUT)) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { config::atomic_write(std::path::Path::new(path), data) } } +/// A regular file's bytes; with `limit`, a file larger than `limit` bytes is an error. +fn read_regular_file(path: &str, limit: Option) -> std::io::Result> { + use std::io::Read; + let file = std::fs::File::open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); + } + if limit.is_some_and(|max| meta.len() > max) { + return Err(pcraft_too_large()); + } + let mut bytes = Vec::new(); + // A sparse file can claim far more than memory: an error, not an abort. + bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; + file.take(limit.map_or(u64::MAX, |max| max + 1)).read_to_end(&mut bytes)?; + if limit.is_some_and(|max| bytes.len() as u64 > max) { + return Err(pcraft_too_large()); + } + Ok(bytes) +} + /// Imports media files into the project (implemented by the media layer). pub trait Importer: Send + Sync { /// Probe one file and return footage metadata. Image sequences are the engine's @@ -118,4 +135,21 @@ mod tests { assert_eq!(FsServices.read_file(&f.to_string_lossy()).unwrap(), b"data"); let _ = std::fs::remove_file(f); } + + /// Templates and dotLottie files are ZIP archives too: only PhotoCraft reads have the + /// 512 MiB input limit. The length is set without writing the data. + #[test] + fn only_photocraft_reads_have_the_input_limit() { + let f = std::env::temp_dir().join(format!("ec-services-large-{}.zip", std::process::id())); + std::fs::write(&f, b"PK\x03\x04").unwrap(); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(super::PCRAFT_MAX_INPUT + 1).unwrap(); + let path = f.to_string_lossy(); + let error = FsServices.read_pcraft(&path).unwrap_err(); + assert!(error.to_string().contains("512 MiB input limit"), "{error}"); + let bytes = FsServices.read_file(&path).unwrap(); + assert_eq!(bytes.len() as u64, super::PCRAFT_MAX_INPUT + 1); + assert!(bytes.starts_with(b"PK\x03\x04")); + drop(bytes); + let _ = std::fs::remove_file(f); + } } diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 58115fd71..1a198d75c 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -255,17 +255,15 @@ fn photocraft_bad_metadata_and_missing_layer_pixels_report_errors() { #[test] #[cfg(unix)] // Sparse length checks exercise the guard without writing half a GiB. fn photocraft_large_files_are_rejected_before_reading() { - for name in ["large-sparse.pcraft", "renamed-sparse.zip"] { - let path = fixture_bytes(name, b"PK\x03\x04".to_vec()); - std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); - assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); - let mut s = Session::default(); - let before = s.project.items.len(); - let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); - assert_eq!(s.project.items.len(), before); - assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); - std::fs::remove_file(path).unwrap(); - } + let path = fixture_bytes("large-sparse.pcraft", b"PK\x03\x04".to_vec()); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(s.project.items.len(), before); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); + std::fs::remove_file(path).unwrap(); } #[test] diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index ad6b1442a..50d5f9e61 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -85,20 +85,17 @@ pub fn is_importable(path: &std::path::Path) -> bool { /// A whole file's bytes, refusing anything that isn't a regular file: a project can name /// `/dev/zero` or a FIFO as footage, and reading those never ends (#2134). pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> { - use std::io::{Read, Seek}; + use std::io::Read; let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - let mut head = [0u8; 4]; - if meta.len() >= 4 { - file.read_exact(&mut head)?; - file.rewind()?; - } - let pcraft = ext_of(path) == "pcraft" || head == *b"PK\x03\x04"; + // Only `.pcraft` files are limited before the read; other ZIP-based files are not. + // A renamed bundle is checked after its read, before it is parsed. + let pcraft = ext_of(path) == "pcraft"; if pcraft && meta.len() > pcraft::MAX_INPUT_BYTES { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit")); } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. @@ -150,4 +147,18 @@ mod read_tests { assert_eq!(super::read_regular_file(&f).unwrap(), b"abc"); let _ = std::fs::remove_file(f); } + + /// Templates and dotLottie files are ZIP archives too: only `.pcraft` files have the + /// 512 MiB input limit. The length is set without writing the data. + #[test] + fn large_zip_files_other_than_photocraft_are_read_whole() { + let f = std::env::temp_dir().join(format!("ec-read-large-{}.zip", std::process::id())); + std::fs::write(&f, b"PK\x03\x04").unwrap(); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(crate::pcraft::MAX_INPUT_BYTES + 1).unwrap(); + let bytes = super::read_regular_file(&f).unwrap(); + assert_eq!(bytes.len() as u64, crate::pcraft::MAX_INPUT_BYTES + 1); + assert!(bytes.starts_with(b"PK\x03\x04")); + drop(bytes); + let _ = std::fs::remove_file(f); + } } diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md index 0599fcfbf..20ebf49b2 100644 --- a/docs/photocraft-import.md +++ b/docs/photocraft-import.md @@ -20,7 +20,7 @@ Use `"importAs":"composition"` for layers. Import uses the existing still-footag ## Limits -PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. +PhotoCraft input is limited to 512 MiB. A `.pcraft` file is checked before it is read. A PhotoCraft bundle with another extension is checked after it is read and before it is parsed. Other ZIP-based files, such as templates and dotLottie files, do not have this limit. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. From b4a18c381ea3e4f4e674d8704a00c424e38b8e3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:25:48 -0800 Subject: [PATCH 06/13] Import: a PDF picked with a PhotoCraft file keeps the Page field Importing a .pcraft file together with a PDF or Illustrator file showed the PhotoCraft dialog without the Page field, so the PDF always imported its first page. The dialog now adds Page when a PDF or Illustrator file is in the import. --- crates/ui-egui/src/panels/forms.rs | 35 +++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index 89efe0ce2..7e12d5a4a 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -516,16 +516,18 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); - ( - "Import PhotoCraft File".into(), - vec![ - Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), - Field::note( - "pcraftNote", - "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", - ), - ], - ) + let mut fields = vec![ + Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), + Field::note( + "pcraftNote", + "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", + ), + ]; + // A PDF or Illustrator file picked with it keeps its Page field. + if is_pdf(p) && !has(p, &["page"]) { + fields.push(Field::num("page", "Page", 1.0)); + } + ("Import PhotoCraft File".into(), fields) } // Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes). Dropped // files start at Settings ▸ Import ▸ Default Drag Import As. @@ -1078,6 +1080,19 @@ mod tests { assert!(app.dialog_state.form.params().get("pcraftNote").is_none()); let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; assert_eq!(options.len(), 2, "Retain Layer Sizes is not offered for canvas-sized PhotoCraft pixels"); + assert!(app.dialog_state.form.params().get("page").is_none(), "no page without a PDF"); + } + } + + #[test] + fn photocraft_import_with_a_pdf_keeps_the_page_field() { + for pdf in ["/picked.pdf", "/picked.ai"] { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let reply = + crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths": ["/picked.pcraft", pdf], "drag": true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import PhotoCraft File"); + assert_eq!(app.dialog_state.form.params()["page"], json!(1.0), "{pdf}"); } } From f76ae41f05a13d017afaa862c239174ecd9ebcbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:06:32 -0800 Subject: [PATCH 07/13] Cargo.lock: list constant_time_eq where cargo sorts it The gate's lockfile check failed because cargo moves the entry ahead of core-foundation 0.9.4. --- Cargo.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bf70392a0..932d79115 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -997,6 +997,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.9.4" @@ -1007,12 +1013,6 @@ dependencies = [ "libc", ] -[[package]] -name = "constant_time_eq" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" - [[package]] name = "core-foundation" version = "0.10.1" From 8e648b3e6fdc8a80eda71e8d01386117113a7a89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:07:13 -0800 Subject: [PATCH 08/13] Import: one PhotoCraft input limit for the engine and media readers The 512 MiB limit is effectcraft_project::PCRAFT_MAX_INPUT. The engine re-exports it and the media reader's limit is defined from it, so the two reads cannot drift apart. Both reads compute their take() limit with saturating_add. --- crates/engine/src/services.rs | 4 ++-- crates/media/src/lib.rs | 2 +- crates/media/src/pcraft.rs | 2 +- crates/project/src/footage.rs | 4 ++++ crates/project/src/lib.rs | 4 +++- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 4bc42baf0..2a641cf41 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -1,7 +1,7 @@ use super::config; /// The largest PhotoCraft bundle [`Services::read_pcraft`] reads. -pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; +pub use effectcraft_project::PCRAFT_MAX_INPUT; /// The error for a PhotoCraft bundle over [`PCRAFT_MAX_INPUT`]. pub fn pcraft_too_large() -> std::io::Error { @@ -130,7 +130,7 @@ fn read_regular_file(path: &str, limit: Option) -> std::io::Result> let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.take(limit.map_or(u64::MAX, |max| max + 1)).read_to_end(&mut bytes)?; + file.take(limit.map_or(u64::MAX, |max| max.saturating_add(1))).read_to_end(&mut bytes)?; if limit.is_some_and(|max| bytes.len() as u64 > max) { return Err(pcraft_too_large()); } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index a6e9e0fb5..02ade4f9b 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -112,7 +112,7 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; if pcraft { - file.take(pcraft::MAX_INPUT_BYTES + 1).read_to_end(&mut bytes)?; + file.take(pcraft::MAX_INPUT_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; if bytes.len() as u64 > pcraft::MAX_INPUT_BYTES { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); } diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs index 220fcd381..ab8b0b74f 100644 --- a/crates/media/src/pcraft.rs +++ b/crates/media/src/pcraft.rs @@ -13,7 +13,7 @@ const MAX_PIXELS: u64 = 16 << 20; // (16 B), two blur images (32 B) and output (16 B), even where lifetimes do not // overlap. Twelve Mi pixels fit within a 1 GiB working-buffer budget (84 B/pixel). const MAX_LAYER_PIXELS: u64 = 12 << 20; -pub(crate) const MAX_INPUT_BYTES: u64 = 512 << 20; +pub(crate) const MAX_INPUT_BYTES: u64 = effectcraft_project::PCRAFT_MAX_INPUT; pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(bytes) == Some(craft_doc::Kind::PhotoCraft) diff --git a/crates/project/src/footage.rs b/crates/project/src/footage.rs index 462772dc4..107e5effc 100644 --- a/crates/project/src/footage.rs +++ b/crates/project/src/footage.rs @@ -49,6 +49,10 @@ impl FieldOrder { /// by this list. pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm", "mxf", "avi"]; +/// The largest PhotoCraft bundle that is read for import, in bytes. The engine's +/// `Services::read_pcraft` and `effectcraft_media`'s file reader both use it. +pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AlphaMode { #[default] diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 9f5f399e0..fe8146b9b 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -40,7 +40,9 @@ mod reach; mod settings; pub use comp::{Comp, Guide, Renderer, Resolution}; -pub use footage::{AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin}; +pub use footage::{ + AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, PCRAFT_MAX_INPUT, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin, +}; pub use item::NO_LAYER; pub use item::{Heard, Item, ItemId, ItemKind, LayerId}; pub use layer::{ From b84130ad63a290897743af7165c27fa070a37268 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 09/13] Import: refuse pass-through groups deeper than the renderer collapses them A pass-through group becomes a precomposition with Collapse Transformations on, and the renderer collapses one only 12 comps deep. A deeper one was flattened, so its layers no longer blended with the layers below the group. Composition import now refuses pass-through groups more than 13 levels deep and suggests Footage, as it does for groups more than 16 levels deep. The renderer's limit is effectcraft_render::MAX_COLLAPSE_DEPTH. --- .../engine/src/interchange/pcraft_import.rs | 14 +++++++++-- crates/engine/src/tests/import_photocraft.rs | 23 +++++++++++++------ crates/render/src/lib.rs | 4 ++++ crates/render/src/pipeline.rs | 2 +- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs index ae3b4e4e0..0f86d2557 100644 --- a/crates/engine/src/interchange/pcraft_import.rs +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -11,6 +11,12 @@ use effectcraft_time::{FrameRate, Tick}; // Each source group becomes a precomposition; match the renderer's nesting limit. const MAX_GROUP_DEPTH: usize = 16; +/// A group whose blend mode is Pass Through: it becomes a precomposition with Collapse +/// Transformations on, so its layers blend with the layers below the group. +fn passes_through(layer: &InputLayer) -> bool { + layer.kind == "group" && layer.blend.as_deref().is_some_and(|b| b.eq_ignore_ascii_case("PassThrough") || b.eq_ignore_ascii_case("Pass Through")) +} + pub(crate) struct Document { outline: Outline, width: u32, @@ -20,7 +26,7 @@ pub(crate) struct Document { /// Metadata only: source pixels remain media and are decoded when a frame needs them, as PSD /// footage is. Bound the number of project items before creating their property groups. pub(crate) fn read(bytes: &[u8]) -> Result { - if bytes.len() as u64 > 512 << 20 { + if bytes.len() as u64 > effectcraft_project::PCRAFT_MAX_INPUT { return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); } fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { @@ -31,6 +37,10 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if depth == MAX_GROUP_DEPTH && layer.kind == "group" { return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); } + // A pass-through group collapses into its parent only this deep in the renderer. + if depth > effectcraft_render::MAX_COLLAPSE_DEPTH && passes_through(layer) { + return Err("PhotoCraft pass-through groups exceed 13 levels; import as Footage for the saved composite".into()); + } *nodes += 1; if *nodes > 4096 { return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); @@ -147,7 +157,7 @@ fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[In opacity.value = Value::Scalar(f64::from(input.opacity.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0); } if let Some(blend) = input.blend.as_deref() { - if input.kind == "group" && (blend.eq_ignore_ascii_case("PassThrough") || blend.eq_ignore_ascii_case("Pass Through")) { + if passes_through(input) { layer.switches.collapse = true; } else if let Some(mode) = BlendMode::from_name(blend) { layer.blend_mode = mode; diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 1a198d75c..b5926aa83 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -290,7 +290,16 @@ fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { #[test] fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { - for (depth, blend) in [(16, "Normal"), (16, "PassThrough"), (17, "Normal"), (17, "PassThrough")] { + // Pass-through groups collapse into their parents only 13 levels deep in the renderer, so a + // deeper one is refused instead of blending as a flattened group. + let cases = [ + (16, "Normal", None), + (13, "PassThrough", None), + (14, "PassThrough", Some("13 levels")), + (17, "Normal", Some("16 levels")), + (17, "PassThrough", Some("13 levels")), + ]; + for (depth, blend, refused) in cases { let mut layers = json!([layer("Deep pixels", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")}))]); for index in 0..depth { layers = json!([layer(&format!("Group {index}"), true, 1.0, blend, json!({"kind":"group","children":layers}))]); @@ -299,15 +308,15 @@ fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; let before = s.project.items.len(); let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); - if depth == 16 { - let comp = ItemId(result["comps"][0].as_u64().unwrap()); - assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0]); - } else { + if let Some(levels) = refused { assert_eq!(s.project.items.len(), before, "unsupported nesting must not create a composition with disappearing artwork"); assert!( - result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("16 levels") && e.contains("Footage"))), - "{result}" + result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains(levels) && e.contains("Footage"))), + "{depth} {blend}: {result}" ); + } else { + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0], "{depth} {blend}"); } std::fs::remove_file(path).unwrap(); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1a3822f48..1b81a7e5c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -63,6 +63,10 @@ pub use opts::{LayerTiming, RenderOpts}; use opts::{MAX_THROUGH, Through}; pub use pipeline::{Collapsed, FootagePicture, MediaOverride, PropertyOverride}; +/// The deepest nested comp whose precomp layers still collapse their transformations: a layer +/// with Collapse Transformations in a comp nested deeper than this is rendered flattened. +pub const MAX_COLLAPSE_DEPTH: usize = 12; + pub struct Renderer<'a> { pub project: &'a Project, pub footage: &'a dyn FootageSource, diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 042dc198c..a57771363 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -357,7 +357,7 @@ impl<'a> Renderer<'a> { /// Properties overrides travel with it and are applied as the nested layers are evaluated, /// so the nested comp is not rasterised at its frame. pub fn collapsed(&self, ctx: &EvalCtx, layer: &Layer) -> Option { - if !layer.switches.collapse || layer.switches.adjustment || self.depth > 12 { + if !layer.switches.collapse || layer.switches.adjustment || self.depth > super::MAX_COLLAPSE_DEPTH { return None; } let LayerSource::Comp { item } = &layer.source else { return None }; From 8e1defea9365f081ad8e0482a907bb2feca599ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:20:23 -0800 Subject: [PATCH 10/13] Import: test the PhotoCraft input limit without reading 512 MiB The two tests of the 512 MiB limit read a sparse file one byte over it into memory to show that other ZIP-based files are read whole. They now check the limit from the file's length alone and read a 4-byte file: the engine test reads it with and without a smaller limit, and the media reader's limit comes from input_limit, which gives the limit for .pcraft files only. --- crates/engine/src/services.rs | 15 ++++++++------ crates/media/src/lib.rs | 39 +++++++++++++++++++++++------------ 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 2a641cf41..ebbe4c3d4 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -173,19 +173,22 @@ mod tests { } /// Templates and dotLottie files are ZIP archives too: only PhotoCraft reads have the - /// 512 MiB input limit. The length is set without writing the data. + /// 512 MiB input limit. A file over it is refused from its length, which is set without + /// writing the data, so nothing is read; the same read with a smaller limit, and with none, + /// shows where the limit applies. #[test] fn only_photocraft_reads_have_the_input_limit() { let f = std::env::temp_dir().join(format!("ec-services-large-{}.zip", std::process::id())); std::fs::write(&f, b"PK\x03\x04").unwrap(); std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(super::PCRAFT_MAX_INPUT + 1).unwrap(); - let path = f.to_string_lossy(); + let path = f.to_string_lossy().to_string(); let error = FsServices.read_pcraft(&path).unwrap_err(); assert!(error.to_string().contains("512 MiB input limit"), "{error}"); - let bytes = FsServices.read_file(&path).unwrap(); - assert_eq!(bytes.len() as u64, super::PCRAFT_MAX_INPUT + 1); - assert!(bytes.starts_with(b"PK\x03\x04")); - drop(bytes); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(4).unwrap(); + assert_eq!(FsServices.read_file(&path).unwrap(), b"PK\x03\x04"); + assert_eq!(FsServices.read_pcraft(&path).unwrap(), b"PK\x03\x04"); + assert!(super::read_regular_file(&path, Some(3)).is_err(), "one byte over a limit"); + assert_eq!(super::read_regular_file(&path, None).unwrap(), b"PK\x03\x04"); let _ = std::fs::remove_file(f); } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 02ade4f9b..7eff0e9cf 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -102,18 +102,17 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - // Only `.pcraft` files are limited before the read; other ZIP-based files are not. // A renamed bundle is checked after its read, before it is parsed. - let pcraft = ext_of(path) == "pcraft"; - if pcraft && meta.len() > pcraft::MAX_INPUT_BYTES { + let limit = input_limit(path); + if limit.is_some_and(|max| meta.len() > max) { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit")); } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - if pcraft { - file.take(pcraft::MAX_INPUT_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; - if bytes.len() as u64 > pcraft::MAX_INPUT_BYTES { + if let Some(max) = limit { + file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); } } else { @@ -122,6 +121,12 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu Ok((bytes, effectcraft_render::reads::FileStamp::of_metadata(&meta))) } +/// The most bytes a read of `path` takes before it fails: `.pcraft` files have the PhotoCraft +/// input limit; other files, ZIP-based templates and dotLottie files included, have none. +fn input_limit(path: &std::path::Path) -> Option { + (ext_of(path) == "pcraft").then_some(pcraft::MAX_INPUT_BYTES) +} + #[cfg(test)] static OPENS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -175,16 +180,24 @@ mod read_tests { } /// Templates and dotLottie files are ZIP archives too: only `.pcraft` files have the - /// 512 MiB input limit. The length is set without writing the data. + /// 512 MiB input limit. A `.pcraft` file over it is refused from its length, which is set + /// without writing the data, so nothing is read. #[test] fn large_zip_files_other_than_photocraft_are_read_whole() { - let f = std::env::temp_dir().join(format!("ec-read-large-{}.zip", std::process::id())); + let max = crate::pcraft::MAX_INPUT_BYTES; + for name in ["a.zip", "a.lottie", "a.json", "a"] { + assert_eq!(super::input_limit(std::path::Path::new(name)), None, "{name}"); + } + for name in ["a.pcraft", "a.PCraft"] { + assert_eq!(super::input_limit(std::path::Path::new(name)), Some(max), "{name}"); + } + let f = std::env::temp_dir().join(format!("ec-read-large-{}.pcraft", std::process::id())); std::fs::write(&f, b"PK\x03\x04").unwrap(); - std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(crate::pcraft::MAX_INPUT_BYTES + 1).unwrap(); - let bytes = super::read_regular_file(&f).unwrap(); - assert_eq!(bytes.len() as u64, crate::pcraft::MAX_INPUT_BYTES + 1); - assert!(bytes.starts_with(b"PK\x03\x04")); - drop(bytes); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(max + 1).unwrap(); + let error = super::read_regular_file(&f).unwrap_err(); + assert!(error.to_string().contains("512 MiB input limit"), "{error}"); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(4).unwrap(); + assert_eq!(super::read_regular_file(&f).unwrap(), b"PK\x03\x04"); let _ = std::fs::remove_file(f); } } From b83fced573bdc7615a61443e47eb53d176c219dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 23:57:37 -0800 Subject: [PATCH 11/13] Import: keep the PhotoCraft note when a Photoshop file is picked with it When a selection holds a .pcraft file together with a .psd or .psb file, the Import Photoshop File dialog now shows the PhotoCraft compatibility note under its Import Kind choices. The note text moves into one helper that both Import dialogs use. --- crates/ui-egui/src/panels/forms.rs | 36 +++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index fc0dc8f26..c50ac1fef 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -505,6 +505,11 @@ fn transform_form(p: &Value, layer: Option<&effectcraft_engine::project::Layer>, (title.into(), fields) } +/// The Import dialog's note on how a PhotoCraft file imports as a composition. +fn pcraft_note() -> Field { + Field::note("pcraftNote", "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.") +} + /// If `id` is a dialog command invoked without its parameters, open its form and return true. pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { let s = &app.session; @@ -517,13 +522,8 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); - let mut fields = vec![ - Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), - Field::note( - "pcraftNote", - "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", - ), - ]; + let mut fields = + vec![Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), pcraft_note()]; // A PDF or Illustrator file picked with it keeps its Page field. if is_pdf(p) && !has(p, &["page"]) { fields.push(Field::num("page", "Page", 1.0)); @@ -537,7 +537,10 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { [("Footage", json!("footage")), ("Composition", json!("composition")), ("Composition - Retain Layer Sizes", json!("compositionLayerSizes"))]; let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = if drag { kinds.iter().position(|(_, v)| v.as_str() == Some(s.prefs.drag_import_as())).unwrap_or(0) } else { 1 }; - ("Import Photoshop File".into(), vec![Field::choice("importAs", "Import Kind", &kinds, sel)]) + let mut fields = vec![Field::choice("importAs", "Import Kind", &kinds, sel)]; + // A PhotoCraft file picked with it keeps its compatibility note. + fields.extend(imports_ext(p, &["pcraft"]).then(pcraft_note)); + ("Import Photoshop File".into(), fields) } // PDF / Illustrator files: Import Kind and the page. "file.import" if !has(p, &["importAs", "page"]) && is_pdf(p) => ( @@ -1098,6 +1101,23 @@ mod tests { } } + #[test] + fn photocraft_import_with_a_photoshop_file_keeps_the_note() { + let has_note = |paths: Value| { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let reply = crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths": paths, "drag": true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import Photoshop File"); + let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; + assert_eq!(options.len(), 3); + app.dialog_state.form.fields.iter().any(|f| f.key == "pcraftNote") + }; + for psd in ["/picked.psd", "/picked.psb"] { + assert!(has_note(json!(["/picked.pcraft", psd])), "{psd}"); + assert!(!has_note(json!([psd])), "{psd}"); + } + } + #[test] fn renderer_form_keeps_descriptive_labels_and_stable_option_values() { crate::i18n::set_current("en"); From 681b2c7468ecc5fea096280111d8c2974fdc4bd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:29:17 -0800 Subject: [PATCH 12/13] Import: report PhotoCraft composition notes as warnings A PhotoCraft document that imports as a composition now returns its notes in the result's `warnings` instead of `errors`, so a successful import no longer reports a failure. With `background`, the notes are shown and returned when the job starts, since the composition stays in the project when the footage job is canceled. --- crates/engine/src/cmd/file.rs | 23 +++++++++++++++----- crates/engine/src/tests/import_photocraft.rs | 22 ++++++++++++++++++- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9feafe25f..f1f542135 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -144,6 +144,13 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { }; let p = p.clone(); let immediate_errors = pending.errors.clone(); + // Compositions made during preparation stay when the job is canceled, so their notes are + // shown now and returned in both results. + let immediate_warnings = std::mem::take(&mut pending.warnings); + for w in &immediate_warnings { + s.events.push(crate::Event::Toast { message: w.clone(), error: true }); + } + let job_warnings = immediate_warnings.clone(); let mut result = s.spawn_task("import", label, false, move |ctl| { let mut probed = Vec::with_capacity(total); for (k, src) in sources.iter().enumerate() { @@ -157,6 +164,9 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { let apply: crate::jobs::Apply = Box::new(move |s: &mut Session| { let made = pending.comps.len() + probed.iter().filter(|r| r.is_ok()).count(); let mut r = add_footage(s, pending, probed)?; + if let Some(w) = r.get_mut("warnings").and_then(Value::as_array_mut) { + w.splice(0..0, job_warnings.into_iter().map(Value::from)); + } finish_import(s, &mut r, target, &p); let mut toast = format!("Imported {made} item{}", if made == 1 { "" } else { "s" }); let errors: Vec<&str> = r["errors"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); @@ -174,6 +184,7 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { // Report those failures now as well as in the eventual job result. if result["started"] == true { result["errors"] = json!(immediate_errors); + result["warnings"] = json!(immediate_warnings); } return Ok(result); } @@ -281,6 +292,8 @@ struct PendingImport { comps: Vec, items: Vec, errors: Vec, + /// Notes about compositions that imported, such as what a PhotoCraft composition leaves out. + warnings: Vec, /// EffectCraft projects merged in (`file.importProject` results); never added to a comp. projects: Vec, } @@ -427,6 +440,7 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { let mut comps = vec![]; let mut items = vec![]; let mut errors = vec![]; + let mut warnings = vec![]; // EffectCraft projects import as projects, as After Effects imports an .aep; so do After // Effects projects, refused when parts of them cannot come over. The app asks about those // before it gets here (`panels::aep_losses`); a script or agent gets the refusal. @@ -460,10 +474,10 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { let bytes = match read { Ok(b) if pcraft || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { match import_pcraft_comp(s, &path, &b, retain) { - Ok((comp, made, warnings)) => { + Ok((comp, made, notes)) => { comps.push(comp); items.extend(made); - errors.extend(warnings); + warnings.extend(notes); } Err(e) => errors.push(format!("{path}: {e}")), } @@ -526,15 +540,14 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { page, psd_layer: p.get("layer").cloned(), }; - Ok(PendingImport { sources, prober, comps, items, errors, projects }) + Ok(PendingImport { sources, prober, comps, items, errors, warnings, projects }) } /// The last part of an import: add the probed files to the project (one undo step) and select /// everything the import made, so the Project panel shows it. fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec>) -> Result { - let PendingImport { comps, mut items, mut errors, projects, .. } = pending; + let PendingImport { comps, mut items, mut errors, mut warnings, projects, .. } = pending; let mut found = vec![]; - let mut warnings = vec![]; for r in probed { match r { Ok(f) => { diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index b5926aa83..4359b4b98 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -86,7 +86,11 @@ fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { let before = s.project.items.len(); let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); assert_eq!(r["comps"].as_array().unwrap().len(), 1, "{r}"); - assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), "{r}"); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + assert!( + r["warnings"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), + "{r}" + ); let cid = ItemId(r["comps"][0].as_u64().unwrap()); let c = s.project.comp(cid).unwrap(); assert_eq!((c.width, c.height), (8, 6)); @@ -119,6 +123,22 @@ fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { std::fs::remove_file(path).unwrap(); } +#[test] +fn photocraft_composition_notes_arrive_before_a_background_footage_job() { + let layered = fixture("background-layered.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")}))])); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let still = fixture_bytes("background-still.png", png.into_inner()); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[layered, still],"importAs":"composition","background":true})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let notes = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("Some masks, effects and profiles"))); + assert!(notes(&r), "the composition already exists, so a canceled job must not hide its notes: {r}"); + s.execute("jobs.wait", json!({})).unwrap(); + std::fs::remove_file(layered).unwrap(); + std::fs::remove_file(still).unwrap(); +} + #[test] fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { struct Metadata(bool); From 99c7e172b08f1c8f929763aeb50d6cce6e6bbdd9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:12:14 -0800 Subject: [PATCH 13/13] Import: show PhotoCraft composition notes as a notice, not an error The notes about a PhotoCraft composition that was already added now go to the window as one non-error notice. With several compositions the notice leads with the first note and a count of the rest, and the finished import's toast repeats the notes. Both command results keep the warnings as before. --- crates/engine/src/cmd/file.rs | 16 ++++++-- crates/engine/src/tests/import_photocraft.rs | 43 ++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f1f542135..72a2510a6 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -145,10 +145,17 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { let p = p.clone(); let immediate_errors = pending.errors.clone(); // Compositions made during preparation stay when the job is canceled, so their notes are - // shown now and returned in both results. + // shown now and returned in both results. The window keeps one notice at a time and shows + // its first line, so they go in one notice led by a summary, and the finished job's toast + // repeats them. let immediate_warnings = std::mem::take(&mut pending.warnings); - for w in &immediate_warnings { - s.events.push(crate::Event::Toast { message: w.clone(), error: true }); + let notes = match immediate_warnings.as_slice() { + [] => String::new(), + [one] => one.clone(), + [first, rest @ ..] => format!("{first} (and {} more)\n{}", rest.len(), immediate_warnings.join("\n")), + }; + if !notes.is_empty() { + s.events.push(crate::Event::Toast { message: notes.clone(), error: false }); } let job_warnings = immediate_warnings.clone(); let mut result = s.spawn_task("import", label, false, move |ctl| { @@ -175,6 +182,9 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { [one] => toast = format!("{toast}. {one}"), [first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)\n{}", rest.len(), errors.join("\n")), } + if !notes.is_empty() { + toast = if errors.is_empty() { format!("{toast}. {notes}") } else { format!("{toast}\n{notes}") }; + } r["toast"] = json!(toast); Ok(r) }); diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 4359b4b98..b135774c5 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -134,11 +134,54 @@ fn photocraft_composition_notes_arrive_before_a_background_footage_job() { assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); let notes = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("Some masks, effects and profiles"))); assert!(notes(&r), "the composition already exists, so a canceled job must not hide its notes: {r}"); + let toast = s.drain_events().into_iter().find_map(|e| match e { + crate::Event::Toast { message, error } if message.contains("Some masks, effects and profiles") => Some(error), + _ => None, + }); + assert_eq!(toast, Some(false), "the composition was imported, so its notes are shown as a notice, not an error"); s.execute("jobs.wait", json!({})).unwrap(); + let done = s.drain_events().into_iter().find_map(|e| match e { + crate::Event::Toast { message, error } if message.starts_with("Imported") => Some((message, error)), + _ => None, + }); + let (done, error) = done.expect("the finished job shows its own toast"); + assert!(!error, "{done}"); + let shown = done.lines().next().unwrap_or_default(); + assert!( + shown.contains("Some masks, effects and profiles"), + "the job's toast replaces the notice in the window, so its first line repeats the notes: {done}" + ); std::fs::remove_file(layered).unwrap(); std::fs::remove_file(still).unwrap(); } +#[test] +fn photocraft_composition_notes_from_several_files_share_one_notice() { + let first = fixture("background-first.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")}))])); + let second = fixture("background-second.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("00ff00ff")}))])); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let still = fixture_bytes("background-third.png", png.into_inner()); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[first, second, still],"importAs":"composition","background":true})).unwrap(); + assert_eq!(r["warnings"].as_array().unwrap().len(), 2, "{r}"); + let notices: Vec = s + .drain_events() + .into_iter() + .filter_map(|e| match e { + crate::Event::Toast { message, error: false } => Some(message), + _ => None, + }) + .collect(); + let [notice] = notices.as_slice() else { panic!("one notice for both compositions: {notices:?}") }; + assert!(notice.lines().next().unwrap_or_default().ends_with("(and 1 more)"), "the shown line says another note is on hover: {notice}"); + assert_eq!(notice.lines().count(), 3, "{notice}"); + s.execute("jobs.wait", json!({})).unwrap(); + for path in [first, second, still] { + std::fs::remove_file(path).unwrap(); + } +} + #[test] fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { struct Metadata(bool);