Import: read PhotoCraft composites and saved layer pixels

This commit is contained in:
dotCooCoo committed 2026-11-02 22:44:46 -08:00
1 parent 7870b5916a
commit a2e2409608
23 files changed
+829 -18

No files matched your search

Generated
+66 -1
View File
@@ -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"
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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,
+6 -1
View File
@@ -114,8 +114,13 @@ pub struct WebServices;
impl Services for WebServices {
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
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());
+4
View File
@@ -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 }
+52 -2
View File
@@ -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<PendingImport> {
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<PendingImport> {
}
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<std::result:
/// definition, OpenEXR premultiplied); TGA, TIFF and movies with alpha don't.
fn alpha_is_labeled(path: &str, codec: &str) -> 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<u64>, Vec<String>)> {
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<CommandSpec> {
"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
),
+1 -1
View File
@@ -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"];
+1 -1
View File
@@ -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
+1
View File
@@ -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;
@@ -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<Document, String> {
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<ItemId>,
pub warnings: Vec<String>,
}
struct Context<'a> {
doc: &'a Document,
path: &'a str,
folder: ItemId,
rate: FrameRate,
duration: Tick,
next: u32,
items: Vec<ItemId>,
warnings: Vec<String>,
}
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<ItemId>, 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
}
+21 -2
View File
@@ -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<Vec<u8>> {
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<()> {
+1
View File
@@ -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;
@@ -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_project::Footage, String> {
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<u8> {
bundle_sized(layers, (8, 6))
}
fn bundle_sized(layers: Value, size: (u32, u32)) -> Vec<u8> {
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<u8>) -> 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();
}
}
+1
View File
@@ -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 }
+15
View File
@@ -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 {
+7 -1
View File
@@ -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<Option<Footage>> {
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<Option<Footage>> {
/// Decode a Photoshop or SVG still (`None` for other formats).
pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result<Option<Image>> {
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.
+22 -4
View File
@@ -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<filmcraft_media::MediaError> 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<Vec<u8>> {
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)
}
+170
View File
@@ -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<Vec<u8>> {
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<Footage> {
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<Vec<usize>> {
fn find(layers: &[Layer], wanted: u32, next: &mut u32, path: &mut Vec<usize>, depth: usize) -> Option<Vec<usize>> {
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<Image> {
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<Image> {
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 })
}
+1 -1
View File
@@ -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::<Vec<_>>();
// A host whose blocking dialogs are unsafe inside this frame shows the dialog without
+4 -1
View File
@@ -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:?}");
}
}
}
+29
View File
@@ -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<Field>) = 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 {
+1 -1
View File
@@ -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,
+25
View File
@@ -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.